blob: bb0e0996bf27074e7de636e7fbd1889e68cb81dc [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman089efff2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14// This pass combines things like:
15// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
17// into:
18// %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
25// 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.
27// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
29// 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.
32// ... etc.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Scalar.h"
38#include "llvm/IntrinsicInst.h"
Owen Anderson24be4c12009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/Pass.h"
41#include "llvm/DerivedTypes.h"
42#include "llvm/GlobalVariable.h"
Dan Gohman9545fb02009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandez48c3c542009-09-18 22:35:49 +000045#include "llvm/Analysis/MallocHelper.h"
Chris Lattnera432bc72008-06-02 01:18:21 +000046#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047#include "llvm/Target/TargetData.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
50#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000051#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000053#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000054#include "llvm/Support/GetElementPtrTypeIterator.h"
55#include "llvm/Support/InstVisitor.h"
Chris Lattnerc7694852009-08-30 07:44:24 +000056#include "llvm/Support/IRBuilder.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057#include "llvm/Support/MathExtras.h"
58#include "llvm/Support/PatternMatch.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000059#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000060#include "llvm/ADT/DenseMap.h"
61#include "llvm/ADT/SmallVector.h"
62#include "llvm/ADT/SmallPtrSet.h"
63#include "llvm/ADT/Statistic.h"
64#include "llvm/ADT/STLExtras.h"
65#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000066#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000067using namespace llvm;
68using namespace llvm::PatternMatch;
69
70STATISTIC(NumCombined , "Number of insts combined");
71STATISTIC(NumConstProp, "Number of constant folds");
72STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74STATISTIC(NumSunkInst , "Number of instructions sunk");
75
76namespace {
Chris Lattner5119c702009-08-30 05:55:36 +000077 /// InstCombineWorklist - This is the worklist management logic for
78 /// InstCombine.
79 class InstCombineWorklist {
80 SmallVector<Instruction*, 256> Worklist;
81 DenseMap<Instruction*, unsigned> WorklistMap;
82
83 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
84 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
85 public:
86 InstCombineWorklist() {}
87
88 bool isEmpty() const { return Worklist.empty(); }
89
90 /// Add - Add the specified instruction to the worklist if it isn't already
91 /// in it.
92 void Add(Instruction *I) {
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000093 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
94 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner5119c702009-08-30 05:55:36 +000095 Worklist.push_back(I);
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000096 }
Chris Lattner5119c702009-08-30 05:55:36 +000097 }
98
Chris Lattnerc5ad98f2009-08-30 06:27:41 +000099 void AddValue(Value *V) {
100 if (Instruction *I = dyn_cast<Instruction>(V))
101 Add(I);
102 }
103
Chris Lattner3183fb62009-08-30 06:13:40 +0000104 // Remove - remove I from the worklist if it exists.
Chris Lattner5119c702009-08-30 05:55:36 +0000105 void Remove(Instruction *I) {
106 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
107 if (It == WorklistMap.end()) return; // Not in worklist.
108
109 // Don't bother moving everything down, just null out the slot.
110 Worklist[It->second] = 0;
111
112 WorklistMap.erase(It);
113 }
114
115 Instruction *RemoveOne() {
116 Instruction *I = Worklist.back();
117 Worklist.pop_back();
118 WorklistMap.erase(I);
119 return I;
120 }
121
Chris Lattner4796b622009-08-30 06:22:51 +0000122 /// AddUsersToWorkList - When an instruction is simplified, add all users of
123 /// the instruction to the work lists because they might get more simplified
124 /// now.
125 ///
126 void AddUsersToWorkList(Instruction &I) {
127 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
128 UI != UE; ++UI)
129 Add(cast<Instruction>(*UI));
130 }
131
Chris Lattner5119c702009-08-30 05:55:36 +0000132
133 /// Zap - check that the worklist is empty and nuke the backing store for
134 /// the map if it is large.
135 void Zap() {
136 assert(WorklistMap.empty() && "Worklist empty, but map not?");
137
138 // Do an explicit clear, this shrinks the map if needed.
139 WorklistMap.clear();
140 }
141 };
142} // end anonymous namespace.
143
144
145namespace {
Chris Lattnerc7694852009-08-30 07:44:24 +0000146 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
147 /// just like the normal insertion helper, but also adds any new instructions
148 /// to the instcombine worklist.
149 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
150 InstCombineWorklist &Worklist;
151 public:
152 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
153
154 void InsertHelper(Instruction *I, const Twine &Name,
155 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
156 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
157 Worklist.Add(I);
158 }
159 };
160} // end anonymous namespace
161
162
163namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000164 class InstCombiner : public FunctionPass,
165 public InstVisitor<InstCombiner, Instruction*> {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166 TargetData *TD;
167 bool MustPreserveLCSSA;
Chris Lattner21d79e22009-08-31 06:57:37 +0000168 bool MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169 public:
Chris Lattner36ec3b42009-08-30 17:53:59 +0000170 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner3183fb62009-08-30 06:13:40 +0000171 InstCombineWorklist Worklist;
172
Chris Lattnerc7694852009-08-30 07:44:24 +0000173 /// Builder - This is an IRBuilder that automatically inserts new
174 /// instructions into the worklist when they are created.
Chris Lattnerad7516a2009-08-30 18:50:58 +0000175 typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
176 BuilderTy *Builder;
Chris Lattnerc7694852009-08-30 07:44:24 +0000177
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000178 static char ID; // Pass identification, replacement for typeid
Chris Lattnerc7694852009-08-30 07:44:24 +0000179 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180
Owen Anderson175b6542009-07-22 00:24:57 +0000181 LLVMContext *Context;
182 LLVMContext *getContext() const { return Context; }
Owen Anderson24be4c12009-07-03 00:17:18 +0000183
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184 public:
185 virtual bool runOnFunction(Function &F);
186
187 bool DoOneIteration(Function &F, unsigned ItNum);
188
189 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190 AU.addPreservedID(LCSSAID);
191 AU.setPreservesCFG();
192 }
193
Dan Gohmana80e2712009-07-21 23:21:54 +0000194 TargetData *getTargetData() const { return TD; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195
196 // Visitation implementation - Implement instruction combining for different
197 // instruction types. The semantics are as follows:
198 // Return Value:
199 // null - No change was made
200 // I - Change was made, I is still valid, I may be dead though
201 // otherwise - Change was made, replace I with returned instruction
202 //
203 Instruction *visitAdd(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000204 Instruction *visitFAdd(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000206 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000207 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000208 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000209 Instruction *visitURem(BinaryOperator &I);
210 Instruction *visitSRem(BinaryOperator &I);
211 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000212 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 Instruction *commonRemTransforms(BinaryOperator &I);
214 Instruction *commonIRemTransforms(BinaryOperator &I);
215 Instruction *commonDivTransforms(BinaryOperator &I);
216 Instruction *commonIDivTransforms(BinaryOperator &I);
217 Instruction *visitUDiv(BinaryOperator &I);
218 Instruction *visitSDiv(BinaryOperator &I);
219 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000220 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +0000221 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000223 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner57e66fa2009-07-23 05:46:22 +0000224 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000225 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000226 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227 Instruction *visitOr (BinaryOperator &I);
228 Instruction *visitXor(BinaryOperator &I);
229 Instruction *visitShl(BinaryOperator &I);
230 Instruction *visitAShr(BinaryOperator &I);
231 Instruction *visitLShr(BinaryOperator &I);
232 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000233 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
234 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235 Instruction *visitFCmpInst(FCmpInst &I);
236 Instruction *visitICmpInst(ICmpInst &I);
237 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
238 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
239 Instruction *LHS,
240 ConstantInt *RHS);
241 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
242 ConstantInt *DivRHS);
243
Dan Gohman17f46f72009-07-28 01:40:03 +0000244 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245 ICmpInst::Predicate Cond, Instruction &I);
246 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
247 BinaryOperator &I);
248 Instruction *commonCastTransforms(CastInst &CI);
249 Instruction *commonIntCastTransforms(CastInst &CI);
250 Instruction *commonPointerCastTransforms(CastInst &CI);
251 Instruction *visitTrunc(TruncInst &CI);
252 Instruction *visitZExt(ZExtInst &CI);
253 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000254 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000256 Instruction *visitFPToUI(FPToUIInst &FI);
257 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000258 Instruction *visitUIToFP(CastInst &CI);
259 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000260 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000261 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 Instruction *visitBitCast(BitCastInst &CI);
263 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
264 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000265 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman58c09632008-09-16 18:46:06 +0000266 Instruction *visitSelectInst(SelectInst &SI);
267 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268 Instruction *visitCallInst(CallInst &CI);
269 Instruction *visitInvokeInst(InvokeInst &II);
270 Instruction *visitPHINode(PHINode &PN);
271 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
272 Instruction *visitAllocationInst(AllocationInst &AI);
273 Instruction *visitFreeInst(FreeInst &FI);
274 Instruction *visitLoadInst(LoadInst &LI);
275 Instruction *visitStoreInst(StoreInst &SI);
276 Instruction *visitBranchInst(BranchInst &BI);
277 Instruction *visitSwitchInst(SwitchInst &SI);
278 Instruction *visitInsertElementInst(InsertElementInst &IE);
279 Instruction *visitExtractElementInst(ExtractElementInst &EI);
280 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000281 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282
283 // visitInstruction - Specify what to return for unhandled instructions...
284 Instruction *visitInstruction(Instruction &I) { return 0; }
285
286 private:
287 Instruction *visitCallSite(CallSite CS);
288 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000289 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000290 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
291 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000292 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000293 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
294
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295
296 public:
297 // InsertNewInstBefore - insert an instruction New before instruction Old
298 // in the program. Add the new instruction to the worklist.
299 //
300 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
301 assert(New && New->getParent() == 0 &&
302 "New instruction already inserted into a basic block!");
303 BasicBlock *BB = Old.getParent();
304 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner3183fb62009-08-30 06:13:40 +0000305 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000306 return New;
307 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000308
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 // ReplaceInstUsesWith - This method is to be used when an instruction is
310 // found to be dead, replacable with another preexisting expression. Here
311 // we add all uses of I to the worklist, replace all uses of I with the new
312 // value, then return I, so that the inst combiner will know that I was
313 // modified.
314 //
315 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner4796b622009-08-30 06:22:51 +0000316 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +0000317
318 // If we are replacing the instruction with itself, this must be in a
319 // segment of unreachable code, so just clobber the instruction.
320 if (&I == V)
321 V = UndefValue::get(I.getType());
322
323 I.replaceAllUsesWith(V);
324 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325 }
326
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327 // EraseInstFromFunction - When dealing with an instruction that has side
328 // effects or produces a void value, we can't rely on DCE to delete the
329 // instruction. Instead, visit methods should return the value returned by
330 // this function.
331 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez48c3c542009-09-18 22:35:49 +0000332 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner26b7f942009-08-31 05:17:58 +0000333
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner3183fb62009-08-30 06:13:40 +0000335 // Make sure that we reprocess all operands now that we reduced their
336 // use counts.
Chris Lattnerc5ad98f2009-08-30 06:27:41 +0000337 if (I.getNumOperands() < 8) {
338 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
339 if (Instruction *Op = dyn_cast<Instruction>(*i))
340 Worklist.Add(Op);
341 }
Chris Lattner3183fb62009-08-30 06:13:40 +0000342 Worklist.Remove(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343 I.eraseFromParent();
Chris Lattner21d79e22009-08-31 06:57:37 +0000344 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345 return 0; // Don't do anything with FI
346 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000347
348 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
349 APInt &KnownOne, unsigned Depth = 0) const {
350 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
351 }
352
353 bool MaskedValueIsZero(Value *V, const APInt &Mask,
354 unsigned Depth = 0) const {
355 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
356 }
357 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
358 return llvm::ComputeNumSignBits(Op, TD, Depth);
359 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360
361 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000362
363 /// SimplifyCommutative - This performs a few simplifications for
364 /// commutative operators.
365 bool SimplifyCommutative(BinaryOperator &I);
366
367 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
368 /// most-complex to least-complex order.
369 bool SimplifyCompare(CmpInst &I);
370
Chris Lattner676c78e2009-01-31 08:15:18 +0000371 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
372 /// based on the demanded bits.
373 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
374 APInt& KnownZero, APInt& KnownOne,
375 unsigned Depth);
376 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000378 unsigned Depth=0);
379
380 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
381 /// SimplifyDemandedBits knows about. See if the instruction has any
382 /// properties that allow us to simplify its operands.
383 bool SimplifyDemandedInstructionBits(Instruction &Inst);
384
Evan Cheng63295ab2009-02-03 10:05:09 +0000385 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
386 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000387
Chris Lattnerf7843b72009-09-27 19:57:57 +0000388 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
389 // which has a PHI node as operand #0, see if we can fold the instruction
390 // into the PHI (which is only possible if all operands to the PHI are
391 // constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +0000392 //
393 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
394 // that would normally be unprofitable because they strongly encourage jump
395 // threading.
396 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397
398 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
399 // operator and they all are only used by the PHI, PHI together their
400 // inputs, and do the operation once, to the result of the PHI.
401 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
402 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000403 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
404
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405
406 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
407 ConstantInt *AndRHS, BinaryOperator &TheAnd);
408
409 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
410 bool isSub, Instruction &I);
411 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
412 bool isSigned, bool Inside, Instruction &IB);
413 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
414 Instruction *MatchBSwap(BinaryOperator &I);
415 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000416 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000417 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000418
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419
420 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000421
Dan Gohman8fd520a2009-06-15 22:12:54 +0000422 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000423 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000424 unsigned GetOrEnforceKnownAlignment(Value *V,
425 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000426
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000427 };
Chris Lattner5119c702009-08-30 05:55:36 +0000428} // end anonymous namespace
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000429
Dan Gohman089efff2008-05-13 00:00:25 +0000430char InstCombiner::ID = 0;
431static RegisterPass<InstCombiner>
432X("instcombine", "Combine redundant instructions");
433
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434// getComplexity: Assign a complexity or rank value to LLVM Values...
435// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman5d138f92009-08-29 23:39:38 +0000436static unsigned getComplexity(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000437 if (isa<Instruction>(V)) {
Owen Anderson76f49252009-07-13 22:18:28 +0000438 if (BinaryOperator::isNeg(V) ||
439 BinaryOperator::isFNeg(V) ||
Dan Gohman7ce405e2009-06-04 22:49:04 +0000440 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441 return 3;
442 return 4;
443 }
444 if (isa<Argument>(V)) return 3;
445 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
446}
447
448// isOnlyUse - Return true if this instruction will be deleted if we stop using
449// it.
450static bool isOnlyUse(Value *V) {
451 return V->hasOneUse() || isa<Constant>(V);
452}
453
454// getPromotedType - Return the specified type promoted as it would be to pass
455// though a va_arg area...
456static const Type *getPromotedType(const Type *Ty) {
457 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
458 if (ITy->getBitWidth() < 32)
Owen Anderson35b47072009-08-13 21:58:54 +0000459 return Type::getInt32Ty(Ty->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460 }
461 return Ty;
462}
463
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000464/// getBitCastOperand - If the specified operand is a CastInst, a constant
465/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
466/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000468 if (Operator *O = dyn_cast<Operator>(V)) {
469 if (O->getOpcode() == Instruction::BitCast)
470 return O->getOperand(0);
471 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
472 if (GEP->hasAllZeroIndices())
473 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000474 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000475 return 0;
476}
477
478/// This function is a wrapper around CastInst::isEliminableCastPair. It
479/// simply extracts arguments and returns what that function returns.
480static Instruction::CastOps
481isEliminableCastPair(
482 const CastInst *CI, ///< The first cast instruction
483 unsigned opcode, ///< The opcode of the second cast instruction
484 const Type *DstTy, ///< The target type for the second cast instruction
485 TargetData *TD ///< The target data for pointer size
486) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000487
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000488 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
489 const Type *MidTy = CI->getType(); // B from above
490
491 // Get the opcodes of the two Cast instructions
492 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
493 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
494
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000495 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmana80e2712009-07-21 23:21:54 +0000496 DstTy,
Owen Anderson35b47072009-08-13 21:58:54 +0000497 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000498
499 // We don't want to form an inttoptr or ptrtoint that converts to an integer
500 // type that differs from the pointer size.
Owen Anderson35b47072009-08-13 21:58:54 +0000501 if ((Res == Instruction::IntToPtr &&
Dan Gohman033445f2009-08-19 23:38:22 +0000502 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson35b47072009-08-13 21:58:54 +0000503 (Res == Instruction::PtrToInt &&
Dan Gohman033445f2009-08-19 23:38:22 +0000504 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000505 Res = 0;
506
507 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000508}
509
510/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
511/// in any code being generated. It does not require codegen if V is simple
512/// enough or if the cast can be folded into other casts.
513static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
514 const Type *Ty, TargetData *TD) {
515 if (V->getType() == Ty || isa<Constant>(V)) return false;
516
517 // If this is another cast that can be eliminated, it isn't codegen either.
518 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000519 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520 return false;
521 return true;
522}
523
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000524// SimplifyCommutative - This performs a few simplifications for commutative
525// operators:
526//
527// 1. Order operands such that they are listed from right (least complex) to
528// left (most complex). This puts constants before unary operators before
529// binary operators.
530//
531// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
532// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
533//
534bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
535 bool Changed = false;
Dan Gohman5d138f92009-08-29 23:39:38 +0000536 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000537 Changed = !I.swapOperands();
538
539 if (!I.isAssociative()) return Changed;
540 Instruction::BinaryOps Opcode = I.getOpcode();
541 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
542 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
543 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000544 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000545 cast<Constant>(I.getOperand(1)),
546 cast<Constant>(Op->getOperand(1)));
547 I.setOperand(0, Op->getOperand(0));
548 I.setOperand(1, Folded);
549 return true;
550 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
551 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
552 isOnlyUse(Op) && isOnlyUse(Op1)) {
553 Constant *C1 = cast<Constant>(Op->getOperand(1));
554 Constant *C2 = cast<Constant>(Op1->getOperand(1));
555
556 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000557 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000558 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000559 Op1->getOperand(0),
560 Op1->getName(), &I);
Chris Lattner3183fb62009-08-30 06:13:40 +0000561 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000562 I.setOperand(0, New);
563 I.setOperand(1, Folded);
564 return true;
565 }
566 }
567 return Changed;
568}
569
570/// SimplifyCompare - For a CmpInst this function just orders the operands
571/// so that theyare listed from right (least complex) to left (most complex).
572/// This puts constants before unary operators before binary operators.
573bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman5d138f92009-08-29 23:39:38 +0000574 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 return false;
576 I.swapOperands();
577 // Compare instructions are not associative so there's nothing else we can do.
578 return true;
579}
580
581// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
582// if the LHS is a constant zero (which is the 'negate' form).
583//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000584static inline Value *dyn_castNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000585 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 return BinaryOperator::getNegArgument(V);
587
588 // Constants can be considered to be negated values if they can be folded.
589 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000590 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000591
592 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
593 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000594 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000595
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596 return 0;
597}
598
Dan Gohman7ce405e2009-06-04 22:49:04 +0000599// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
600// instruction if the LHS is a constant negative zero (which is the 'negate'
601// form).
602//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000603static inline Value *dyn_castFNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000604 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000605 return BinaryOperator::getFNegArgument(V);
606
607 // Constants can be considered to be negated values if they can be folded.
608 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000609 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000610
611 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
612 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000613 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000614
615 return 0;
616}
617
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000618static inline Value *dyn_castNotVal(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619 if (BinaryOperator::isNot(V))
620 return BinaryOperator::getNotArgument(V);
621
622 // Constants can be considered to be not'ed values...
623 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000624 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625 return 0;
626}
627
628// dyn_castFoldableMul - If this value is a multiply that can be folded into
629// other computations (because it has a constant operand), return the
630// non-constant operand of the multiply, and set CST to point to the multiplier.
631// Otherwise, return null.
632//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000633static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634 if (V->hasOneUse() && V->getType()->isInteger())
635 if (Instruction *I = dyn_cast<Instruction>(V)) {
636 if (I->getOpcode() == Instruction::Mul)
637 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
638 return I->getOperand(0);
639 if (I->getOpcode() == Instruction::Shl)
640 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
641 // The multiplier is really 1 << CST.
642 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
643 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000644 CST = ConstantInt::get(V->getType()->getContext(),
645 APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000646 return I->getOperand(0);
647 }
648 }
649 return 0;
650}
651
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652/// AddOne - Add one to a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000653static Constant *AddOne(Constant *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000654 return ConstantExpr::getAdd(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000655 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656}
657/// SubOne - Subtract one from a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000658static Constant *SubOne(ConstantInt *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000659 return ConstantExpr::getSub(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000660 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000661}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000662/// MultiplyOverflows - True if the multiply can not be expressed in an int
663/// this size.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000664static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000665 uint32_t W = C1->getBitWidth();
666 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
667 if (sign) {
668 LHSExt.sext(W * 2);
669 RHSExt.sext(W * 2);
670 } else {
671 LHSExt.zext(W * 2);
672 RHSExt.zext(W * 2);
673 }
674
675 APInt MulExt = LHSExt * RHSExt;
676
677 if (sign) {
678 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
679 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
680 return MulExt.slt(Min) || MulExt.sgt(Max);
681 } else
682 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
683}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000685
686/// ShrinkDemandedConstant - Check to see if the specified operand of the
687/// specified instruction is a constant integer. If so, check to see if there
688/// are any bits set in the constant that are not demanded. If so, shrink the
689/// constant and return true.
690static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000691 APInt Demanded) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692 assert(I && "No instruction?");
693 assert(OpNo < I->getNumOperands() && "Operand index too large");
694
695 // If the operand is not a constant integer, nothing to do.
696 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
697 if (!OpC) return false;
698
699 // If there are no bits set that aren't demanded, nothing to do.
700 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
701 if ((~Demanded & OpC->getValue()) == 0)
702 return false;
703
704 // This instruction is producing bits that are not demanded. Shrink the RHS.
705 Demanded &= OpC->getValue();
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000706 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707 return true;
708}
709
710// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
711// set of known zero and one bits, compute the maximum and minimum values that
712// could have the specified known zero and known one bits, returning them in
713// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000714static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715 const APInt& KnownOne,
716 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000717 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
718 KnownZero.getBitWidth() == Min.getBitWidth() &&
719 KnownZero.getBitWidth() == Max.getBitWidth() &&
720 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 APInt UnknownBits = ~(KnownZero|KnownOne);
722
723 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
724 // bit if it is unknown.
725 Min = KnownOne;
726 Max = KnownOne|UnknownBits;
727
Dan Gohman7934d592009-04-25 17:12:48 +0000728 if (UnknownBits.isNegative()) { // Sign bit is unknown
729 Min.set(Min.getBitWidth()-1);
730 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000731 }
732}
733
734// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
735// a set of known zero and one bits, compute the maximum and minimum values that
736// could have the specified known zero and known one bits, returning them in
737// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000738static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000739 const APInt &KnownOne,
740 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000741 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
742 KnownZero.getBitWidth() == Min.getBitWidth() &&
743 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000744 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
745 APInt UnknownBits = ~(KnownZero|KnownOne);
746
747 // The minimum value is when the unknown bits are all zeros.
748 Min = KnownOne;
749 // The maximum value is when the unknown bits are all ones.
750 Max = KnownOne|UnknownBits;
751}
752
Chris Lattner676c78e2009-01-31 08:15:18 +0000753/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
754/// SimplifyDemandedBits knows about. See if the instruction has any
755/// properties that allow us to simplify its operands.
756bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000757 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000758 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
759 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
760
761 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
762 KnownZero, KnownOne, 0);
763 if (V == 0) return false;
764 if (V == &Inst) return true;
765 ReplaceInstUsesWith(Inst, V);
766 return true;
767}
768
769/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
770/// specified instruction operand if possible, updating it in place. It returns
771/// true if it made any change and false otherwise.
772bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
773 APInt &KnownZero, APInt &KnownOne,
774 unsigned Depth) {
775 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
776 KnownZero, KnownOne, Depth);
777 if (NewVal == 0) return false;
Dan Gohman3af2d412009-10-05 16:31:55 +0000778 U = NewVal;
Chris Lattner676c78e2009-01-31 08:15:18 +0000779 return true;
780}
781
782
783/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
784/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785/// that only the bits set in DemandedMask of the result of V are ever used
786/// downstream. Consequently, depending on the mask and V, it may be possible
787/// to replace V with a constant or one of its operands. In such cases, this
788/// function does the replacement and returns true. In all other cases, it
789/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000790/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000791/// to be zero in the expression. These are provided to potentially allow the
792/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
793/// the expression. KnownOne and KnownZero always follow the invariant that
794/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
795/// the bits in KnownOne and KnownZero may only be accurate for those bits set
796/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
797/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000798///
799/// This returns null if it did not change anything and it permits no
800/// simplification. This returns V itself if it did some simplification of V's
801/// operands based on the information about what bits are demanded. This returns
802/// some other non-null value if it found out that V is equal to another value
803/// in the context where the specified bits are demanded, but not for all users.
804Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
805 APInt &KnownZero, APInt &KnownOne,
806 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807 assert(V != 0 && "Null pointer of Value???");
808 assert(Depth <= 6 && "Limit Search Depth");
809 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000810 const Type *VTy = V->getType();
811 assert((TD || !isa<PointerType>(VTy)) &&
812 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000813 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
814 (!VTy->isIntOrIntVector() ||
815 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000816 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000817 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000818 "Value *V, DemandedMask, KnownZero and KnownOne "
819 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
821 // We know all of the bits for a constant!
822 KnownOne = CI->getValue() & DemandedMask;
823 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000824 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000825 }
Dan Gohman7934d592009-04-25 17:12:48 +0000826 if (isa<ConstantPointerNull>(V)) {
827 // We know all of the bits for a constant!
828 KnownOne.clear();
829 KnownZero = DemandedMask;
830 return 0;
831 }
832
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000833 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000835 if (DemandedMask == 0) { // Not demanding any bits from V.
836 if (isa<UndefValue>(V))
837 return 0;
Owen Andersonb99ecca2009-07-30 23:03:37 +0000838 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839 }
840
Chris Lattner08817332009-01-31 08:24:16 +0000841 if (Depth == 6) // Limit search depth.
842 return 0;
843
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000844 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
845 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
846
Dan Gohman7934d592009-04-25 17:12:48 +0000847 Instruction *I = dyn_cast<Instruction>(V);
848 if (!I) {
849 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
850 return 0; // Only analyze instructions.
851 }
852
Chris Lattner08817332009-01-31 08:24:16 +0000853 // If there are multiple uses of this value and we aren't at the root, then
854 // we can't do any simplifications of the operands, because DemandedMask
855 // only reflects the bits demanded by *one* of the users.
856 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000857 // Despite the fact that we can't simplify this instruction in all User's
858 // context, we can at least compute the knownzero/knownone bits, and we can
859 // do simplifications that apply to *just* the one user if we know that
860 // this instruction has a simpler value in that context.
861 if (I->getOpcode() == Instruction::And) {
862 // If either the LHS or the RHS are Zero, the result is zero.
863 ComputeMaskedBits(I->getOperand(1), DemandedMask,
864 RHSKnownZero, RHSKnownOne, Depth+1);
865 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
866 LHSKnownZero, LHSKnownOne, Depth+1);
867
868 // If all of the demanded bits are known 1 on one side, return the other.
869 // These bits cannot contribute to the result of the 'and' in this
870 // context.
871 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
872 (DemandedMask & ~LHSKnownZero))
873 return I->getOperand(0);
874 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
875 (DemandedMask & ~RHSKnownZero))
876 return I->getOperand(1);
877
878 // If all of the demanded bits in the inputs are known zeros, return zero.
879 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000880 return Constant::getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000881
882 } else if (I->getOpcode() == Instruction::Or) {
883 // We can simplify (X|Y) -> X or Y in the user's context if we know that
884 // only bits from X or Y are demanded.
885
886 // If either the LHS or the RHS are One, the result is One.
887 ComputeMaskedBits(I->getOperand(1), DemandedMask,
888 RHSKnownZero, RHSKnownOne, Depth+1);
889 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
890 LHSKnownZero, LHSKnownOne, Depth+1);
891
892 // If all of the demanded bits are known zero on one side, return the
893 // other. These bits cannot contribute to the result of the 'or' in this
894 // context.
895 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
896 (DemandedMask & ~LHSKnownOne))
897 return I->getOperand(0);
898 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
899 (DemandedMask & ~RHSKnownOne))
900 return I->getOperand(1);
901
902 // If all of the potentially set bits on one side are known to be set on
903 // the other side, just use the 'other' side.
904 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
905 (DemandedMask & (~RHSKnownZero)))
906 return I->getOperand(0);
907 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
908 (DemandedMask & (~LHSKnownZero)))
909 return I->getOperand(1);
910 }
911
Chris Lattner08817332009-01-31 08:24:16 +0000912 // Compute the KnownZero/KnownOne bits to simplify things downstream.
913 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
914 return 0;
915 }
916
917 // If this is the root being simplified, allow it to have multiple uses,
918 // just set the DemandedMask to all bits so that we can try to simplify the
919 // operands. This allows visitTruncInst (for example) to simplify the
920 // operand of a trunc without duplicating all the logic below.
921 if (Depth == 0 && !V->hasOneUse())
922 DemandedMask = APInt::getAllOnesValue(BitWidth);
923
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000924 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000925 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000926 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000927 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000928 case Instruction::And:
929 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000930 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
931 RHSKnownZero, RHSKnownOne, Depth+1) ||
932 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000933 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000934 return I;
935 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
936 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000937
938 // If all of the demanded bits are known 1 on one side, return the other.
939 // These bits cannot contribute to the result of the 'and'.
940 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
941 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000942 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000943 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
944 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000945 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000946
947 // If all of the demanded bits in the inputs are known zeros, return zero.
948 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000949 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000950
951 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000952 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000953 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000954
955 // Output known-1 bits are only known if set in both the LHS & RHS.
956 RHSKnownOne &= LHSKnownOne;
957 // Output known-0 are known to be clear if zero in either the LHS | RHS.
958 RHSKnownZero |= LHSKnownZero;
959 break;
960 case Instruction::Or:
961 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +0000962 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
963 RHSKnownZero, RHSKnownOne, Depth+1) ||
964 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000965 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000966 return I;
967 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
968 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000969
970 // If all of the demanded bits are known zero on one side, return the other.
971 // These bits cannot contribute to the result of the 'or'.
972 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
973 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000974 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000975 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
976 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000977 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000978
979 // If all of the potentially set bits on one side are known to be set on
980 // the other side, just use the 'other' side.
981 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
982 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000983 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000984 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
985 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000986 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000987
988 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000989 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +0000990 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991
992 // Output known-0 bits are only known if clear in both the LHS & RHS.
993 RHSKnownZero &= LHSKnownZero;
994 // Output known-1 are known to be set if set in either the LHS | RHS.
995 RHSKnownOne |= LHSKnownOne;
996 break;
997 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +0000998 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
999 RHSKnownZero, RHSKnownOne, Depth+1) ||
1000 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001001 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001002 return I;
1003 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1004 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005
1006 // If all of the demanded bits are known zero on one side, return the other.
1007 // These bits cannot contribute to the result of the 'xor'.
1008 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001009 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001010 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001011 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012
1013 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1014 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1015 (RHSKnownOne & LHSKnownOne);
1016 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1017 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1018 (RHSKnownOne & LHSKnownZero);
1019
1020 // If all of the demanded bits are known to be zero on one side or the
1021 // other, turn this into an *inclusive* or.
1022 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneradba7ea2009-08-31 04:36:22 +00001023 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1024 Instruction *Or =
1025 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1026 I->getName());
1027 return InsertNewInstBefore(Or, *I);
1028 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029
1030 // If all of the demanded bits on one side are known, and all of the set
1031 // bits on that side are also known to be set on the other side, turn this
1032 // into an AND, as we know the bits will be cleared.
1033 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1034 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1035 // all known
1036 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohmancf2c9982009-08-03 22:07:33 +00001037 Constant *AndC = Constant::getIntegerValue(VTy,
1038 ~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001039 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001040 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001041 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001042 }
1043 }
1044
1045 // If the RHS is a constant, see if we can simplify it.
1046 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001047 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001048 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001049
1050 RHSKnownZero = KnownZeroOut;
1051 RHSKnownOne = KnownOneOut;
1052 break;
1053 }
1054 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001055 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1056 RHSKnownZero, RHSKnownOne, Depth+1) ||
1057 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001059 return I;
1060 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1061 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001062
1063 // If the operands are constants, see if we can simplify them.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001064 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1065 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001066 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001067
1068 // Only known if known in both the LHS and RHS.
1069 RHSKnownOne &= LHSKnownOne;
1070 RHSKnownZero &= LHSKnownZero;
1071 break;
1072 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001073 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001074 DemandedMask.zext(truncBf);
1075 RHSKnownZero.zext(truncBf);
1076 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001077 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001079 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001080 DemandedMask.trunc(BitWidth);
1081 RHSKnownZero.trunc(BitWidth);
1082 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001083 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001084 break;
1085 }
1086 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001087 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001088 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001089
1090 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1091 if (const VectorType *SrcVTy =
1092 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1093 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1094 // Don't touch a bitcast between vectors of different element counts.
1095 return false;
1096 } else
1097 // Don't touch a scalar-to-vector bitcast.
1098 return false;
1099 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1100 // Don't touch a vector-to-scalar bitcast.
1101 return false;
1102
Chris Lattner676c78e2009-01-31 08:15:18 +00001103 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001104 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001105 return I;
1106 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001107 break;
1108 case Instruction::ZExt: {
1109 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001110 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001111
1112 DemandedMask.trunc(SrcBitWidth);
1113 RHSKnownZero.trunc(SrcBitWidth);
1114 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001115 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001117 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001118 DemandedMask.zext(BitWidth);
1119 RHSKnownZero.zext(BitWidth);
1120 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001121 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001122 // The top bits are known to be zero.
1123 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1124 break;
1125 }
1126 case Instruction::SExt: {
1127 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001128 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001129
1130 APInt InputDemandedBits = DemandedMask &
1131 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1132
1133 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1134 // If any of the sign extended bits are demanded, we know that the sign
1135 // bit is demanded.
1136 if ((NewBits & DemandedMask) != 0)
1137 InputDemandedBits.set(SrcBitWidth-1);
1138
1139 InputDemandedBits.trunc(SrcBitWidth);
1140 RHSKnownZero.trunc(SrcBitWidth);
1141 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001142 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001144 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001145 InputDemandedBits.zext(BitWidth);
1146 RHSKnownZero.zext(BitWidth);
1147 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001148 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149
1150 // If the sign bit of the input is known set or clear, then we know the
1151 // top bits of the result.
1152
1153 // If the input sign bit is known zero, or if the NewBits are not demanded
1154 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001155 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001156 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001157 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1158 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001159 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1160 RHSKnownOne |= NewBits;
1161 }
1162 break;
1163 }
1164 case Instruction::Add: {
1165 // Figure out what the input bits are. If the top bits of the and result
1166 // are not demanded, then the add doesn't demand them from its input
1167 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001168 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001169
1170 // If there is a constant on the RHS, there are a variety of xformations
1171 // we can do.
1172 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1173 // If null, this should be simplified elsewhere. Some of the xforms here
1174 // won't work if the RHS is zero.
1175 if (RHS->isZero())
1176 break;
1177
1178 // If the top bit of the output is demanded, demand everything from the
1179 // input. Otherwise, we demand all the input bits except NLZ top bits.
1180 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1181
1182 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001183 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001185 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001186
1187 // If the RHS of the add has bits set that can't affect the input, reduce
1188 // the constant.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001189 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001190 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001191
1192 // Avoid excess work.
1193 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1194 break;
1195
1196 // Turn it into OR if input bits are zero.
1197 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1198 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001199 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001200 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001201 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001202 }
1203
1204 // We can say something about the output known-zero and known-one bits,
1205 // depending on potential carries from the input constant and the
1206 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1207 // bits set and the RHS constant is 0x01001, then we know we have a known
1208 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1209
1210 // To compute this, we first compute the potential carry bits. These are
1211 // the bits which may be modified. I'm not aware of a better way to do
1212 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001213 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1215
1216 // Now that we know which bits have carries, compute the known-1/0 sets.
1217
1218 // Bits are known one if they are known zero in one operand and one in the
1219 // other, and there is no input carry.
1220 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1221 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1222
1223 // Bits are known zero if they are known zero in both operands and there
1224 // is no input carry.
1225 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1226 } else {
1227 // If the high-bits of this ADD are not demanded, then it does not demand
1228 // the high bits of its LHS or RHS.
1229 if (DemandedMask[BitWidth-1] == 0) {
1230 // Right fill the mask of bits for this ADD to demand the most
1231 // significant bit and all those below it.
1232 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001233 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1234 LHSKnownZero, LHSKnownOne, Depth+1) ||
1235 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001236 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001237 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001238 }
1239 }
1240 break;
1241 }
1242 case Instruction::Sub:
1243 // If the high-bits of this SUB are not demanded, then it does not demand
1244 // the high bits of its LHS or RHS.
1245 if (DemandedMask[BitWidth-1] == 0) {
1246 // Right fill the mask of bits for this SUB to demand the most
1247 // significant bit and all those below it.
1248 uint32_t NLZ = DemandedMask.countLeadingZeros();
1249 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001250 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1251 LHSKnownZero, LHSKnownOne, Depth+1) ||
1252 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001253 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001254 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001255 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001256 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1257 // the known zeros and ones.
1258 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259 break;
1260 case Instruction::Shl:
1261 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1262 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1263 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001264 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001266 return I;
1267 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268 RHSKnownZero <<= ShiftAmt;
1269 RHSKnownOne <<= ShiftAmt;
1270 // low bits known zero.
1271 if (ShiftAmt)
1272 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1273 }
1274 break;
1275 case Instruction::LShr:
1276 // For a logical shift right
1277 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1278 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1279
1280 // Unsigned shift right.
1281 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001282 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001284 return I;
1285 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001286 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1287 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1288 if (ShiftAmt) {
1289 // Compute the new bits that are at the top now.
1290 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1291 RHSKnownZero |= HighBits; // high bits known zero.
1292 }
1293 }
1294 break;
1295 case Instruction::AShr:
1296 // If this is an arithmetic shift right and only the low-bit is set, we can
1297 // always convert this into a logical shr, even if the shift amount is
1298 // variable. The low bit of the shift cannot be an input sign bit unless
1299 // the shift amount is >= the size of the datatype, which is undefined.
1300 if (DemandedMask == 1) {
1301 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001302 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001303 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001304 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 }
1306
1307 // If the sign bit is the only bit demanded by this ashr, then there is no
1308 // need to do it, the shift doesn't change the high bit.
1309 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001310 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001311
1312 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1313 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1314
1315 // Signed shift right.
1316 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1317 // If any of the "high bits" are demanded, we should set the sign bit as
1318 // demanded.
1319 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1320 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001321 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001323 return I;
1324 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325 // Compute the new bits that are at the top now.
1326 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1327 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1328 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1329
1330 // Handle the sign bits.
1331 APInt SignBit(APInt::getSignBit(BitWidth));
1332 // Adjust to where it is now in the mask.
1333 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1334
1335 // If the input sign bit is known to be zero, or if none of the top bits
1336 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001337 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001338 (HighBits & ~DemandedMask) == HighBits) {
1339 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001340 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001342 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001343 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1344 RHSKnownOne |= HighBits;
1345 }
1346 }
1347 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001348 case Instruction::SRem:
1349 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001350 APInt RA = Rem->getValue().abs();
1351 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001352 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001353 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001354
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001355 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001356 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001357 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001358 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001359 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001360
1361 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1362 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001363
1364 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001365
Chris Lattner676c78e2009-01-31 08:15:18 +00001366 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001367 }
1368 }
1369 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001370 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001371 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1372 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001373 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1374 KnownZero2, KnownOne2, Depth+1) ||
1375 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001376 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001377 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001378
Chris Lattneree5417c2009-01-21 18:09:24 +00001379 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001380 Leaders = std::max(Leaders,
1381 KnownZero2.countLeadingOnes());
1382 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001383 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001384 }
Chris Lattner989ba312008-06-18 04:33:20 +00001385 case Instruction::Call:
1386 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1387 switch (II->getIntrinsicID()) {
1388 default: break;
1389 case Intrinsic::bswap: {
1390 // If the only bits demanded come from one byte of the bswap result,
1391 // just shift the input byte into position to eliminate the bswap.
1392 unsigned NLZ = DemandedMask.countLeadingZeros();
1393 unsigned NTZ = DemandedMask.countTrailingZeros();
1394
1395 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1396 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1397 // have 14 leading zeros, round to 8.
1398 NLZ &= ~7;
1399 NTZ &= ~7;
1400 // If we need exactly one byte, we can do this transformation.
1401 if (BitWidth-NLZ-NTZ == 8) {
1402 unsigned ResultBit = NTZ;
1403 unsigned InputBit = BitWidth-NTZ-8;
1404
1405 // Replace this with either a left or right shift to get the byte into
1406 // the right place.
1407 Instruction *NewVal;
1408 if (InputBit > ResultBit)
1409 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001410 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001411 else
1412 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001413 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001414 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001415 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001416 }
1417
1418 // TODO: Could compute known zero/one bits based on the input.
1419 break;
1420 }
1421 }
1422 }
Chris Lattner4946e222008-06-18 18:11:55 +00001423 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001424 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001425 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001426
1427 // If the client is only demanding bits that we know, return the known
1428 // constant.
Dan Gohmancf2c9982009-08-03 22:07:33 +00001429 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1430 return Constant::getIntegerValue(VTy, RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001431 return false;
1432}
1433
1434
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001435/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001436/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001437/// actually used by the caller. This method analyzes which elements of the
1438/// operand are undef and returns that information in UndefElts.
1439///
1440/// If the information about demanded elements can be used to simplify the
1441/// operation, the operation is simplified, then the resultant value is
1442/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001443Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1444 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001445 unsigned Depth) {
1446 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001447 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001448 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001449
1450 if (isa<UndefValue>(V)) {
1451 // If the entire vector is undefined, just return this info.
1452 UndefElts = EltMask;
1453 return 0;
1454 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1455 UndefElts = EltMask;
Owen Andersonb99ecca2009-07-30 23:03:37 +00001456 return UndefValue::get(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001457 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001458
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001459 UndefElts = 0;
1460 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1461 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb99ecca2009-07-30 23:03:37 +00001462 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001463
1464 std::vector<Constant*> Elts;
1465 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001466 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001467 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001468 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001469 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1470 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001471 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001472 } else { // Otherwise, defined.
1473 Elts.push_back(CP->getOperand(i));
1474 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001475
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001476 // If we changed the constant, return it.
Owen Anderson2f422e02009-07-28 21:19:26 +00001477 Constant *NewCP = ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001478 return NewCP != CP ? NewCP : 0;
1479 } else if (isa<ConstantAggregateZero>(V)) {
1480 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1481 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001482
1483 // Check if this is identity. If so, return 0 since we are not simplifying
1484 // anything.
1485 if (DemandedElts == ((1ULL << VWidth) -1))
1486 return 0;
1487
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001488 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonaac28372009-07-31 20:28:14 +00001489 Constant *Zero = Constant::getNullValue(EltTy);
Owen Andersonb99ecca2009-07-30 23:03:37 +00001490 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001491 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001492 for (unsigned i = 0; i != VWidth; ++i) {
1493 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1494 Elts.push_back(Elt);
1495 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001496 UndefElts = DemandedElts ^ EltMask;
Owen Anderson2f422e02009-07-28 21:19:26 +00001497 return ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001498 }
1499
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001500 // Limit search depth.
1501 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001502 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001503
1504 // If multiple users are using the root value, procede with
1505 // simplification conservatively assuming that all elements
1506 // are needed.
1507 if (!V->hasOneUse()) {
1508 // Quit if we find multiple users of a non-root value though.
1509 // They'll be handled when it's their turn to be visited by
1510 // the main instcombine process.
1511 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001512 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001513 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001514
1515 // Conservatively assume that all elements are needed.
1516 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001517 }
1518
1519 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001520 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521
1522 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001523 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001524 Value *TmpV;
1525 switch (I->getOpcode()) {
1526 default: break;
1527
1528 case Instruction::InsertElement: {
1529 // If this is a variable index, we don't know which element it overwrites.
1530 // demand exactly the same input as we produce.
1531 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1532 if (Idx == 0) {
1533 // Note that we can't propagate undef elt info, because we don't know
1534 // which elt is getting updated.
1535 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1536 UndefElts2, Depth+1);
1537 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1538 break;
1539 }
1540
1541 // If this is inserting an element that isn't demanded, remove this
1542 // insertelement.
1543 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner059cfc72009-08-30 06:20:05 +00001544 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1545 Worklist.Add(I);
1546 return I->getOperand(0);
1547 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001548
1549 // Otherwise, the element inserted overwrites whatever was there, so the
1550 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001551 APInt DemandedElts2 = DemandedElts;
1552 DemandedElts2.clear(IdxNo);
1553 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001554 UndefElts, Depth+1);
1555 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1556
1557 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001558 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001559 break;
1560 }
1561 case Instruction::ShuffleVector: {
1562 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001563 uint64_t LHSVWidth =
1564 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001565 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001566 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001567 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001568 unsigned MaskVal = Shuffle->getMaskValue(i);
1569 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001570 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001571 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001572 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001573 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001574 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001575 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001576 }
1577 }
1578 }
1579
Nate Begemanb4d176f2009-02-11 22:36:25 +00001580 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001581 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001582 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001583 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1584
Nate Begemanb4d176f2009-02-11 22:36:25 +00001585 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001586 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1587 UndefElts3, Depth+1);
1588 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1589
1590 bool NewUndefElts = false;
1591 for (unsigned i = 0; i < VWidth; i++) {
1592 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001593 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001594 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001595 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001596 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001597 NewUndefElts = true;
1598 UndefElts.set(i);
1599 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001600 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001601 if (UndefElts3[MaskVal - LHSVWidth]) {
1602 NewUndefElts = true;
1603 UndefElts.set(i);
1604 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001605 }
1606 }
1607
1608 if (NewUndefElts) {
1609 // Add additional discovered undefs.
1610 std::vector<Constant*> Elts;
1611 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001612 if (UndefElts[i])
Owen Anderson35b47072009-08-13 21:58:54 +00001613 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001614 else
Owen Anderson35b47072009-08-13 21:58:54 +00001615 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001616 Shuffle->getMaskValue(i)));
1617 }
Owen Anderson2f422e02009-07-28 21:19:26 +00001618 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001619 MadeChange = true;
1620 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001621 break;
1622 }
1623 case Instruction::BitCast: {
1624 // Vector->vector casts only.
1625 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1626 if (!VTy) break;
1627 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001628 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001629 unsigned Ratio;
1630
1631 if (VWidth == InVWidth) {
1632 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1633 // elements as are demanded of us.
1634 Ratio = 1;
1635 InputDemandedElts = DemandedElts;
1636 } else if (VWidth > InVWidth) {
1637 // Untested so far.
1638 break;
1639
1640 // If there are more elements in the result than there are in the source,
1641 // then an input element is live if any of the corresponding output
1642 // elements are live.
1643 Ratio = VWidth/InVWidth;
1644 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001645 if (DemandedElts[OutIdx])
1646 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001647 }
1648 } else {
1649 // Untested so far.
1650 break;
1651
1652 // If there are more elements in the source than there are in the result,
1653 // then an input element is live if the corresponding output element is
1654 // live.
1655 Ratio = InVWidth/VWidth;
1656 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001657 if (DemandedElts[InIdx/Ratio])
1658 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001659 }
1660
1661 // div/rem demand all inputs, because they don't want divide by zero.
1662 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1663 UndefElts2, Depth+1);
1664 if (TmpV) {
1665 I->setOperand(0, TmpV);
1666 MadeChange = true;
1667 }
1668
1669 UndefElts = UndefElts2;
1670 if (VWidth > InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001671 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001672 // If there are more elements in the result than there are in the source,
1673 // then an output element is undef if the corresponding input element is
1674 // undef.
1675 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001676 if (UndefElts2[OutIdx/Ratio])
1677 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001678 } else if (VWidth < InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001679 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001680 // If there are more elements in the source than there are in the result,
1681 // then a result element is undef if all of the corresponding input
1682 // elements are undef.
1683 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1684 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001685 if (!UndefElts2[InIdx]) // Not undef?
1686 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001687 }
1688 break;
1689 }
1690 case Instruction::And:
1691 case Instruction::Or:
1692 case Instruction::Xor:
1693 case Instruction::Add:
1694 case Instruction::Sub:
1695 case Instruction::Mul:
1696 // div/rem demand all inputs, because they don't want divide by zero.
1697 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1698 UndefElts, Depth+1);
1699 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1700 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1701 UndefElts2, Depth+1);
1702 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1703
1704 // Output elements are undefined if both are undefined. Consider things
1705 // like undef&0. The result is known zero, not undef.
1706 UndefElts &= UndefElts2;
1707 break;
1708
1709 case Instruction::Call: {
1710 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1711 if (!II) break;
1712 switch (II->getIntrinsicID()) {
1713 default: break;
1714
1715 // Binary vector operations that work column-wise. A dest element is a
1716 // function of the corresponding input elements from the two inputs.
1717 case Intrinsic::x86_sse_sub_ss:
1718 case Intrinsic::x86_sse_mul_ss:
1719 case Intrinsic::x86_sse_min_ss:
1720 case Intrinsic::x86_sse_max_ss:
1721 case Intrinsic::x86_sse2_sub_sd:
1722 case Intrinsic::x86_sse2_mul_sd:
1723 case Intrinsic::x86_sse2_min_sd:
1724 case Intrinsic::x86_sse2_max_sd:
1725 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1726 UndefElts, Depth+1);
1727 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1728 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1729 UndefElts2, Depth+1);
1730 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1731
1732 // If only the low elt is demanded and this is a scalarizable intrinsic,
1733 // scalarize it now.
1734 if (DemandedElts == 1) {
1735 switch (II->getIntrinsicID()) {
1736 default: break;
1737 case Intrinsic::x86_sse_sub_ss:
1738 case Intrinsic::x86_sse_mul_ss:
1739 case Intrinsic::x86_sse2_sub_sd:
1740 case Intrinsic::x86_sse2_mul_sd:
1741 // TODO: Lower MIN/MAX/ABS/etc
1742 Value *LHS = II->getOperand(1);
1743 Value *RHS = II->getOperand(2);
1744 // Extract the element as scalars.
Eric Christopher1ba36872009-07-25 02:28:41 +00001745 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001746 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christopher1ba36872009-07-25 02:28:41 +00001747 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001748 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001749
1750 switch (II->getIntrinsicID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001751 default: llvm_unreachable("Case stmts out of sync!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001752 case Intrinsic::x86_sse_sub_ss:
1753 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001754 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001755 II->getName()), *II);
1756 break;
1757 case Intrinsic::x86_sse_mul_ss:
1758 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001759 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001760 II->getName()), *II);
1761 break;
1762 }
1763
1764 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001765 InsertElementInst::Create(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001766 UndefValue::get(II->getType()), TmpV,
Owen Anderson35b47072009-08-13 21:58:54 +00001767 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001768 InsertNewInstBefore(New, *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001769 return New;
1770 }
1771 }
1772
1773 // Output elements are undefined if both are undefined. Consider things
1774 // like undef&0. The result is known zero, not undef.
1775 UndefElts &= UndefElts2;
1776 break;
1777 }
1778 break;
1779 }
1780 }
1781 return MadeChange ? I : 0;
1782}
1783
Dan Gohman5d56fd42008-05-19 22:14:15 +00001784
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001785/// AssociativeOpt - Perform an optimization on an associative operator. This
1786/// function is designed to check a chain of associative operators for a
1787/// potential to apply a certain optimization. Since the optimization may be
1788/// applicable if the expression was reassociated, this checks the chain, then
1789/// reassociates the expression as necessary to expose the optimization
1790/// opportunity. This makes use of a special Functor, which must define
1791/// 'shouldApply' and 'apply' methods.
1792///
1793template<typename Functor>
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001794static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001795 unsigned Opcode = Root.getOpcode();
1796 Value *LHS = Root.getOperand(0);
1797
1798 // Quick check, see if the immediate LHS matches...
1799 if (F.shouldApply(LHS))
1800 return F.apply(Root);
1801
1802 // Otherwise, if the LHS is not of the same opcode as the root, return.
1803 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1804 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1805 // Should we apply this transform to the RHS?
1806 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1807
1808 // If not to the RHS, check to see if we should apply to the LHS...
1809 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1810 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1811 ShouldApply = true;
1812 }
1813
1814 // If the functor wants to apply the optimization to the RHS of LHSI,
1815 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1816 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001817 // Now all of the instructions are in the current basic block, go ahead
1818 // and perform the reassociation.
1819 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1820
1821 // First move the selected RHS to the LHS of the root...
1822 Root.setOperand(0, LHSI->getOperand(1));
1823
1824 // Make what used to be the LHS of the root be the user of the root...
1825 Value *ExtraOperand = TmpLHSI->getOperand(1);
1826 if (&Root == TmpLHSI) {
Owen Andersonaac28372009-07-31 20:28:14 +00001827 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001828 return 0;
1829 }
1830 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1831 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001832 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001833 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001834 ARI = Root;
1835
1836 // Now propagate the ExtraOperand down the chain of instructions until we
1837 // get to LHSI.
1838 while (TmpLHSI != LHSI) {
1839 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1840 // Move the instruction to immediately before the chain we are
1841 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001842 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001843 ARI = NextLHSI;
1844
1845 Value *NextOp = NextLHSI->getOperand(1);
1846 NextLHSI->setOperand(1, ExtraOperand);
1847 TmpLHSI = NextLHSI;
1848 ExtraOperand = NextOp;
1849 }
1850
1851 // Now that the instructions are reassociated, have the functor perform
1852 // the transformation...
1853 return F.apply(Root);
1854 }
1855
1856 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1857 }
1858 return 0;
1859}
1860
Dan Gohman089efff2008-05-13 00:00:25 +00001861namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001862
Nick Lewycky27f6c132008-05-23 04:34:58 +00001863// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001864struct AddRHS {
1865 Value *RHS;
Dan Gohmancdff2122009-08-12 16:23:25 +00001866 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001867 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1868 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001869 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001870 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001871 }
1872};
1873
1874// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1875// iff C1&C2 == 0
1876struct AddMaskingAnd {
1877 Constant *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00001878 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001879 bool shouldApply(Value *LHS) const {
1880 ConstantInt *C1;
Dan Gohmancdff2122009-08-12 16:23:25 +00001881 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Anderson02b48c32009-07-29 18:55:55 +00001882 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001883 }
1884 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001885 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001886 }
1887};
1888
Dan Gohman089efff2008-05-13 00:00:25 +00001889}
1890
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001891static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1892 InstCombiner *IC) {
Chris Lattner78628292009-08-30 19:47:22 +00001893 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattnerd6164c22009-08-30 20:01:10 +00001894 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001895
1896 // Figure out if the constant is the left or the right argument.
1897 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1898 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1899
1900 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1901 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +00001902 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1903 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001904 }
1905
1906 Value *Op0 = SO, *Op1 = ConstOperand;
1907 if (!ConstIsRHS)
1908 std::swap(Op0, Op1);
Chris Lattnerc7694852009-08-30 07:44:24 +00001909
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001910 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattnerc7694852009-08-30 07:44:24 +00001911 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1912 SO->getName()+".op");
1913 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1914 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1915 SO->getName()+".cmp");
1916 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1917 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1918 SO->getName()+".cmp");
1919 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001920}
1921
1922// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1923// constant as the other operand, try to fold the binary operator into the
1924// select arguments. This also works for Cast instructions, which obviously do
1925// not have a second operand.
1926static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1927 InstCombiner *IC) {
1928 // Don't modify shared select instructions
1929 if (!SI->hasOneUse()) return 0;
1930 Value *TV = SI->getOperand(1);
1931 Value *FV = SI->getOperand(2);
1932
1933 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1934 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson35b47072009-08-13 21:58:54 +00001935 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001936
1937 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1938 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1939
Gabor Greifd6da1d02008-04-06 20:25:17 +00001940 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1941 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001942 }
1943 return 0;
1944}
1945
1946
Chris Lattnerf7843b72009-09-27 19:57:57 +00001947/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1948/// has a PHI node as operand #0, see if we can fold the instruction into the
1949/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +00001950///
1951/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1952/// that would normally be unprofitable because they strongly encourage jump
1953/// threading.
1954Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1955 bool AllowAggressive) {
1956 AllowAggressive = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001957 PHINode *PN = cast<PHINode>(I.getOperand(0));
1958 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner9b61abd2009-09-27 20:46:36 +00001959 if (NumPHIValues == 0 ||
1960 // We normally only transform phis with a single use, unless we're trying
1961 // hard to make jump threading happen.
1962 (!PN->hasOneUse() && !AllowAggressive))
1963 return 0;
1964
1965
Chris Lattnerf7843b72009-09-27 19:57:57 +00001966 // Check to see if all of the operands of the PHI are simple constants
1967 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00001968 // remember the BB it is in. If there is more than one or if *it* is a PHI,
1969 // bail out. We don't do arbitrary constant expressions here because moving
1970 // their computation can be expensive without a cost model.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001971 BasicBlock *NonConstBB = 0;
1972 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattnerf7843b72009-09-27 19:57:57 +00001973 if (!isa<Constant>(PN->getIncomingValue(i)) ||
1974 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001975 if (NonConstBB) return 0; // More than one non-const value.
1976 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1977 NonConstBB = PN->getIncomingBlock(i);
1978
1979 // If the incoming non-constant value is in I's block, we have an infinite
1980 // loop.
1981 if (NonConstBB == I.getParent())
1982 return 0;
1983 }
1984
1985 // If there is exactly one non-constant value, we can insert a copy of the
1986 // operation in that block. However, if this is a critical edge, we would be
1987 // inserting the computation one some other paths (e.g. inside a loop). Only
1988 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9b61abd2009-09-27 20:46:36 +00001989 if (NonConstBB != 0 && !AllowAggressive) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001990 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1991 if (!BI || !BI->isUnconditional()) return 0;
1992 }
1993
1994 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001995 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001996 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1997 InsertNewInstBefore(NewPN, *PN);
1998 NewPN->takeName(PN);
1999
2000 // Next, add all of the operands to the PHI.
Chris Lattnerf7843b72009-09-27 19:57:57 +00002001 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2002 // We only currently try to fold the condition of a select when it is a phi,
2003 // not the true/false values.
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002004 Value *TrueV = SI->getTrueValue();
2005 Value *FalseV = SI->getFalseValue();
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002006 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerf7843b72009-09-27 19:57:57 +00002007 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002008 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002009 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2010 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002011 Value *InV = 0;
2012 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002013 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerf7843b72009-09-27 19:57:57 +00002014 } else {
2015 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002016 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2017 FalseVInPred,
Chris Lattnerf7843b72009-09-27 19:57:57 +00002018 "phitmp", NonConstBB->getTerminator());
2019 Worklist.Add(cast<Instruction>(InV));
2020 }
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002021 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002022 }
2023 } else if (I.getNumOperands() == 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002024 Constant *C = cast<Constant>(I.getOperand(1));
2025 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002026 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002027 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2028 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +00002029 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002030 else
Owen Anderson02b48c32009-07-29 18:55:55 +00002031 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002032 } else {
2033 assert(PN->getIncomingBlock(i) == NonConstBB);
2034 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002035 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002036 PN->getIncomingValue(i), C, "phitmp",
2037 NonConstBB->getTerminator());
2038 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +00002039 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002040 CI->getPredicate(),
2041 PN->getIncomingValue(i), C, "phitmp",
2042 NonConstBB->getTerminator());
2043 else
Edwin Törökbd448e32009-07-14 16:55:14 +00002044 llvm_unreachable("Unknown binop!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002045
Chris Lattner3183fb62009-08-30 06:13:40 +00002046 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002047 }
2048 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2049 }
2050 } else {
2051 CastInst *CI = cast<CastInst>(&I);
2052 const Type *RetTy = CI->getType();
2053 for (unsigned i = 0; i != NumPHIValues; ++i) {
2054 Value *InV;
2055 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002056 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002057 } else {
2058 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002059 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002060 I.getType(), "phitmp",
2061 NonConstBB->getTerminator());
Chris Lattner3183fb62009-08-30 06:13:40 +00002062 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002063 }
2064 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2065 }
2066 }
2067 return ReplaceInstUsesWith(I, NewPN);
2068}
2069
Chris Lattner55476162008-01-29 06:52:45 +00002070
Chris Lattner3554f972008-05-20 05:46:13 +00002071/// WillNotOverflowSignedAdd - Return true if we can prove that:
2072/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2073/// This basically requires proving that the add in the original type would not
2074/// overflow to change the sign bit or have a carry out.
2075bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2076 // There are different heuristics we can use for this. Here are some simple
2077 // ones.
2078
2079 // Add has the property that adding any two 2's complement numbers can only
2080 // have one carry bit which can change a sign. As such, if LHS and RHS each
2081 // have at least two sign bits, we know that the addition of the two values will
2082 // sign extend fine.
2083 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2084 return true;
2085
2086
2087 // If one of the operands only has one non-zero bit, and if the other operand
2088 // has a known-zero bit in a more significant place than it (not including the
2089 // sign bit) the ripple may go up to and fill the zero, but won't change the
2090 // sign. For example, (X & ~4) + 1.
2091
2092 // TODO: Implement.
2093
2094 return false;
2095}
2096
Chris Lattner55476162008-01-29 06:52:45 +00002097
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002098Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2099 bool Changed = SimplifyCommutative(I);
2100 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2101
2102 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2103 // X + undef -> undef
2104 if (isa<UndefValue>(RHS))
2105 return ReplaceInstUsesWith(I, RHS);
2106
2107 // X + 0 --> X
Dan Gohman7ce405e2009-06-04 22:49:04 +00002108 if (RHSC->isNullValue())
2109 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002110
2111 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2112 // X + (signbit) --> X ^ signbit
2113 const APInt& Val = CI->getValue();
2114 uint32_t BitWidth = Val.getBitWidth();
2115 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002116 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002117
2118 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2119 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002120 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002121 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002122
Eli Friedmana21526d2009-07-13 22:27:52 +00002123 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +00002124 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson35b47072009-08-13 21:58:54 +00002125 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002126 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002127 }
2128
2129 if (isa<PHINode>(LHS))
2130 if (Instruction *NV = FoldOpIntoPhi(I))
2131 return NV;
2132
2133 ConstantInt *XorRHS = 0;
2134 Value *XorLHS = 0;
2135 if (isa<ConstantInt>(RHSC) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002136 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002137 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002138 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2139
2140 uint32_t Size = TySizeBits / 2;
2141 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2142 APInt CFF80Val(-C0080Val);
2143 do {
2144 if (TySizeBits > Size) {
2145 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2146 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2147 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2148 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2149 // This is a sign extend if the top bits are known zero.
2150 if (!MaskedValueIsZero(XorLHS,
2151 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2152 Size = 0; // Not a sign ext, but can't be any others either.
2153 break;
2154 }
2155 }
2156 Size >>= 1;
2157 C0080Val = APIntOps::lshr(C0080Val, Size);
2158 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2159 } while (Size >= 1);
2160
2161 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002162 // with funny bit widths then this switch statement should be removed. It
2163 // is just here to get the size of the "middle" type back up to something
2164 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002165 const Type *MiddleType = 0;
2166 switch (Size) {
2167 default: break;
Owen Anderson35b47072009-08-13 21:58:54 +00002168 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2169 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2170 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002171 }
2172 if (MiddleType) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002173 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002174 return new SExtInst(NewTrunc, I.getType(), I.getName());
2175 }
2176 }
2177 }
2178
Owen Anderson35b47072009-08-13 21:58:54 +00002179 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002180 return BinaryOperator::CreateXor(LHS, RHS);
2181
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002182 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002183 if (I.getType()->isInteger()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00002184 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Anderson24be4c12009-07-03 00:17:18 +00002185 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002186
2187 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2188 if (RHSI->getOpcode() == Instruction::Sub)
2189 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2190 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2191 }
2192 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2193 if (LHSI->getOpcode() == Instruction::Sub)
2194 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2195 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2196 }
2197 }
2198
2199 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002200 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002201 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002202 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002203 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002204 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohmancdff2122009-08-12 16:23:25 +00002205 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002206 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002207 }
2208
Gabor Greifa645dd32008-05-16 19:29:10 +00002209 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002210 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002211
2212 // A + -B --> A - B
2213 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002214 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002215 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002216
2217
2218 ConstantInt *C2;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002219 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002220 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002221 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002222
2223 // X*C1 + X*C2 --> X * (C1+C2)
2224 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002225 if (X == dyn_castFoldableMul(RHS, C1))
Owen Anderson02b48c32009-07-29 18:55:55 +00002226 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002227 }
2228
2229 // X + X*C --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002230 if (dyn_castFoldableMul(RHS, C2) == LHS)
2231 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002232
2233 // X + ~X --> -1 since ~X = -X-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002234 if (dyn_castNotVal(LHS) == RHS ||
2235 dyn_castNotVal(RHS) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +00002236 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002237
2238
2239 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00002240 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2241 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002242 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002243
2244 // A+B --> A|B iff A and B have no bits set in common.
2245 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2246 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2247 APInt LHSKnownOne(IT->getBitWidth(), 0);
2248 APInt LHSKnownZero(IT->getBitWidth(), 0);
2249 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2250 if (LHSKnownZero != 0) {
2251 APInt RHSKnownOne(IT->getBitWidth(), 0);
2252 APInt RHSKnownZero(IT->getBitWidth(), 0);
2253 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2254
2255 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002256 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002257 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002258 }
2259 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002260
Nick Lewycky83598a72008-02-03 07:42:09 +00002261 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002262 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002263 Value *W, *X, *Y, *Z;
Dan Gohmancdff2122009-08-12 16:23:25 +00002264 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2265 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002266 if (W != Y) {
2267 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002268 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002269 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002270 std::swap(W, X);
2271 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002272 std::swap(Y, Z);
2273 std::swap(W, X);
2274 }
2275 }
2276
2277 if (W == Y) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002278 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002279 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002280 }
2281 }
2282 }
2283
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002284 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2285 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002286 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002287 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002288
2289 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002290 if (LHS->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002291 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002292 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002293 if (Anded == CRHS) {
2294 // See if all bits from the first bit set in the Add RHS up are included
2295 // in the mask. First, get the rightmost bit.
2296 const APInt& AddRHSV = CRHS->getValue();
2297
2298 // Form a mask of all bits from the lowest bit added through the top.
2299 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2300
2301 // See if the and mask includes all of these bits.
2302 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2303
2304 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2305 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattnerc7694852009-08-30 07:44:24 +00002306 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002307 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002308 }
2309 }
2310 }
2311
2312 // Try to fold constant add into select arguments.
2313 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2314 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2315 return R;
2316 }
2317
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002318 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002319 {
2320 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002321 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002322 if (!SI) {
2323 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002324 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002325 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002326 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002327 Value *TV = SI->getTrueValue();
2328 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002329 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002330
2331 // Can we fold the add into the argument of the select?
2332 // We check both true and false select arguments for a matching subtract.
Dan Gohmancdff2122009-08-12 16:23:25 +00002333 if (match(FV, m_Zero()) &&
2334 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002335 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002336 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohmancdff2122009-08-12 16:23:25 +00002337 if (match(TV, m_Zero()) &&
2338 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002339 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002340 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002341 }
2342 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002343
Chris Lattner3554f972008-05-20 05:46:13 +00002344 // Check for (add (sext x), y), see if we can merge this into an
2345 // integer add followed by a sext.
2346 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2347 // (add (sext x), cst) --> (sext (add x, cst'))
2348 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2349 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002350 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002351 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002352 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002353 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2354 // Insert the new, smaller add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002355 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2356 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002357 return new SExtInst(NewAdd, I.getType());
2358 }
2359 }
2360
2361 // (add (sext x), (sext y)) --> (sext (add int x, y))
2362 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2363 // Only do this if x/y have the same type, if at last one of them has a
2364 // single use (so we don't increase the number of sexts), and if the
2365 // integer add will not overflow.
2366 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2367 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2368 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2369 RHSConv->getOperand(0))) {
2370 // Insert the new integer add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002371 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2372 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002373 return new SExtInst(NewAdd, I.getType());
2374 }
2375 }
2376 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002377
2378 return Changed ? &I : 0;
2379}
2380
2381Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2382 bool Changed = SimplifyCommutative(I);
2383 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2384
2385 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2386 // X + 0 --> X
2387 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +00002388 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002389 (I.getType())->getValueAPF()))
2390 return ReplaceInstUsesWith(I, LHS);
2391 }
2392
2393 if (isa<PHINode>(LHS))
2394 if (Instruction *NV = FoldOpIntoPhi(I))
2395 return NV;
2396 }
2397
2398 // -A + B --> B - A
2399 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002400 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002401 return BinaryOperator::CreateFSub(RHS, LHSV);
2402
2403 // A + -B --> A - B
2404 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002405 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002406 return BinaryOperator::CreateFSub(LHS, V);
2407
2408 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2409 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2410 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2411 return ReplaceInstUsesWith(I, LHS);
2412
Chris Lattner3554f972008-05-20 05:46:13 +00002413 // Check for (add double (sitofp x), y), see if we can merge this into an
2414 // integer add followed by a promotion.
2415 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2416 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2417 // ... if the constant fits in the integer value. This is useful for things
2418 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2419 // requires a constant pool load, and generally allows the add to be better
2420 // instcombined.
2421 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2422 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002423 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002424 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002425 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002426 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2427 // Insert the new integer add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002428 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2429 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002430 return new SIToFPInst(NewAdd, I.getType());
2431 }
2432 }
2433
2434 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2435 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2436 // Only do this if x/y have the same type, if at last one of them has a
2437 // single use (so we don't increase the number of int->fp conversions),
2438 // and if the integer add will not overflow.
2439 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2440 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2441 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2442 RHSConv->getOperand(0))) {
2443 // Insert the new integer add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002444 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2445 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002446 return new SIToFPInst(NewAdd, I.getType());
2447 }
2448 }
2449 }
2450
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002451 return Changed ? &I : 0;
2452}
2453
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002454Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2455 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2456
Dan Gohman7ce405e2009-06-04 22:49:04 +00002457 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002458 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002459
2460 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002461 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002462 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002463
2464 if (isa<UndefValue>(Op0))
2465 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2466 if (isa<UndefValue>(Op1))
2467 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2468
2469 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2470 // Replace (-1 - A) with (~A)...
2471 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00002472 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002473
2474 // C - ~X == X + (1+C)
2475 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002476 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002477 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002478
2479 // -(X >>u 31) -> (X >>s 31)
2480 // -(X >>s 31) -> (X >>u 31)
2481 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002482 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002483 if (SI->getOpcode() == Instruction::LShr) {
2484 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2485 // Check to see if we are shifting out everything but the sign bit.
2486 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2487 SI->getType()->getPrimitiveSizeInBits()-1) {
2488 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002489 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002490 SI->getOperand(0), CU, SI->getName());
2491 }
2492 }
2493 }
2494 else if (SI->getOpcode() == Instruction::AShr) {
2495 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2496 // Check to see if we are shifting out everything but the sign bit.
2497 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2498 SI->getType()->getPrimitiveSizeInBits()-1) {
2499 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002500 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002501 SI->getOperand(0), CU, SI->getName());
2502 }
2503 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002504 }
2505 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002506 }
2507
2508 // Try to fold constant sub into select arguments.
2509 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2510 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2511 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002512
2513 // C - zext(bool) -> bool ? C - 1 : C
2514 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson35b47072009-08-13 21:58:54 +00002515 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002516 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002517 }
2518
Owen Anderson35b47072009-08-13 21:58:54 +00002519 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002520 return BinaryOperator::CreateXor(Op0, Op1);
2521
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002522 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002523 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002524 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002525 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002526 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002527 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002528 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002529 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002530 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2531 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2532 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002533 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002534 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002535 }
2536 }
2537
2538 if (Op1I->hasOneUse()) {
2539 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2540 // is not used by anyone else...
2541 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002542 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002543 // Swap the two operands of the subexpr...
2544 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2545 Op1I->setOperand(0, IIOp1);
2546 Op1I->setOperand(1, IIOp0);
2547
2548 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002549 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002550 }
2551
2552 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2553 //
2554 if (Op1I->getOpcode() == Instruction::And &&
2555 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2556 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2557
Chris Lattnerc7694852009-08-30 07:44:24 +00002558 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greifa645dd32008-05-16 19:29:10 +00002559 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002560 }
2561
2562 // 0 - (X sdiv C) -> (X sdiv -C)
2563 if (Op1I->getOpcode() == Instruction::SDiv)
2564 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2565 if (CSI->isZero())
2566 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002567 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002568 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002569
2570 // X - X*C --> X * (1-C)
2571 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002572 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002573 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00002574 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002575 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002576 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002577 }
2578 }
2579 }
2580
Dan Gohman7ce405e2009-06-04 22:49:04 +00002581 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2582 if (Op0I->getOpcode() == Instruction::Add) {
2583 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2584 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2585 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2586 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2587 } else if (Op0I->getOpcode() == Instruction::Sub) {
2588 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002589 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002590 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002591 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002592 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002593
2594 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002595 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002596 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002597 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002598
2599 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002600 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00002601 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002602 }
2603 return 0;
2604}
2605
Dan Gohman7ce405e2009-06-04 22:49:04 +00002606Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2607 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2608
2609 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002610 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002611 return BinaryOperator::CreateFAdd(Op0, V);
2612
2613 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2614 if (Op1I->getOpcode() == Instruction::FAdd) {
2615 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002616 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002617 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002618 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002619 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002620 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002621 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002622 }
2623
2624 return 0;
2625}
2626
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002627/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2628/// comparison only checks the sign bit. If it only checks the sign bit, set
2629/// TrueIfSigned if the result of the comparison is true when the input value is
2630/// signed.
2631static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2632 bool &TrueIfSigned) {
2633 switch (pred) {
2634 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2635 TrueIfSigned = true;
2636 return RHS->isZero();
2637 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2638 TrueIfSigned = true;
2639 return RHS->isAllOnesValue();
2640 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2641 TrueIfSigned = false;
2642 return RHS->isAllOnesValue();
2643 case ICmpInst::ICMP_UGT:
2644 // True if LHS u> RHS and RHS == high-bit-mask - 1
2645 TrueIfSigned = true;
2646 return RHS->getValue() ==
2647 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2648 case ICmpInst::ICMP_UGE:
2649 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2650 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002651 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002652 default:
2653 return false;
2654 }
2655}
2656
2657Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2658 bool Changed = SimplifyCommutative(I);
2659 Value *Op0 = I.getOperand(0);
2660
Eli Friedmane426ded2009-07-18 09:12:15 +00002661 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002662 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002663
2664 // Simplify mul instructions with a constant RHS...
2665 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2666 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2667
2668 // ((X << C1)*C2) == (X * (C2 << C1))
2669 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2670 if (SI->getOpcode() == Instruction::Shl)
2671 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002672 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002673 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002674
2675 if (CI->isZero())
2676 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2677 if (CI->equalsInt(1)) // X * 1 == X
2678 return ReplaceInstUsesWith(I, Op0);
2679 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002680 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002681
2682 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2683 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002684 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002685 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002686 }
Chris Lattner6297fc72008-08-11 22:06:05 +00002687 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedman6e058402009-07-14 02:01:53 +00002688 if (Op1->isNullValue())
2689 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky94418732008-11-27 20:21:08 +00002690
2691 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2692 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002693 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00002694
2695 // As above, vector X*splat(1.0) -> X in all defined cases.
2696 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002697 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2698 if (CI->equalsInt(1))
2699 return ReplaceInstUsesWith(I, Op0);
2700 }
2701 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002702 }
2703
2704 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2705 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002706 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002707 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnerc7694852009-08-30 07:44:24 +00002708 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2709 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
Gabor Greifa645dd32008-05-16 19:29:10 +00002710 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002711
2712 }
2713
2714 // Try to fold constant mul into select arguments.
2715 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2716 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2717 return R;
2718
2719 if (isa<PHINode>(Op0))
2720 if (Instruction *NV = FoldOpIntoPhi(I))
2721 return NV;
2722 }
2723
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002724 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2725 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002726 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002727
Nick Lewycky1c246402008-11-21 07:33:58 +00002728 // (X / Y) * Y = X - (X % Y)
2729 // (X / Y) * -Y = (X % Y) - X
2730 {
2731 Value *Op1 = I.getOperand(1);
2732 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2733 if (!BO ||
2734 (BO->getOpcode() != Instruction::UDiv &&
2735 BO->getOpcode() != Instruction::SDiv)) {
2736 Op1 = Op0;
2737 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2738 }
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002739 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00002740 if (BO && BO->hasOneUse() &&
2741 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2742 (BO->getOpcode() == Instruction::UDiv ||
2743 BO->getOpcode() == Instruction::SDiv)) {
2744 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2745
Dan Gohman07878902009-08-12 16:33:09 +00002746 // If the division is exact, X % Y is zero.
2747 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2748 if (SDiv->isExact()) {
2749 if (Op1BO == Op1)
2750 return ReplaceInstUsesWith(I, Op0BO);
2751 else
2752 return BinaryOperator::CreateNeg(Op0BO);
2753 }
2754
Chris Lattnerc7694852009-08-30 07:44:24 +00002755 Value *Rem;
Nick Lewycky1c246402008-11-21 07:33:58 +00002756 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattnerc7694852009-08-30 07:44:24 +00002757 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00002758 else
Chris Lattnerc7694852009-08-30 07:44:24 +00002759 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00002760 Rem->takeName(BO);
2761
2762 if (Op1BO == Op1)
2763 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattnerc7694852009-08-30 07:44:24 +00002764 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00002765 }
2766 }
2767
Owen Anderson35b47072009-08-13 21:58:54 +00002768 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002769 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2770
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002771 // If one of the operands of the multiply is a cast from a boolean value, then
2772 // we know the bool is either zero or one, so this is a 'masking' multiply.
2773 // See if we can simplify things based on how the boolean was originally
2774 // formed.
2775 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002776 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson35b47072009-08-13 21:58:54 +00002777 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002778 BoolCast = CI;
2779 if (!BoolCast)
2780 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson35b47072009-08-13 21:58:54 +00002781 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002782 BoolCast = CI;
2783 if (BoolCast) {
2784 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2785 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2786 const Type *SCOpTy = SCIOp0->getType();
2787 bool TIS = false;
2788
2789 // If the icmp is true iff the sign bit of X is set, then convert this
2790 // multiply into a shift/and combination.
2791 if (isa<ConstantInt>(SCIOp1) &&
2792 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2793 TIS) {
2794 // Shift the X value right to turn it into "all signbits".
Owen Andersoneacb44d2009-07-24 23:12:02 +00002795 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002796 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnerc7694852009-08-30 07:44:24 +00002797 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2798 BoolCast->getOperand(0)->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002799
2800 // If the multiply type is not the same as the source type, sign extend
2801 // or truncate to the multiply type.
Chris Lattnerd6164c22009-08-30 20:01:10 +00002802 if (I.getType() != V->getType())
2803 V = Builder->CreateIntCast(V, I.getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002804
2805 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002806 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002807 }
2808 }
2809 }
2810
2811 return Changed ? &I : 0;
2812}
2813
Dan Gohman7ce405e2009-06-04 22:49:04 +00002814Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2815 bool Changed = SimplifyCommutative(I);
2816 Value *Op0 = I.getOperand(0);
2817
2818 // Simplify mul instructions with a constant RHS...
2819 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2820 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2821 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2822 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2823 if (Op1F->isExactlyValue(1.0))
2824 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2825 } else if (isa<VectorType>(Op1->getType())) {
2826 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2827 // As above, vector X*splat(1.0) -> X in all defined cases.
2828 if (Constant *Splat = Op1V->getSplatValue()) {
2829 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2830 if (F->isExactlyValue(1.0))
2831 return ReplaceInstUsesWith(I, Op0);
2832 }
2833 }
2834 }
2835
2836 // Try to fold constant mul into select arguments.
2837 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2838 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2839 return R;
2840
2841 if (isa<PHINode>(Op0))
2842 if (Instruction *NV = FoldOpIntoPhi(I))
2843 return NV;
2844 }
2845
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002846 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2847 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002848 return BinaryOperator::CreateFMul(Op0v, Op1v);
2849
2850 return Changed ? &I : 0;
2851}
2852
Chris Lattner76972db2008-07-14 00:15:52 +00002853/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2854/// instruction.
2855bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2856 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2857
2858 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2859 int NonNullOperand = -1;
2860 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2861 if (ST->isNullValue())
2862 NonNullOperand = 2;
2863 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2864 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2865 if (ST->isNullValue())
2866 NonNullOperand = 1;
2867
2868 if (NonNullOperand == -1)
2869 return false;
2870
2871 Value *SelectCond = SI->getOperand(0);
2872
2873 // Change the div/rem to use 'Y' instead of the select.
2874 I.setOperand(1, SI->getOperand(NonNullOperand));
2875
2876 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2877 // problem. However, the select, or the condition of the select may have
2878 // multiple uses. Based on our knowledge that the operand must be non-zero,
2879 // propagate the known value for the select into other uses of it, and
2880 // propagate a known value of the condition into its other users.
2881
2882 // If the select and condition only have a single use, don't bother with this,
2883 // early exit.
2884 if (SI->use_empty() && SelectCond->hasOneUse())
2885 return true;
2886
2887 // Scan the current block backward, looking for other uses of SI.
2888 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2889
2890 while (BBI != BBFront) {
2891 --BBI;
2892 // If we found a call to a function, we can't assume it will return, so
2893 // information from below it cannot be propagated above it.
2894 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2895 break;
2896
2897 // Replace uses of the select or its condition with the known values.
2898 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2899 I != E; ++I) {
2900 if (*I == SI) {
2901 *I = SI->getOperand(NonNullOperand);
Chris Lattner3183fb62009-08-30 06:13:40 +00002902 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00002903 } else if (*I == SelectCond) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00002904 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2905 ConstantInt::getFalse(*Context);
Chris Lattner3183fb62009-08-30 06:13:40 +00002906 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00002907 }
2908 }
2909
2910 // If we past the instruction, quit looking for it.
2911 if (&*BBI == SI)
2912 SI = 0;
2913 if (&*BBI == SelectCond)
2914 SelectCond = 0;
2915
2916 // If we ran out of things to eliminate, break out of the loop.
2917 if (SelectCond == 0 && SI == 0)
2918 break;
2919
2920 }
2921 return true;
2922}
2923
2924
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002925/// This function implements the transforms on div instructions that work
2926/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2927/// used by the visitors to those instructions.
2928/// @brief Transforms common to all three div instructions
2929Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2930 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2931
Chris Lattner653ef3c2008-02-19 06:12:18 +00002932 // undef / X -> 0 for integer.
2933 // undef / X -> undef for FP (the undef could be a snan).
2934 if (isa<UndefValue>(Op0)) {
2935 if (Op0->getType()->isFPOrFPVector())
2936 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00002937 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002938 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002939
2940 // X / undef -> undef
2941 if (isa<UndefValue>(Op1))
2942 return ReplaceInstUsesWith(I, Op1);
2943
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002944 return 0;
2945}
2946
2947/// This function implements the transforms common to both integer division
2948/// instructions (udiv and sdiv). It is called by the visitors to those integer
2949/// division instructions.
2950/// @brief Common integer divide transforms
2951Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2952 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2953
Chris Lattnercefb36c2008-05-16 02:59:42 +00002954 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002955 if (Op0 == Op1) {
2956 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00002957 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002958 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00002959 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00002960 }
2961
Owen Andersoneacb44d2009-07-24 23:12:02 +00002962 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002963 return ReplaceInstUsesWith(I, CI);
2964 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002965
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002966 if (Instruction *Common = commonDivTransforms(I))
2967 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002968
2969 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2970 // This does not apply for fdiv.
2971 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2972 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002973
2974 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2975 // div X, 1 == X
2976 if (RHS->equalsInt(1))
2977 return ReplaceInstUsesWith(I, Op0);
2978
2979 // (X / C1) / C2 -> X / (C1*C2)
2980 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2981 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2982 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002983 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002984 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00002985 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00002986 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002987 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002988 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002989 }
2990
2991 if (!RHS->isZero()) { // avoid X udiv 0
2992 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2993 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2994 return R;
2995 if (isa<PHINode>(Op0))
2996 if (Instruction *NV = FoldOpIntoPhi(I))
2997 return NV;
2998 }
2999 }
3000
3001 // 0 / X == 0, we don't need to preserve faults!
3002 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3003 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00003004 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003005
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003006 // It can't be division by zero, hence it must be division by one.
Owen Anderson35b47072009-08-13 21:58:54 +00003007 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003008 return ReplaceInstUsesWith(I, Op0);
3009
Nick Lewycky94418732008-11-27 20:21:08 +00003010 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3011 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3012 // div X, 1 == X
3013 if (X->isOne())
3014 return ReplaceInstUsesWith(I, Op0);
3015 }
3016
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003017 return 0;
3018}
3019
3020Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3021 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3022
3023 // Handle the integer div common cases
3024 if (Instruction *Common = commonIDivTransforms(I))
3025 return Common;
3026
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003027 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00003028 // X udiv C^2 -> X >> C
3029 // Check to see if this is an unsigned division with an exact power of 2,
3030 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003031 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003032 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003033 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003034
3035 // X udiv C, where C >= signbit
3036 if (C->getValue().isNegative()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003037 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersonaac28372009-07-31 20:28:14 +00003038 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003039 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003040 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003041 }
3042
3043 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3044 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3045 if (RHSI->getOpcode() == Instruction::Shl &&
3046 isa<ConstantInt>(RHSI->getOperand(0))) {
3047 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3048 if (C1.isPowerOf2()) {
3049 Value *N = RHSI->getOperand(1);
3050 const Type *NTy = N->getType();
Chris Lattnerc7694852009-08-30 07:44:24 +00003051 if (uint32_t C2 = C1.logBase2())
3052 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003053 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003054 }
3055 }
3056 }
3057
3058 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3059 // where C1&C2 are powers of two.
3060 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3061 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3062 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3063 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3064 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3065 // Compute the shift amounts
3066 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3067 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003068 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003069 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003070
3071 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003072 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003073 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003074
3075 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003076 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003077 }
3078 }
3079 return 0;
3080}
3081
3082Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3083 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3084
3085 // Handle the integer div common cases
3086 if (Instruction *Common = commonIDivTransforms(I))
3087 return Common;
3088
3089 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3090 // sdiv X, -1 == -X
3091 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00003092 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00003093
Dan Gohman07878902009-08-12 16:33:09 +00003094 // sdiv X, C --> ashr X, log2(C)
Dan Gohman31b6b132009-08-11 20:47:47 +00003095 if (cast<SDivOperator>(&I)->isExact() &&
3096 RHS->getValue().isNonNegative() &&
3097 RHS->getValue().isPowerOf2()) {
3098 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3099 RHS->getValue().exactLogBase2());
3100 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3101 }
Dan Gohman5ce93b32009-08-12 16:37:02 +00003102
3103 // -X/C --> X/-C provided the negation doesn't overflow.
3104 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3105 if (isa<Constant>(Sub->getOperand(0)) &&
3106 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohmanb5ed4492009-08-20 17:11:38 +00003107 Sub->hasNoSignedWrap())
Dan Gohman5ce93b32009-08-12 16:37:02 +00003108 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3109 ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003110 }
3111
3112 // If the sign bits of both operands are zero (i.e. we can prove they are
3113 // unsigned inputs), turn this into a udiv.
3114 if (I.getType()->isInteger()) {
3115 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003116 if (MaskedValueIsZero(Op0, Mask)) {
3117 if (MaskedValueIsZero(Op1, Mask)) {
3118 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3119 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3120 }
3121 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00003122 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00003123 ShiftedInt->getValue().isPowerOf2()) {
3124 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3125 // Safe because the only negative value (1 << Y) can take on is
3126 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3127 // the sign bit set.
3128 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3129 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003130 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003131 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003132
3133 return 0;
3134}
3135
3136Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3137 return commonDivTransforms(I);
3138}
3139
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003140/// This function implements the transforms on rem instructions that work
3141/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3142/// is used by the visitors to those instructions.
3143/// @brief Transforms common to all three rem instructions
3144Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3145 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3146
Chris Lattner653ef3c2008-02-19 06:12:18 +00003147 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3148 if (I.getType()->isFPOrFPVector())
3149 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00003150 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003151 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003152 if (isa<UndefValue>(Op1))
3153 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3154
3155 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003156 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3157 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003158
3159 return 0;
3160}
3161
3162/// This function implements the transforms common to both integer remainder
3163/// instructions (urem and srem). It is called by the visitors to those integer
3164/// remainder instructions.
3165/// @brief Common integer remainder transforms
3166Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3167 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3168
3169 if (Instruction *common = commonRemTransforms(I))
3170 return common;
3171
Dale Johannesena51f7372009-01-21 00:35:19 +00003172 // 0 % X == 0 for integer, we don't need to preserve faults!
3173 if (Constant *LHS = dyn_cast<Constant>(Op0))
3174 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00003175 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003176
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003177 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3178 // X % 0 == undef, we don't need to preserve faults!
3179 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003180 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003181
3182 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003183 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003184
3185 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3186 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3187 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3188 return R;
3189 } else if (isa<PHINode>(Op0I)) {
3190 if (Instruction *NV = FoldOpIntoPhi(I))
3191 return NV;
3192 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003193
3194 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003195 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003196 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003197 }
3198 }
3199
3200 return 0;
3201}
3202
3203Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3204 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3205
3206 if (Instruction *common = commonIRemTransforms(I))
3207 return common;
3208
3209 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3210 // X urem C^2 -> X and C
3211 // Check to see if this is an unsigned remainder with an exact power of 2,
3212 // if so, convert to a bitwise and.
3213 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3214 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003215 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003216 }
3217
3218 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3219 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3220 if (RHSI->getOpcode() == Instruction::Shl &&
3221 isa<ConstantInt>(RHSI->getOperand(0))) {
3222 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00003223 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00003224 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003225 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003226 }
3227 }
3228 }
3229
3230 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3231 // where C1&C2 are powers of two.
3232 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3233 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3234 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3235 // STO == 0 and SFO == 0 handled above.
3236 if ((STO->getValue().isPowerOf2()) &&
3237 (SFO->getValue().isPowerOf2())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003238 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3239 SI->getName()+".t");
3240 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3241 SI->getName()+".f");
Gabor Greifd6da1d02008-04-06 20:25:17 +00003242 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003243 }
3244 }
3245 }
3246
3247 return 0;
3248}
3249
3250Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3251 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3252
Dan Gohmandb3dd962007-11-05 23:16:33 +00003253 // Handle the integer rem common cases
Chris Lattner4796b622009-08-30 06:22:51 +00003254 if (Instruction *Common = commonIRemTransforms(I))
3255 return Common;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003256
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003257 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003258 if (!isa<Constant>(RHSNeg) ||
3259 (isa<ConstantInt>(RHSNeg) &&
3260 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003261 // X % -Y -> X % Y
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003262 Worklist.AddValue(I.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003263 I.setOperand(1, RHSNeg);
3264 return &I;
3265 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003266
Dan Gohmandb3dd962007-11-05 23:16:33 +00003267 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003268 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003269 if (I.getType()->isInteger()) {
3270 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3271 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3272 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003273 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003274 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003275 }
3276
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003277 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003278 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3279 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003280
Nick Lewyckyfd746832008-12-20 16:48:00 +00003281 bool hasNegative = false;
3282 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3283 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3284 if (RHS->getValue().isNegative())
3285 hasNegative = true;
3286
3287 if (hasNegative) {
3288 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003289 for (unsigned i = 0; i != VWidth; ++i) {
3290 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3291 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00003292 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003293 else
3294 Elts[i] = RHS;
3295 }
3296 }
3297
Owen Anderson2f422e02009-07-28 21:19:26 +00003298 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003299 if (NewRHSV != RHSV) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003300 Worklist.AddValue(I.getOperand(1));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003301 I.setOperand(1, NewRHSV);
3302 return &I;
3303 }
3304 }
3305 }
3306
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003307 return 0;
3308}
3309
3310Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3311 return commonRemTransforms(I);
3312}
3313
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003314// isOneBitSet - Return true if there is exactly one bit set in the specified
3315// constant.
3316static bool isOneBitSet(const ConstantInt *CI) {
3317 return CI->getValue().isPowerOf2();
3318}
3319
3320// isHighOnes - Return true if the constant is of the form 1+0+.
3321// This is the same as lowones(~X).
3322static bool isHighOnes(const ConstantInt *CI) {
3323 return (~CI->getValue() + 1).isPowerOf2();
3324}
3325
3326/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3327/// are carefully arranged to allow folding of expressions such as:
3328///
3329/// (A < B) | (A > B) --> (A != B)
3330///
3331/// Note that this is only valid if the first and second predicates have the
3332/// same sign. Is illegal to do: (A u< B) | (A s> B)
3333///
3334/// Three bits are used to represent the condition, as follows:
3335/// 0 A > B
3336/// 1 A == B
3337/// 2 A < B
3338///
3339/// <=> Value Definition
3340/// 000 0 Always false
3341/// 001 1 A > B
3342/// 010 2 A == B
3343/// 011 3 A >= B
3344/// 100 4 A < B
3345/// 101 5 A != B
3346/// 110 6 A <= B
3347/// 111 7 Always true
3348///
3349static unsigned getICmpCode(const ICmpInst *ICI) {
3350 switch (ICI->getPredicate()) {
3351 // False -> 0
3352 case ICmpInst::ICMP_UGT: return 1; // 001
3353 case ICmpInst::ICMP_SGT: return 1; // 001
3354 case ICmpInst::ICMP_EQ: return 2; // 010
3355 case ICmpInst::ICMP_UGE: return 3; // 011
3356 case ICmpInst::ICMP_SGE: return 3; // 011
3357 case ICmpInst::ICMP_ULT: return 4; // 100
3358 case ICmpInst::ICMP_SLT: return 4; // 100
3359 case ICmpInst::ICMP_NE: return 5; // 101
3360 case ICmpInst::ICMP_ULE: return 6; // 110
3361 case ICmpInst::ICMP_SLE: return 6; // 110
3362 // True -> 7
3363 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003364 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003365 return 0;
3366 }
3367}
3368
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003369/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3370/// predicate into a three bit mask. It also returns whether it is an ordered
3371/// predicate by reference.
3372static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3373 isOrdered = false;
3374 switch (CC) {
3375 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3376 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003377 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3378 case FCmpInst::FCMP_UGT: return 1; // 001
3379 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3380 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003381 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3382 case FCmpInst::FCMP_UGE: return 3; // 011
3383 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3384 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003385 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3386 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003387 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3388 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003389 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003390 default:
3391 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003392 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003393 return 0;
3394 }
3395}
3396
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003397/// getICmpValue - This is the complement of getICmpCode, which turns an
3398/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003399/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003400/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003401static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003402 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003403 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003404 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson4f720fa2009-07-31 17:39:07 +00003405 case 0: return ConstantInt::getFalse(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003406 case 1:
3407 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003408 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003409 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003410 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3411 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003412 case 3:
3413 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003414 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003415 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003416 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003417 case 4:
3418 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003419 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003420 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003421 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3422 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003423 case 6:
3424 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003425 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003426 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003427 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003428 case 7: return ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003429 }
3430}
3431
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003432/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3433/// opcode and two operands into either a FCmp instruction. isordered is passed
3434/// in to determine which kind of predicate to use in the new fcmp instruction.
3435static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003436 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003437 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003438 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003439 case 0:
3440 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003441 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003442 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003443 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003444 case 1:
3445 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003446 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003447 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003448 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003449 case 2:
3450 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003451 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003452 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003453 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003454 case 3:
3455 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003456 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003457 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003458 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003459 case 4:
3460 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003461 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003462 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003463 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003464 case 5:
3465 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003466 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003467 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003468 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003469 case 6:
3470 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003471 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003472 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003473 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003474 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003475 }
3476}
3477
Chris Lattner2972b822008-11-16 04:55:20 +00003478/// PredicatesFoldable - Return true if both predicates match sign or if at
3479/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003480static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3481 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattner2972b822008-11-16 04:55:20 +00003482 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3483 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003484}
3485
3486namespace {
3487// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3488struct FoldICmpLogical {
3489 InstCombiner &IC;
3490 Value *LHS, *RHS;
3491 ICmpInst::Predicate pred;
3492 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3493 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3494 pred(ICI->getPredicate()) {}
3495 bool shouldApply(Value *V) const {
3496 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3497 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003498 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3499 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003500 return false;
3501 }
3502 Instruction *apply(Instruction &Log) const {
3503 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3504 if (ICI->getOperand(0) != LHS) {
3505 assert(ICI->getOperand(1) == LHS);
3506 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3507 }
3508
3509 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3510 unsigned LHSCode = getICmpCode(ICI);
3511 unsigned RHSCode = getICmpCode(RHSICI);
3512 unsigned Code;
3513 switch (Log.getOpcode()) {
3514 case Instruction::And: Code = LHSCode & RHSCode; break;
3515 case Instruction::Or: Code = LHSCode | RHSCode; break;
3516 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003517 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003518 }
3519
3520 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3521 ICmpInst::isSignedPredicate(ICI->getPredicate());
3522
Owen Anderson24be4c12009-07-03 00:17:18 +00003523 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003524 if (Instruction *I = dyn_cast<Instruction>(RV))
3525 return I;
3526 // Otherwise, it's a constant boolean value...
3527 return IC.ReplaceInstUsesWith(Log, RV);
3528 }
3529};
3530} // end anonymous namespace
3531
3532// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3533// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3534// guaranteed to be a binary operator.
3535Instruction *InstCombiner::OptAndOp(Instruction *Op,
3536 ConstantInt *OpRHS,
3537 ConstantInt *AndRHS,
3538 BinaryOperator &TheAnd) {
3539 Value *X = Op->getOperand(0);
3540 Constant *Together = 0;
3541 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00003542 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003543
3544 switch (Op->getOpcode()) {
3545 case Instruction::Xor:
3546 if (Op->hasOneUse()) {
3547 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattnerc7694852009-08-30 07:44:24 +00003548 Value *And = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003549 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003550 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003551 }
3552 break;
3553 case Instruction::Or:
3554 if (Together == AndRHS) // (X | C) & C --> C
3555 return ReplaceInstUsesWith(TheAnd, AndRHS);
3556
3557 if (Op->hasOneUse() && Together != OpRHS) {
3558 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattnerc7694852009-08-30 07:44:24 +00003559 Value *Or = Builder->CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003560 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003561 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003562 }
3563 break;
3564 case Instruction::Add:
3565 if (Op->hasOneUse()) {
3566 // Adding a one to a single bit bit-field should be turned into an XOR
3567 // of the bit. First thing to check is to see if this AND is with a
3568 // single bit constant.
3569 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3570
3571 // If there is only one bit set...
3572 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3573 // Ok, at this point, we know that we are masking the result of the
3574 // ADD down to exactly one bit. If the constant we are adding has
3575 // no bits set below this bit, then we can eliminate the ADD.
3576 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3577
3578 // Check to see if any bits below the one bit set in AndRHSV are set.
3579 if ((AddRHS & (AndRHSV-1)) == 0) {
3580 // If not, the only thing that can effect the output of the AND is
3581 // the bit specified by AndRHSV. If that bit is set, the effect of
3582 // the XOR is to toggle the bit. If it is clear, then the ADD has
3583 // no effect.
3584 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3585 TheAnd.setOperand(0, X);
3586 return &TheAnd;
3587 } else {
3588 // Pull the XOR out of the AND.
Chris Lattnerc7694852009-08-30 07:44:24 +00003589 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003590 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003591 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003592 }
3593 }
3594 }
3595 }
3596 break;
3597
3598 case Instruction::Shl: {
3599 // We know that the AND will not produce any of the bits shifted in, so if
3600 // the anded constant includes them, clear them now!
3601 //
3602 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3603 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3604 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003605 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003606
3607 if (CI->getValue() == ShlMask) {
3608 // Masking out bits that the shift already masks
3609 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3610 } else if (CI != AndRHS) { // Reducing bits set in and.
3611 TheAnd.setOperand(1, CI);
3612 return &TheAnd;
3613 }
3614 break;
3615 }
3616 case Instruction::LShr:
3617 {
3618 // We know that the AND will not produce any of the bits shifted in, so if
3619 // the anded constant includes them, clear them now! This only applies to
3620 // unsigned shifts, because a signed shr may bring in set bits!
3621 //
3622 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3623 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3624 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003625 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003626
3627 if (CI->getValue() == ShrMask) {
3628 // Masking out bits that the shift already masks.
3629 return ReplaceInstUsesWith(TheAnd, Op);
3630 } else if (CI != AndRHS) {
3631 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3632 return &TheAnd;
3633 }
3634 break;
3635 }
3636 case Instruction::AShr:
3637 // Signed shr.
3638 // See if this is shifting in some sign extension, then masking it out
3639 // with an and.
3640 if (Op->hasOneUse()) {
3641 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3642 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3643 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003644 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003645 if (C == AndRHS) { // Masking out bits shifted in.
3646 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3647 // Make the argument unsigned.
3648 Value *ShVal = Op->getOperand(0);
Chris Lattnerc7694852009-08-30 07:44:24 +00003649 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003650 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003651 }
3652 }
3653 break;
3654 }
3655 return 0;
3656}
3657
3658
3659/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3660/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3661/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3662/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3663/// insert new instructions.
3664Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3665 bool isSigned, bool Inside,
3666 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003667 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003668 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3669 "Lo is not <= Hi in range emission code!");
3670
3671 if (Inside) {
3672 if (Lo == Hi) // Trivially false.
Dan Gohmane6803b82009-08-25 23:17:54 +00003673 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003674
3675 // V >= Min && V < Hi --> V < Hi
3676 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3677 ICmpInst::Predicate pred = (isSigned ?
3678 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003679 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003680 }
3681
3682 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00003683 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattnerc7694852009-08-30 07:44:24 +00003684 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003685 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003686 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003687 }
3688
3689 if (Lo == Hi) // Trivially true.
Dan Gohmane6803b82009-08-25 23:17:54 +00003690 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003691
3692 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003693 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003694 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3695 ICmpInst::Predicate pred = (isSigned ?
3696 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003697 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003698 }
3699
3700 // Emit V-Lo >u Hi-1-Lo
3701 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00003702 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattnerc7694852009-08-30 07:44:24 +00003703 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003704 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003705 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003706}
3707
3708// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3709// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3710// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3711// not, since all 1s are not contiguous.
3712static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3713 const APInt& V = Val->getValue();
3714 uint32_t BitWidth = Val->getType()->getBitWidth();
3715 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3716
3717 // look for the first zero bit after the run of ones
3718 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3719 // look for the first non-zero bit
3720 ME = V.getActiveBits();
3721 return true;
3722}
3723
3724/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3725/// where isSub determines whether the operator is a sub. If we can fold one of
3726/// the following xforms:
3727///
3728/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3729/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3730/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3731///
3732/// return (A +/- B).
3733///
3734Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3735 ConstantInt *Mask, bool isSub,
3736 Instruction &I) {
3737 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3738 if (!LHSI || LHSI->getNumOperands() != 2 ||
3739 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3740
3741 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3742
3743 switch (LHSI->getOpcode()) {
3744 default: return 0;
3745 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00003746 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003747 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3748 if ((Mask->getValue().countLeadingZeros() +
3749 Mask->getValue().countPopulation()) ==
3750 Mask->getValue().getBitWidth())
3751 break;
3752
3753 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3754 // part, we don't need any explicit masks to take them out of A. If that
3755 // is all N is, ignore it.
3756 uint32_t MB = 0, ME = 0;
3757 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3758 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3759 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3760 if (MaskedValueIsZero(RHS, Mask))
3761 break;
3762 }
3763 }
3764 return 0;
3765 case Instruction::Or:
3766 case Instruction::Xor:
3767 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3768 if ((Mask->getValue().countLeadingZeros() +
3769 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00003770 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003771 break;
3772 return 0;
3773 }
3774
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003775 if (isSub)
Chris Lattnerc7694852009-08-30 07:44:24 +00003776 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3777 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003778}
3779
Chris Lattner0631ea72008-11-16 05:06:21 +00003780/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3781Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3782 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00003783 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00003784 ConstantInt *LHSCst, *RHSCst;
3785 ICmpInst::Predicate LHSCC, RHSCC;
3786
Chris Lattnerf3803482008-11-16 05:10:52 +00003787 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00003788 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00003789 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00003790 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00003791 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00003792 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003793
3794 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3795 // where C is a power of 2
3796 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3797 LHSCst->getValue().isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003798 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohmane6803b82009-08-25 23:17:54 +00003799 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerf3803482008-11-16 05:10:52 +00003800 }
3801
3802 // From here on, we only handle:
3803 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3804 if (Val != Val2) return 0;
3805
Chris Lattner0631ea72008-11-16 05:06:21 +00003806 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3807 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3808 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3809 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3810 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3811 return 0;
3812
3813 // We can't fold (ugt x, C) & (sgt x, C2).
3814 if (!PredicatesFoldable(LHSCC, RHSCC))
3815 return 0;
3816
3817 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003818 bool ShouldSwap;
Chris Lattner0631ea72008-11-16 05:06:21 +00003819 if (ICmpInst::isSignedPredicate(LHSCC) ||
3820 (ICmpInst::isEquality(LHSCC) &&
3821 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003822 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003823 else
Chris Lattner665298f2008-11-16 05:14:43 +00003824 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3825
3826 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003827 std::swap(LHS, RHS);
3828 std::swap(LHSCst, RHSCst);
3829 std::swap(LHSCC, RHSCC);
3830 }
3831
3832 // At this point, we know we have have two icmp instructions
3833 // comparing a value against two constants and and'ing the result
3834 // together. Because of the above check, we know that we only have
3835 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3836 // (from the FoldICmpLogical check above), that the two constants
3837 // are not equal and that the larger constant is on the RHS
3838 assert(LHSCst != RHSCst && "Compares not folded above?");
3839
3840 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003841 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003842 case ICmpInst::ICMP_EQ:
3843 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003844 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003845 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3846 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3847 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003848 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003849 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3850 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3851 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3852 return ReplaceInstUsesWith(I, LHS);
3853 }
3854 case ICmpInst::ICMP_NE:
3855 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003856 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003857 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003858 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00003859 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003860 break; // (X != 13 & X u< 15) -> no change
3861 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003862 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00003863 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003864 break; // (X != 13 & X s< 15) -> no change
3865 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3866 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3867 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3868 return ReplaceInstUsesWith(I, RHS);
3869 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003870 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00003871 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00003872 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmane6803b82009-08-25 23:17:54 +00003873 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003874 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00003875 }
3876 break; // (X != 13 & X != 15) -> no change
3877 }
3878 break;
3879 case ICmpInst::ICMP_ULT:
3880 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003881 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003882 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3883 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003884 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003885 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3886 break;
3887 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3888 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3889 return ReplaceInstUsesWith(I, LHS);
3890 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3891 break;
3892 }
3893 break;
3894 case ICmpInst::ICMP_SLT:
3895 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003896 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003897 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3898 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003899 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003900 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3901 break;
3902 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3903 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3904 return ReplaceInstUsesWith(I, LHS);
3905 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3906 break;
3907 }
3908 break;
3909 case ICmpInst::ICMP_UGT:
3910 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003911 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003912 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3913 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3914 return ReplaceInstUsesWith(I, RHS);
3915 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3916 break;
3917 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003918 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00003919 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003920 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003921 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003922 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003923 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003924 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3925 break;
3926 }
3927 break;
3928 case ICmpInst::ICMP_SGT:
3929 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003930 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003931 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3932 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3933 return ReplaceInstUsesWith(I, RHS);
3934 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3935 break;
3936 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003937 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00003938 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003939 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003940 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003941 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003942 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003943 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3944 break;
3945 }
3946 break;
3947 }
Chris Lattner0631ea72008-11-16 05:06:21 +00003948
3949 return 0;
3950}
3951
Chris Lattner93a359a2009-07-23 05:14:02 +00003952Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3953 FCmpInst *RHS) {
3954
3955 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3956 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3957 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3958 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3959 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3960 // If either of the constants are nans, then the whole thing returns
3961 // false.
3962 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00003963 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00003964 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner93a359a2009-07-23 05:14:02 +00003965 LHS->getOperand(0), RHS->getOperand(0));
3966 }
Chris Lattnercf373552009-07-23 05:32:17 +00003967
3968 // Handle vector zeros. This occurs because the canonical form of
3969 // "fcmp ord x,x" is "fcmp ord x, 0".
3970 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3971 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00003972 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnercf373552009-07-23 05:32:17 +00003973 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00003974 return 0;
3975 }
3976
3977 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3978 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3979 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3980
3981
3982 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3983 // Swap RHS operands to match LHS.
3984 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3985 std::swap(Op1LHS, Op1RHS);
3986 }
3987
3988 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3989 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3990 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00003991 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +00003992
3993 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00003994 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00003995 if (Op0CC == FCmpInst::FCMP_TRUE)
3996 return ReplaceInstUsesWith(I, RHS);
3997 if (Op1CC == FCmpInst::FCMP_TRUE)
3998 return ReplaceInstUsesWith(I, LHS);
3999
4000 bool Op0Ordered;
4001 bool Op1Ordered;
4002 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4003 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4004 if (Op1Pred == 0) {
4005 std::swap(LHS, RHS);
4006 std::swap(Op0Pred, Op1Pred);
4007 std::swap(Op0Ordered, Op1Ordered);
4008 }
4009 if (Op0Pred == 0) {
4010 // uno && ueq -> uno && (uno || eq) -> ueq
4011 // ord && olt -> ord && (ord && lt) -> olt
4012 if (Op0Ordered == Op1Ordered)
4013 return ReplaceInstUsesWith(I, RHS);
4014
4015 // uno && oeq -> uno && (ord && eq) -> false
4016 // uno && ord -> false
4017 if (!Op0Ordered)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004018 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004019 // ord && ueq -> ord && (uno || eq) -> oeq
4020 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4021 Op0LHS, Op0RHS, Context));
4022 }
4023 }
4024
4025 return 0;
4026}
4027
Chris Lattner0631ea72008-11-16 05:06:21 +00004028
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004029Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4030 bool Changed = SimplifyCommutative(I);
4031 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4032
4033 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00004034 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004035
4036 // and X, X = X
4037 if (Op0 == Op1)
4038 return ReplaceInstUsesWith(I, Op1);
4039
4040 // See if we can simplify any instructions used by the instruction whose sole
4041 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004042 if (SimplifyDemandedInstructionBits(I))
4043 return &I;
4044 if (isa<VectorType>(I.getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004045 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4046 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4047 return ReplaceInstUsesWith(I, I.getOperand(0));
4048 } else if (isa<ConstantAggregateZero>(Op1)) {
4049 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4050 }
4051 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00004052
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004053 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4054 const APInt& AndRHSMask = AndRHS->getValue();
4055 APInt NotAndRHS(~AndRHSMask);
4056
4057 // Optimize a variety of ((val OP C1) & C2) combinations...
4058 if (isa<BinaryOperator>(Op0)) {
4059 Instruction *Op0I = cast<Instruction>(Op0);
4060 Value *Op0LHS = Op0I->getOperand(0);
4061 Value *Op0RHS = Op0I->getOperand(1);
4062 switch (Op0I->getOpcode()) {
4063 case Instruction::Xor:
4064 case Instruction::Or:
4065 // If the mask is only needed on one incoming arm, push it up.
4066 if (Op0I->hasOneUse()) {
4067 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4068 // Not masking anything out for the LHS, move to RHS.
Chris Lattnerc7694852009-08-30 07:44:24 +00004069 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4070 Op0RHS->getName()+".masked");
Gabor Greifa645dd32008-05-16 19:29:10 +00004071 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004072 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4073 }
4074 if (!isa<Constant>(Op0RHS) &&
4075 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4076 // Not masking anything out for the RHS, move to LHS.
Chris Lattnerc7694852009-08-30 07:44:24 +00004077 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4078 Op0LHS->getName()+".masked");
Gabor Greifa645dd32008-05-16 19:29:10 +00004079 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004080 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4081 }
4082 }
4083
4084 break;
4085 case Instruction::Add:
4086 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4087 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4088 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4089 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004090 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004091 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004092 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004093 break;
4094
4095 case Instruction::Sub:
4096 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4097 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4098 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4099 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004100 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004101
Nick Lewyckya349ba42008-07-10 05:51:40 +00004102 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4103 // has 1's for all bits that the subtraction with A might affect.
4104 if (Op0I->hasOneUse()) {
4105 uint32_t BitWidth = AndRHSMask.getBitWidth();
4106 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4107 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4108
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004109 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004110 if (!(A && A->isZero()) && // avoid infinite recursion.
4111 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004112 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004113 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4114 }
4115 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004116 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004117
4118 case Instruction::Shl:
4119 case Instruction::LShr:
4120 // (1 << x) & 1 --> zext(x == 0)
4121 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004122 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004123 Value *NewICmp =
4124 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004125 return new ZExtInst(NewICmp, I.getType());
4126 }
4127 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004128 }
4129
4130 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4131 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4132 return Res;
4133 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4134 // If this is an integer truncation or change from signed-to-unsigned, and
4135 // if the source is an and/or with immediate, transform it. This
4136 // frequently occurs for bitfield accesses.
4137 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4138 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4139 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004140 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004141 if (CastOp->getOpcode() == Instruction::And) {
4142 // Change: and (cast (and X, C1) to T), C2
4143 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4144 // This will fold the two constants together, which may allow
4145 // other simplifications.
Chris Lattnerc7694852009-08-30 07:44:24 +00004146 Value *NewCast = Builder->CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004147 CastOp->getOperand(0), I.getType(),
4148 CastOp->getName()+".shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004149 // trunc_or_bitcast(C1)&C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004150 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004151 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004152 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004153 } else if (CastOp->getOpcode() == Instruction::Or) {
4154 // Change: and (cast (or X, C1) to T), C2
4155 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004156 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004157 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00004158 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004159 return ReplaceInstUsesWith(I, AndRHS);
4160 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004161 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004162 }
4163 }
4164
4165 // Try to fold constant and into select arguments.
4166 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4167 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4168 return R;
4169 if (isa<PHINode>(Op0))
4170 if (Instruction *NV = FoldOpIntoPhi(I))
4171 return NV;
4172 }
4173
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004174 Value *Op0NotVal = dyn_castNotVal(Op0);
4175 Value *Op1NotVal = dyn_castNotVal(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004176
4177 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersonaac28372009-07-31 20:28:14 +00004178 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004179
4180 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4181 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004182 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4183 I.getName()+".demorgan");
Dan Gohmancdff2122009-08-12 16:23:25 +00004184 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004185 }
4186
4187 {
4188 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004189 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004190 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4191 return ReplaceInstUsesWith(I, Op1);
4192
4193 // (A|B) & ~(A&B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004194 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004195 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004196 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004197 }
4198 }
4199
Dan Gohmancdff2122009-08-12 16:23:25 +00004200 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004201 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4202 return ReplaceInstUsesWith(I, Op0);
4203
4204 // ~(A&B) & (A|B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004205 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004206 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004207 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004208 }
4209 }
4210
4211 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004212 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004213 if (A == Op1) { // (A^B)&A -> A&(A^B)
4214 I.swapOperands(); // Simplify below
4215 std::swap(Op0, Op1);
4216 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4217 cast<BinaryOperator>(Op0)->swapOperands();
4218 I.swapOperands(); // Simplify below
4219 std::swap(Op0, Op1);
4220 }
4221 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004222
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004223 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004224 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004225 if (B == Op0) { // B&(A^B) -> B&(B^A)
4226 cast<BinaryOperator>(Op1)->swapOperands();
4227 std::swap(A, B);
4228 }
Chris Lattnerc7694852009-08-30 07:44:24 +00004229 if (A == Op0) // A&(A^B) -> A & ~B
4230 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004231 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004232
4233 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00004234 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4235 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004236 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004237 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4238 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004239 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004240 }
4241
4242 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4243 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004244 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004245 return R;
4246
Chris Lattner0631ea72008-11-16 05:06:21 +00004247 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4248 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4249 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004250 }
4251
4252 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4253 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4254 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4255 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4256 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004257 if (SrcTy == Op1C->getOperand(0)->getType() &&
4258 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004259 // Only do this if the casts both really cause code to be generated.
4260 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4261 I.getType(), TD) &&
4262 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4263 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004264 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4265 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004266 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004267 }
4268 }
4269
4270 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4271 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4272 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4273 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4274 SI0->getOperand(1) == SI1->getOperand(1) &&
4275 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004276 Value *NewOp =
4277 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4278 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004279 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004280 SI1->getOperand(1));
4281 }
4282 }
4283
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004284 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004285 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004286 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4287 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4288 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004289 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004290
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004291 return Changed ? &I : 0;
4292}
4293
Chris Lattner567f5112008-10-05 02:13:19 +00004294/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4295/// capable of providing pieces of a bswap. The subexpression provides pieces
4296/// of a bswap if it is proven that each of the non-zero bytes in the output of
4297/// the expression came from the corresponding "byte swapped" byte in some other
4298/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4299/// we know that the expression deposits the low byte of %X into the high byte
4300/// of the bswap result and that all other bytes are zero. This expression is
4301/// accepted, the high byte of ByteValues is set to X to indicate a correct
4302/// match.
4303///
4304/// This function returns true if the match was unsuccessful and false if so.
4305/// On entry to the function the "OverallLeftShift" is a signed integer value
4306/// indicating the number of bytes that the subexpression is later shifted. For
4307/// example, if the expression is later right shifted by 16 bits, the
4308/// OverallLeftShift value would be -2 on entry. This is used to specify which
4309/// byte of ByteValues is actually being set.
4310///
4311/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4312/// byte is masked to zero by a user. For example, in (X & 255), X will be
4313/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4314/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4315/// always in the local (OverallLeftShift) coordinate space.
4316///
4317static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4318 SmallVector<Value*, 8> &ByteValues) {
4319 if (Instruction *I = dyn_cast<Instruction>(V)) {
4320 // If this is an or instruction, it may be an inner node of the bswap.
4321 if (I->getOpcode() == Instruction::Or) {
4322 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4323 ByteValues) ||
4324 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4325 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004326 }
Chris Lattner567f5112008-10-05 02:13:19 +00004327
4328 // If this is a logical shift by a constant multiple of 8, recurse with
4329 // OverallLeftShift and ByteMask adjusted.
4330 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4331 unsigned ShAmt =
4332 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4333 // Ensure the shift amount is defined and of a byte value.
4334 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4335 return true;
4336
4337 unsigned ByteShift = ShAmt >> 3;
4338 if (I->getOpcode() == Instruction::Shl) {
4339 // X << 2 -> collect(X, +2)
4340 OverallLeftShift += ByteShift;
4341 ByteMask >>= ByteShift;
4342 } else {
4343 // X >>u 2 -> collect(X, -2)
4344 OverallLeftShift -= ByteShift;
4345 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004346 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004347 }
4348
4349 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4350 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4351
4352 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4353 ByteValues);
4354 }
4355
4356 // If this is a logical 'and' with a mask that clears bytes, clear the
4357 // corresponding bytes in ByteMask.
4358 if (I->getOpcode() == Instruction::And &&
4359 isa<ConstantInt>(I->getOperand(1))) {
4360 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4361 unsigned NumBytes = ByteValues.size();
4362 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4363 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4364
4365 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4366 // If this byte is masked out by a later operation, we don't care what
4367 // the and mask is.
4368 if ((ByteMask & (1 << i)) == 0)
4369 continue;
4370
4371 // If the AndMask is all zeros for this byte, clear the bit.
4372 APInt MaskB = AndMask & Byte;
4373 if (MaskB == 0) {
4374 ByteMask &= ~(1U << i);
4375 continue;
4376 }
4377
4378 // If the AndMask is not all ones for this byte, it's not a bytezap.
4379 if (MaskB != Byte)
4380 return true;
4381
4382 // Otherwise, this byte is kept.
4383 }
4384
4385 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4386 ByteValues);
4387 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004388 }
4389
Chris Lattner567f5112008-10-05 02:13:19 +00004390 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4391 // the input value to the bswap. Some observations: 1) if more than one byte
4392 // is demanded from this input, then it could not be successfully assembled
4393 // into a byteswap. At least one of the two bytes would not be aligned with
4394 // their ultimate destination.
4395 if (!isPowerOf2_32(ByteMask)) return true;
4396 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004397
Chris Lattner567f5112008-10-05 02:13:19 +00004398 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4399 // is demanded, it needs to go into byte 0 of the result. This means that the
4400 // byte needs to be shifted until it lands in the right byte bucket. The
4401 // shift amount depends on the position: if the byte is coming from the high
4402 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4403 // low part, it must be shifted left.
4404 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4405 if (InputByteNo < ByteValues.size()/2) {
4406 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4407 return true;
4408 } else {
4409 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4410 return true;
4411 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004412
4413 // If the destination byte value is already defined, the values are or'd
4414 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004415 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004416 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004417 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004418 return false;
4419}
4420
4421/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4422/// If so, insert the new bswap intrinsic and return it.
4423Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4424 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004425 if (!ITy || ITy->getBitWidth() % 16 ||
4426 // ByteMask only allows up to 32-byte values.
4427 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004428 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4429
4430 /// ByteValues - For each byte of the result, we keep track of which value
4431 /// defines each byte.
4432 SmallVector<Value*, 8> ByteValues;
4433 ByteValues.resize(ITy->getBitWidth()/8);
4434
4435 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004436 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4437 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004438 return 0;
4439
4440 // Check to see if all of the bytes come from the same value.
4441 Value *V = ByteValues[0];
4442 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4443
4444 // Check to make sure that all of the bytes come from the same value.
4445 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4446 if (ByteValues[i] != V)
4447 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004448 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004449 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004450 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004451 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004452}
4453
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004454/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4455/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4456/// we can simplify this expression to "cond ? C : D or B".
4457static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004458 Value *C, Value *D,
4459 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004460 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004461 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004462 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004463 return 0;
4464
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004465 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00004466 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004467 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00004468 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004469 return SelectInst::Create(Cond, C, B);
4470 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00004471 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004472 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00004473 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004474 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004475 return 0;
4476}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004477
Chris Lattner0c678e52008-11-16 05:20:07 +00004478/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4479Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4480 ICmpInst *LHS, ICmpInst *RHS) {
4481 Value *Val, *Val2;
4482 ConstantInt *LHSCst, *RHSCst;
4483 ICmpInst::Predicate LHSCC, RHSCC;
4484
4485 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004486 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004487 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004488 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004489 m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00004490 return 0;
4491
4492 // From here on, we only handle:
4493 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4494 if (Val != Val2) return 0;
4495
4496 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4497 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4498 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4499 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4500 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4501 return 0;
4502
4503 // We can't fold (ugt x, C) | (sgt x, C2).
4504 if (!PredicatesFoldable(LHSCC, RHSCC))
4505 return 0;
4506
4507 // Ensure that the larger constant is on the RHS.
4508 bool ShouldSwap;
4509 if (ICmpInst::isSignedPredicate(LHSCC) ||
4510 (ICmpInst::isEquality(LHSCC) &&
4511 ICmpInst::isSignedPredicate(RHSCC)))
4512 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4513 else
4514 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4515
4516 if (ShouldSwap) {
4517 std::swap(LHS, RHS);
4518 std::swap(LHSCst, RHSCst);
4519 std::swap(LHSCC, RHSCC);
4520 }
4521
4522 // At this point, we know we have have two icmp instructions
4523 // comparing a value against two constants and or'ing the result
4524 // together. Because of the above check, we know that we only have
4525 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4526 // FoldICmpLogical check above), that the two constants are not
4527 // equal.
4528 assert(LHSCst != RHSCst && "Compares not folded above?");
4529
4530 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004531 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004532 case ICmpInst::ICMP_EQ:
4533 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004534 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004535 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004536 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004537 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00004538 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004539 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004540 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohmane6803b82009-08-25 23:17:54 +00004541 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004542 }
4543 break; // (X == 13 | X == 15) -> no change
4544 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4545 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4546 break;
4547 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4548 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4549 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4550 return ReplaceInstUsesWith(I, RHS);
4551 }
4552 break;
4553 case ICmpInst::ICMP_NE:
4554 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004555 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004556 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4557 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4558 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4559 return ReplaceInstUsesWith(I, LHS);
4560 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4561 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4562 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004563 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004564 }
4565 break;
4566 case ICmpInst::ICMP_ULT:
4567 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004568 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004569 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4570 break;
4571 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4572 // If RHSCst is [us]MAXINT, it is always false. Not handling
4573 // this can cause overflow.
4574 if (RHSCst->isMaxValue(false))
4575 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004576 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004577 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004578 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4579 break;
4580 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4581 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4582 return ReplaceInstUsesWith(I, RHS);
4583 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4584 break;
4585 }
4586 break;
4587 case ICmpInst::ICMP_SLT:
4588 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004589 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004590 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4591 break;
4592 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4593 // If RHSCst is [us]MAXINT, it is always false. Not handling
4594 // this can cause overflow.
4595 if (RHSCst->isMaxValue(true))
4596 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004597 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004598 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004599 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4600 break;
4601 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4602 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4603 return ReplaceInstUsesWith(I, RHS);
4604 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4605 break;
4606 }
4607 break;
4608 case ICmpInst::ICMP_UGT:
4609 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004610 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004611 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4612 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4613 return ReplaceInstUsesWith(I, LHS);
4614 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4615 break;
4616 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4617 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004618 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004619 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4620 break;
4621 }
4622 break;
4623 case ICmpInst::ICMP_SGT:
4624 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004625 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004626 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4627 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4628 return ReplaceInstUsesWith(I, LHS);
4629 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4630 break;
4631 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4632 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004633 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004634 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4635 break;
4636 }
4637 break;
4638 }
4639 return 0;
4640}
4641
Chris Lattner57e66fa2009-07-23 05:46:22 +00004642Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4643 FCmpInst *RHS) {
4644 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4645 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4646 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4647 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4648 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4649 // If either of the constants are nans, then the whole thing returns
4650 // true.
4651 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004652 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004653
4654 // Otherwise, no need to compare the two constants, compare the
4655 // rest.
Dan Gohmane6803b82009-08-25 23:17:54 +00004656 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004657 LHS->getOperand(0), RHS->getOperand(0));
4658 }
4659
4660 // Handle vector zeros. This occurs because the canonical form of
4661 // "fcmp uno x,x" is "fcmp uno x, 0".
4662 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4663 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004664 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004665 LHS->getOperand(0), RHS->getOperand(0));
4666
4667 return 0;
4668 }
4669
4670 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4671 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4672 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4673
4674 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4675 // Swap RHS operands to match LHS.
4676 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4677 std::swap(Op1LHS, Op1RHS);
4678 }
4679 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4680 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4681 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004682 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004683 Op0LHS, Op0RHS);
4684 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004685 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004686 if (Op0CC == FCmpInst::FCMP_FALSE)
4687 return ReplaceInstUsesWith(I, RHS);
4688 if (Op1CC == FCmpInst::FCMP_FALSE)
4689 return ReplaceInstUsesWith(I, LHS);
4690 bool Op0Ordered;
4691 bool Op1Ordered;
4692 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4693 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4694 if (Op0Ordered == Op1Ordered) {
4695 // If both are ordered or unordered, return a new fcmp with
4696 // or'ed predicates.
4697 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4698 Op0LHS, Op0RHS, Context);
4699 if (Instruction *I = dyn_cast<Instruction>(RV))
4700 return I;
4701 // Otherwise, it's a constant boolean value...
4702 return ReplaceInstUsesWith(I, RV);
4703 }
4704 }
4705 return 0;
4706}
4707
Bill Wendlingdae376a2008-12-01 08:23:25 +00004708/// FoldOrWithConstants - This helper function folds:
4709///
Bill Wendling236a1192008-12-02 05:09:00 +00004710/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004711///
4712/// into:
4713///
Bill Wendling236a1192008-12-02 05:09:00 +00004714/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004715///
Bill Wendling236a1192008-12-02 05:09:00 +00004716/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004717Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004718 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004719 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4720 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004721
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004722 Value *V1 = 0;
4723 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004724 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004725
Bill Wendling86ee3162008-12-02 06:18:11 +00004726 APInt Xor = CI1->getValue() ^ CI2->getValue();
4727 if (!Xor.isAllOnesValue()) return 0;
4728
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004729 if (V1 == A || V1 == B) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004730 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004731 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004732 }
4733
4734 return 0;
4735}
4736
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004737Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4738 bool Changed = SimplifyCommutative(I);
4739 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4740
4741 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersonaac28372009-07-31 20:28:14 +00004742 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004743
4744 // or X, X = X
4745 if (Op0 == Op1)
4746 return ReplaceInstUsesWith(I, Op0);
4747
4748 // See if we can simplify any instructions used by the instruction whose sole
4749 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004750 if (SimplifyDemandedInstructionBits(I))
4751 return &I;
4752 if (isa<VectorType>(I.getType())) {
4753 if (isa<ConstantAggregateZero>(Op1)) {
4754 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4755 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4756 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4757 return ReplaceInstUsesWith(I, I.getOperand(1));
4758 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004759 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004760
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004761 // or X, -1 == -1
4762 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4763 ConstantInt *C1 = 0; Value *X = 0;
4764 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004765 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004766 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004767 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004768 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004769 return BinaryOperator::CreateAnd(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004770 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004771 }
4772
4773 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004774 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004775 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004776 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004777 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004778 return BinaryOperator::CreateXor(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004779 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004780 }
4781
4782 // Try to fold constant and into select arguments.
4783 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4784 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4785 return R;
4786 if (isa<PHINode>(Op0))
4787 if (Instruction *NV = FoldOpIntoPhi(I))
4788 return NV;
4789 }
4790
4791 Value *A = 0, *B = 0;
4792 ConstantInt *C1 = 0, *C2 = 0;
4793
Dan Gohmancdff2122009-08-12 16:23:25 +00004794 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004795 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4796 return ReplaceInstUsesWith(I, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004797 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004798 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4799 return ReplaceInstUsesWith(I, Op0);
4800
4801 // (A | B) | C and A | (B | C) -> bswap if possible.
4802 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00004803 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4804 match(Op1, m_Or(m_Value(), m_Value())) ||
4805 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4806 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004807 if (Instruction *BSwap = MatchBSwap(I))
4808 return BSwap;
4809 }
4810
4811 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004812 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004813 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004814 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004815 Value *NOr = Builder->CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004816 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004817 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004818 }
4819
4820 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004821 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004822 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004823 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004824 Value *NOr = Builder->CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004825 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004826 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004827 }
4828
4829 // (A & C)|(B & D)
4830 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004831 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4832 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004833 Value *V1 = 0, *V2 = 0, *V3 = 0;
4834 C1 = dyn_cast<ConstantInt>(C);
4835 C2 = dyn_cast<ConstantInt>(D);
4836 if (C1 && C2) { // (A & C1)|(B & C2)
4837 // If we have: ((V + N) & C1) | (V & C2)
4838 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4839 // replace with V+N.
4840 if (C1->getValue() == ~C2->getValue()) {
4841 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohmancdff2122009-08-12 16:23:25 +00004842 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004843 // Add commutes, try both ways.
4844 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4845 return ReplaceInstUsesWith(I, A);
4846 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4847 return ReplaceInstUsesWith(I, A);
4848 }
4849 // Or commutes, try both ways.
4850 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004851 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004852 // Add commutes, try both ways.
4853 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4854 return ReplaceInstUsesWith(I, B);
4855 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4856 return ReplaceInstUsesWith(I, B);
4857 }
4858 }
4859 V1 = 0; V2 = 0; V3 = 0;
4860 }
4861
4862 // Check to see if we have any common things being and'ed. If so, find the
4863 // terms for V1 & (V2|V3).
4864 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4865 if (A == B) // (A & C)|(A & D) == A & (C|D)
4866 V1 = A, V2 = C, V3 = D;
4867 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4868 V1 = A, V2 = B, V3 = C;
4869 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4870 V1 = C, V2 = A, V3 = D;
4871 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4872 V1 = C, V2 = A, V3 = B;
4873
4874 if (V1) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004875 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00004876 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004877 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004878 }
Dan Gohman279952c2008-10-28 22:38:57 +00004879
Dan Gohman35b76162008-10-30 20:40:10 +00004880 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00004881 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004882 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004883 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004884 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004885 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004886 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004887 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004888 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004889
Bill Wendling22ca8352008-11-30 13:52:49 +00004890 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004891 if ((match(C, m_Not(m_Specific(D))) &&
4892 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004893 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004894 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004895 if ((match(A, m_Not(m_Specific(D))) &&
4896 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004897 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004898 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004899 if ((match(C, m_Not(m_Specific(B))) &&
4900 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004901 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004902 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004903 if ((match(A, m_Not(m_Specific(B))) &&
4904 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004905 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004906 }
4907
4908 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4909 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4910 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4911 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4912 SI0->getOperand(1) == SI1->getOperand(1) &&
4913 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004914 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4915 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004916 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004917 SI1->getOperand(1));
4918 }
4919 }
4920
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004921 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004922 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4923 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004924 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004925 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004926 }
4927 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004928 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4929 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004930 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004931 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004932 }
4933
Dan Gohmancdff2122009-08-12 16:23:25 +00004934 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004935 if (A == Op1) // ~A | A == -1
Owen Andersonaac28372009-07-31 20:28:14 +00004936 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004937 } else {
4938 A = 0;
4939 }
4940 // Note, A is still live here!
Dan Gohmancdff2122009-08-12 16:23:25 +00004941 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004942 if (Op0 == B)
Owen Andersonaac28372009-07-31 20:28:14 +00004943 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004944
4945 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4946 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004947 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohmancdff2122009-08-12 16:23:25 +00004948 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004949 }
4950 }
4951
4952 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4953 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004954 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004955 return R;
4956
Chris Lattner0c678e52008-11-16 05:20:07 +00004957 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4958 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4959 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004960 }
4961
4962 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004963 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004964 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4965 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004966 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4967 !isa<ICmpInst>(Op1C->getOperand(0))) {
4968 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004969 if (SrcTy == Op1C->getOperand(0)->getType() &&
4970 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00004971 // Only do this if the casts both really cause code to be
4972 // generated.
4973 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4974 I.getType(), TD) &&
4975 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4976 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004977 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4978 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004979 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004980 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004981 }
4982 }
Chris Lattner91882432007-10-24 05:38:08 +00004983 }
4984
4985
4986 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4987 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00004988 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4989 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4990 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004991 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004992
4993 return Changed ? &I : 0;
4994}
4995
Dan Gohman089efff2008-05-13 00:00:25 +00004996namespace {
4997
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004998// XorSelf - Implements: X ^ X --> 0
4999struct XorSelf {
5000 Value *RHS;
5001 XorSelf(Value *rhs) : RHS(rhs) {}
5002 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5003 Instruction *apply(BinaryOperator &Xor) const {
5004 return &Xor;
5005 }
5006};
5007
Dan Gohman089efff2008-05-13 00:00:25 +00005008}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005009
5010Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5011 bool Changed = SimplifyCommutative(I);
5012 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5013
Evan Chenge5cd8032008-03-25 20:07:13 +00005014 if (isa<UndefValue>(Op1)) {
5015 if (isa<UndefValue>(Op0))
5016 // Handle undef ^ undef -> 0 special case. This is a common
5017 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00005018 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005019 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005020 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005021
5022 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005023 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005024 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00005025 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005026 }
5027
5028 // See if we can simplify any instructions used by the instruction whose sole
5029 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005030 if (SimplifyDemandedInstructionBits(I))
5031 return &I;
5032 if (isa<VectorType>(I.getType()))
5033 if (isa<ConstantAggregateZero>(Op1))
5034 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005035
5036 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005037 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005038 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5039 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5040 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5041 if (Op0I->getOpcode() == Instruction::And ||
5042 Op0I->getOpcode() == Instruction::Or) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005043 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5044 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005045 Value *NotY =
5046 Builder->CreateNot(Op0I->getOperand(1),
5047 Op0I->getOperand(1)->getName()+".not");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005048 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005049 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattnerc7694852009-08-30 07:44:24 +00005050 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005051 }
5052 }
5053 }
5054 }
5055
5056
5057 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00005058 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005059 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005060 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005061 return new ICmpInst(ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005062 ICI->getOperand(0), ICI->getOperand(1));
5063
Nick Lewycky1405e922007-08-06 20:04:16 +00005064 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005065 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005066 FCI->getOperand(0), FCI->getOperand(1));
5067 }
5068
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005069 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5070 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5071 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5072 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5073 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattnerc7694852009-08-30 07:44:24 +00005074 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5075 (RHS == ConstantExpr::getCast(Opcode,
5076 ConstantInt::getTrue(*Context),
5077 Op0C->getDestTy()))) {
5078 CI->setPredicate(CI->getInversePredicate());
5079 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005080 }
5081 }
5082 }
5083 }
5084
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005085 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5086 // ~(c-X) == X-c-1 == X+(-c-1)
5087 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5088 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005089 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5090 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005091 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005092 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005093 }
5094
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005095 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005096 if (Op0I->getOpcode() == Instruction::Add) {
5097 // ~(X-c) --> (-c-1)-X
5098 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005099 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005100 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00005101 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005102 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00005103 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005104 } else if (RHS->getValue().isSignBit()) {
5105 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005106 Constant *C = ConstantInt::get(*Context,
5107 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005108 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005109
5110 }
5111 } else if (Op0I->getOpcode() == Instruction::Or) {
5112 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5113 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005114 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005115 // Anything in both C1 and C2 is known to be zero, remove it from
5116 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00005117 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5118 NewRHS = ConstantExpr::getAnd(NewRHS,
5119 ConstantExpr::getNot(CommonBits));
Chris Lattner3183fb62009-08-30 06:13:40 +00005120 Worklist.Add(Op0I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005121 I.setOperand(0, Op0I->getOperand(0));
5122 I.setOperand(1, NewRHS);
5123 return &I;
5124 }
5125 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005126 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005127 }
5128
5129 // Try to fold constant and into select arguments.
5130 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5131 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5132 return R;
5133 if (isa<PHINode>(Op0))
5134 if (Instruction *NV = FoldOpIntoPhi(I))
5135 return NV;
5136 }
5137
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005138 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005139 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00005140 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005141
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005142 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005143 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00005144 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005145
5146
5147 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5148 if (Op1I) {
5149 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005150 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005151 if (A == Op0) { // B^(B|A) == (A|B)^B
5152 Op1I->swapOperands();
5153 I.swapOperands();
5154 std::swap(Op0, Op1);
5155 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5156 I.swapOperands(); // Simplified below.
5157 std::swap(Op0, Op1);
5158 }
Dan Gohmancdff2122009-08-12 16:23:25 +00005159 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005160 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005161 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005162 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005163 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005164 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005165 if (A == Op0) { // A^(A&B) -> A^(B&A)
5166 Op1I->swapOperands();
5167 std::swap(A, B);
5168 }
5169 if (B == Op0) { // A^(B&A) -> (B&A)^A
5170 I.swapOperands(); // Simplified below.
5171 std::swap(Op0, Op1);
5172 }
5173 }
5174 }
5175
5176 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5177 if (Op0I) {
5178 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005179 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005180 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005181 if (A == Op1) // (B|A)^B == (A|B)^B
5182 std::swap(A, B);
Chris Lattnerc7694852009-08-30 07:44:24 +00005183 if (B == Op1) // (A|B)^B == A & ~B
5184 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohmancdff2122009-08-12 16:23:25 +00005185 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005186 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005187 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005188 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005189 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005190 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005191 if (A == Op1) // (A&B)^A -> (B&A)^A
5192 std::swap(A, B);
5193 if (B == Op1 && // (B&A)^A == ~B & A
5194 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerc7694852009-08-30 07:44:24 +00005195 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005196 }
5197 }
5198 }
5199
5200 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5201 if (Op0I && Op1I && Op0I->isShift() &&
5202 Op0I->getOpcode() == Op1I->getOpcode() &&
5203 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5204 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005205 Value *NewOp =
5206 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5207 Op0I->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005208 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005209 Op1I->getOperand(1));
5210 }
5211
5212 if (Op0I && Op1I) {
5213 Value *A, *B, *C, *D;
5214 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005215 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5216 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005217 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005218 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005219 }
5220 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005221 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5222 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005223 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005224 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005225 }
5226
5227 // (A & B)^(C & D)
5228 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005229 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5230 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005231 // (X & Y)^(X & Y) -> (Y^Z) & X
5232 Value *X = 0, *Y = 0, *Z = 0;
5233 if (A == C)
5234 X = A, Y = B, Z = D;
5235 else if (A == D)
5236 X = A, Y = B, Z = C;
5237 else if (B == C)
5238 X = B, Y = A, Z = D;
5239 else if (B == D)
5240 X = B, Y = A, Z = C;
5241
5242 if (X) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005243 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005244 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005245 }
5246 }
5247 }
5248
5249 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5250 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005251 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005252 return R;
5253
5254 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005255 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005256 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5257 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5258 const Type *SrcTy = Op0C->getOperand(0)->getType();
5259 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5260 // Only do this if the casts both really cause code to be generated.
5261 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5262 I.getType(), TD) &&
5263 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5264 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005265 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5266 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005267 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005268 }
5269 }
Chris Lattner91882432007-10-24 05:38:08 +00005270 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005271
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005272 return Changed ? &I : 0;
5273}
5274
Owen Anderson24be4c12009-07-03 00:17:18 +00005275static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005276 LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005277 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005278}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005279
Dan Gohman8fd520a2009-06-15 22:12:54 +00005280static bool HasAddOverflow(ConstantInt *Result,
5281 ConstantInt *In1, ConstantInt *In2,
5282 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005283 if (IsSigned)
5284 if (In2->getValue().isNegative())
5285 return Result->getValue().sgt(In1->getValue());
5286 else
5287 return Result->getValue().slt(In1->getValue());
5288 else
5289 return Result->getValue().ult(In1->getValue());
5290}
5291
Dan Gohman8fd520a2009-06-15 22:12:54 +00005292/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005293/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005294static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005295 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005296 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005297 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005298
Dan Gohman8fd520a2009-06-15 22:12:54 +00005299 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5300 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005301 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005302 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5303 ExtractElement(In1, Idx, Context),
5304 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005305 IsSigned))
5306 return true;
5307 }
5308 return false;
5309 }
5310
5311 return HasAddOverflow(cast<ConstantInt>(Result),
5312 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5313 IsSigned);
5314}
5315
5316static bool HasSubOverflow(ConstantInt *Result,
5317 ConstantInt *In1, ConstantInt *In2,
5318 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005319 if (IsSigned)
5320 if (In2->getValue().isNegative())
5321 return Result->getValue().slt(In1->getValue());
5322 else
5323 return Result->getValue().sgt(In1->getValue());
5324 else
5325 return Result->getValue().ugt(In1->getValue());
5326}
5327
Dan Gohman8fd520a2009-06-15 22:12:54 +00005328/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5329/// overflowed for this type.
5330static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005331 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005332 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005333 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005334
5335 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5336 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005337 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005338 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5339 ExtractElement(In1, Idx, Context),
5340 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005341 IsSigned))
5342 return true;
5343 }
5344 return false;
5345 }
5346
5347 return HasSubOverflow(cast<ConstantInt>(Result),
5348 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5349 IsSigned);
5350}
5351
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005352/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5353/// code necessary to compute the offset from the base pointer (without adding
5354/// in the base pointer). Return the result as a signed integer of intptr size.
5355static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005356 TargetData &TD = *IC.getTargetData();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005357 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson35b47072009-08-13 21:58:54 +00005358 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersonaac28372009-07-31 20:28:14 +00005359 Value *Result = Constant::getNullValue(IntPtrTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005360
5361 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005362 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005363 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5364
Gabor Greif17396002008-06-12 21:37:33 +00005365 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5366 ++i, ++GTI) {
5367 Value *Op = *i;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005368 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005369 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5370 if (OpC->isZero()) continue;
5371
5372 // Handle a struct index, which adds its field offset to the pointer.
5373 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5374 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5375
Chris Lattnerc7694852009-08-30 07:44:24 +00005376 Result = IC.Builder->CreateAdd(Result,
5377 ConstantInt::get(IntPtrTy, Size),
5378 GEP->getName()+".offs");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005379 continue;
5380 }
5381
Owen Andersoneacb44d2009-07-24 23:12:02 +00005382 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Anderson24be4c12009-07-03 00:17:18 +00005383 Constant *OC =
Owen Anderson02b48c32009-07-29 18:55:55 +00005384 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5385 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattnerc7694852009-08-30 07:44:24 +00005386 // Emit an add instruction.
5387 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005388 continue;
5389 }
5390 // Convert to correct type.
Chris Lattnerc7694852009-08-30 07:44:24 +00005391 if (Op->getType() != IntPtrTy)
5392 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005393 if (Size != 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005394 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattnerc7694852009-08-30 07:44:24 +00005395 // We'll let instcombine(mul) convert this to a shl if possible.
5396 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005397 }
5398
5399 // Emit an add instruction.
Chris Lattnerc7694852009-08-30 07:44:24 +00005400 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005401 }
5402 return Result;
5403}
5404
Chris Lattnereba75862008-04-22 02:53:33 +00005405
Dan Gohmanff9b4732009-07-17 22:16:21 +00005406/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5407/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5408/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5409/// be complex, and scales are involved. The above expression would also be
5410/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5411/// This later form is less amenable to optimization though, and we are allowed
5412/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattnereba75862008-04-22 02:53:33 +00005413///
5414/// If we can't emit an optimized form for this expression, this returns null.
5415///
5416static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5417 InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005418 TargetData &TD = *IC.getTargetData();
Chris Lattnereba75862008-04-22 02:53:33 +00005419 gep_type_iterator GTI = gep_type_begin(GEP);
5420
5421 // Check to see if this gep only has a single variable index. If so, and if
5422 // any constant indices are a multiple of its scale, then we can compute this
5423 // in terms of the scale of the variable index. For example, if the GEP
5424 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5425 // because the expression will cross zero at the same point.
5426 unsigned i, e = GEP->getNumOperands();
5427 int64_t Offset = 0;
5428 for (i = 1; i != e; ++i, ++GTI) {
5429 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5430 // Compute the aggregate offset of constant indices.
5431 if (CI->isZero()) continue;
5432
5433 // Handle a struct index, which adds its field offset to the pointer.
5434 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5435 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5436 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005437 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005438 Offset += Size*CI->getSExtValue();
5439 }
5440 } else {
5441 // Found our variable index.
5442 break;
5443 }
5444 }
5445
5446 // If there are no variable indices, we must have a constant offset, just
5447 // evaluate it the general way.
5448 if (i == e) return 0;
5449
5450 Value *VariableIdx = GEP->getOperand(i);
5451 // Determine the scale factor of the variable element. For example, this is
5452 // 4 if the variable index is into an array of i32.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005453 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005454
5455 // Verify that there are no other variable indices. If so, emit the hard way.
5456 for (++i, ++GTI; i != e; ++i, ++GTI) {
5457 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5458 if (!CI) return 0;
5459
5460 // Compute the aggregate offset of constant indices.
5461 if (CI->isZero()) continue;
5462
5463 // Handle a struct index, which adds its field offset to the pointer.
5464 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5465 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5466 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005467 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005468 Offset += Size*CI->getSExtValue();
5469 }
5470 }
5471
5472 // Okay, we know we have a single variable index, which must be a
5473 // pointer/array/vector index. If there is no offset, life is simple, return
5474 // the index.
5475 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5476 if (Offset == 0) {
5477 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5478 // we don't need to bother extending: the extension won't affect where the
5479 // computation crosses zero.
5480 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson35b47072009-08-13 21:58:54 +00005481 VariableIdx = new TruncInst(VariableIdx,
5482 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005483 VariableIdx->getName(), &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005484 return VariableIdx;
5485 }
5486
5487 // Otherwise, there is an index. The computation we will do will be modulo
5488 // the pointer size, so get it.
5489 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5490
5491 Offset &= PtrSizeMask;
5492 VariableScale &= PtrSizeMask;
5493
5494 // To do this transformation, any constant index must be a multiple of the
5495 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5496 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5497 // multiple of the variable scale.
5498 int64_t NewOffs = Offset / (int64_t)VariableScale;
5499 if (Offset != NewOffs*(int64_t)VariableScale)
5500 return 0;
5501
5502 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson35b47072009-08-13 21:58:54 +00005503 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattnereba75862008-04-22 02:53:33 +00005504 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005505 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005506 true /*SExt*/,
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005507 VariableIdx->getName(), &I);
Owen Andersoneacb44d2009-07-24 23:12:02 +00005508 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005509 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005510}
5511
5512
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005513/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5514/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohman17f46f72009-07-28 01:40:03 +00005515Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005516 ICmpInst::Predicate Cond,
5517 Instruction &I) {
Chris Lattnereba75862008-04-22 02:53:33 +00005518 // Look through bitcasts.
5519 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5520 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005521
5522 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohman17f46f72009-07-28 01:40:03 +00005523 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005524 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005525 // This transformation (ignoring the base and scales) is valid because we
Dan Gohman17f46f72009-07-28 01:40:03 +00005526 // know pointers can't overflow since the gep is inbounds. See if we can
5527 // output an optimized form.
Chris Lattnereba75862008-04-22 02:53:33 +00005528 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5529
5530 // If not, synthesize the offset the hard way.
5531 if (Offset == 0)
5532 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005533 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonaac28372009-07-31 20:28:14 +00005534 Constant::getNullValue(Offset->getType()));
Dan Gohman17f46f72009-07-28 01:40:03 +00005535 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005536 // If the base pointers are different, but the indices are the same, just
5537 // compare the base pointer.
5538 if (PtrBase != GEPRHS->getOperand(0)) {
5539 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5540 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5541 GEPRHS->getOperand(0)->getType();
5542 if (IndicesTheSame)
5543 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5544 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5545 IndicesTheSame = false;
5546 break;
5547 }
5548
5549 // If all indices are the same, just compare the base pointers.
5550 if (IndicesTheSame)
Dan Gohmane6803b82009-08-25 23:17:54 +00005551 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005552 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5553
5554 // Otherwise, the base pointers are different and the indices are
5555 // different, bail out.
5556 return 0;
5557 }
5558
5559 // If one of the GEPs has all zero indices, recurse.
5560 bool AllZeros = true;
5561 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5562 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5563 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5564 AllZeros = false;
5565 break;
5566 }
5567 if (AllZeros)
5568 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5569 ICmpInst::getSwappedPredicate(Cond), I);
5570
5571 // If the other GEP has all zero indices, recurse.
5572 AllZeros = true;
5573 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5574 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5575 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5576 AllZeros = false;
5577 break;
5578 }
5579 if (AllZeros)
5580 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5581
5582 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5583 // If the GEPs only differ by one index, compare it.
5584 unsigned NumDifferences = 0; // Keep track of # differences.
5585 unsigned DiffOperand = 0; // The operand that differs.
5586 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5587 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5588 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5589 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5590 // Irreconcilable differences.
5591 NumDifferences = 2;
5592 break;
5593 } else {
5594 if (NumDifferences++) break;
5595 DiffOperand = i;
5596 }
5597 }
5598
5599 if (NumDifferences == 0) // SAME GEP?
5600 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson35b47072009-08-13 21:58:54 +00005601 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005602 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005603
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005604 else if (NumDifferences == 1) {
5605 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5606 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5607 // Make sure we do a signed comparison here.
Dan Gohmane6803b82009-08-25 23:17:54 +00005608 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005609 }
5610 }
5611
5612 // Only lower this if the icmp is the only user of the GEP or if we expect
5613 // the result to fold to a constant!
Dan Gohmana80e2712009-07-21 23:21:54 +00005614 if (TD &&
5615 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005616 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5617 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5618 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5619 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005620 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005621 }
5622 }
5623 return 0;
5624}
5625
Chris Lattnere6b62d92008-05-19 20:18:56 +00005626/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5627///
5628Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5629 Instruction *LHSI,
5630 Constant *RHSC) {
5631 if (!isa<ConstantFP>(RHSC)) return 0;
5632 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5633
5634 // Get the width of the mantissa. We don't want to hack on conversions that
5635 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005636 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005637 if (MantissaWidth == -1) return 0; // Unknown.
5638
5639 // Check to see that the input is converted from an integer type that is small
5640 // enough that preserves all bits. TODO: check here for "known" sign bits.
5641 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005642 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005643
5644 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005645 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5646 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005647 ++InputSize;
5648
5649 // If the conversion would lose info, don't hack on this.
5650 if ((int)InputSize > MantissaWidth)
5651 return 0;
5652
5653 // Otherwise, we can potentially simplify the comparison. We know that it
5654 // will always come through as an integer value and we know the constant is
5655 // not a NAN (it would have been previously simplified).
5656 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5657
5658 ICmpInst::Predicate Pred;
5659 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005660 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnere6b62d92008-05-19 20:18:56 +00005661 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005662 case FCmpInst::FCMP_OEQ:
5663 Pred = ICmpInst::ICMP_EQ;
5664 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005665 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005666 case FCmpInst::FCMP_OGT:
5667 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5668 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005669 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005670 case FCmpInst::FCMP_OGE:
5671 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5672 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005673 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005674 case FCmpInst::FCMP_OLT:
5675 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5676 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005677 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005678 case FCmpInst::FCMP_OLE:
5679 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5680 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005681 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005682 case FCmpInst::FCMP_ONE:
5683 Pred = ICmpInst::ICMP_NE;
5684 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005685 case FCmpInst::FCMP_ORD:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005686 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005687 case FCmpInst::FCMP_UNO:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005688 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005689 }
5690
5691 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5692
5693 // Now we know that the APFloat is a normal number, zero or inf.
5694
Chris Lattnerf13ff492008-05-20 03:50:52 +00005695 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005696 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005697 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005698
Bill Wendling20636df2008-11-09 04:26:50 +00005699 if (!LHSUnsigned) {
5700 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5701 // and large values.
5702 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5703 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5704 APFloat::rmNearestTiesToEven);
5705 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5706 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5707 Pred == ICmpInst::ICMP_SLE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005708 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5709 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005710 }
5711 } else {
5712 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5713 // +INF and large values.
5714 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5715 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5716 APFloat::rmNearestTiesToEven);
5717 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5718 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5719 Pred == ICmpInst::ICMP_ULE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005720 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5721 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005722 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005723 }
5724
Bill Wendling20636df2008-11-09 04:26:50 +00005725 if (!LHSUnsigned) {
5726 // See if the RHS value is < SignedMin.
5727 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5728 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5729 APFloat::rmNearestTiesToEven);
5730 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5731 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5732 Pred == ICmpInst::ICMP_SGE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005733 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5734 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005735 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005736 }
5737
Bill Wendling20636df2008-11-09 04:26:50 +00005738 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5739 // [0, UMAX], but it may still be fractional. See if it is fractional by
5740 // casting the FP value to the integer value and back, checking for equality.
5741 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005742 Constant *RHSInt = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005743 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5744 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005745 if (!RHS.isZero()) {
5746 bool Equal = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005747 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5748 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005749 if (!Equal) {
5750 // If we had a comparison against a fractional value, we have to adjust
5751 // the compare predicate and sometimes the value. RHSC is rounded towards
5752 // zero at this point.
5753 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005754 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng14118132009-05-22 23:10:53 +00005755 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005756 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005757 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00005758 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005759 case ICmpInst::ICMP_ULE:
5760 // (float)int <= 4.4 --> int <= 4
5761 // (float)int <= -4.4 --> false
5762 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005763 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005764 break;
5765 case ICmpInst::ICMP_SLE:
5766 // (float)int <= 4.4 --> int <= 4
5767 // (float)int <= -4.4 --> int < -4
5768 if (RHS.isNegative())
5769 Pred = ICmpInst::ICMP_SLT;
5770 break;
5771 case ICmpInst::ICMP_ULT:
5772 // (float)int < -4.4 --> false
5773 // (float)int < 4.4 --> int <= 4
5774 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005775 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005776 Pred = ICmpInst::ICMP_ULE;
5777 break;
5778 case ICmpInst::ICMP_SLT:
5779 // (float)int < -4.4 --> int < -4
5780 // (float)int < 4.4 --> int <= 4
5781 if (!RHS.isNegative())
5782 Pred = ICmpInst::ICMP_SLE;
5783 break;
5784 case ICmpInst::ICMP_UGT:
5785 // (float)int > 4.4 --> int > 4
5786 // (float)int > -4.4 --> true
5787 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005788 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005789 break;
5790 case ICmpInst::ICMP_SGT:
5791 // (float)int > 4.4 --> int > 4
5792 // (float)int > -4.4 --> int >= -4
5793 if (RHS.isNegative())
5794 Pred = ICmpInst::ICMP_SGE;
5795 break;
5796 case ICmpInst::ICMP_UGE:
5797 // (float)int >= -4.4 --> true
5798 // (float)int >= 4.4 --> int > 4
5799 if (!RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005800 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005801 Pred = ICmpInst::ICMP_UGT;
5802 break;
5803 case ICmpInst::ICMP_SGE:
5804 // (float)int >= -4.4 --> int >= -4
5805 // (float)int >= 4.4 --> int > 4
5806 if (!RHS.isNegative())
5807 Pred = ICmpInst::ICMP_SGT;
5808 break;
5809 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005810 }
5811 }
5812
5813 // Lower this FP comparison into an appropriate integer version of the
5814 // comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00005815 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00005816}
5817
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005818Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5819 bool Changed = SimplifyCompare(I);
5820 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5821
5822 // Fold trivial predicates.
5823 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner41c09932009-09-02 05:12:37 +00005824 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005825 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner41c09932009-09-02 05:12:37 +00005826 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005827
5828 // Simplify 'fcmp pred X, X'
5829 if (Op0 == Op1) {
5830 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005831 default: llvm_unreachable("Unknown predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005832 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5833 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5834 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner41c09932009-09-02 05:12:37 +00005835 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005836 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5837 case FCmpInst::FCMP_OLT: // True if ordered and less than
5838 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner41c09932009-09-02 05:12:37 +00005839 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005840
5841 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5842 case FCmpInst::FCMP_ULT: // True if unordered or less than
5843 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5844 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5845 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5846 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersonaac28372009-07-31 20:28:14 +00005847 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005848 return &I;
5849
5850 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5851 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5852 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5853 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5854 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5855 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersonaac28372009-07-31 20:28:14 +00005856 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005857 return &I;
5858 }
5859 }
5860
5861 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner41c09932009-09-02 05:12:37 +00005862 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005863
5864 // Handle fcmp with constant RHS
5865 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005866 // If the constant is a nan, see if we can fold the comparison based on it.
5867 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5868 if (CFP->getValueAPF().isNaN()) {
5869 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson4f720fa2009-07-31 17:39:07 +00005870 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnerf13ff492008-05-20 03:50:52 +00005871 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5872 "Comparison must be either ordered or unordered!");
5873 // True if unordered.
Owen Anderson4f720fa2009-07-31 17:39:07 +00005874 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005875 }
5876 }
5877
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005878 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5879 switch (LHSI->getOpcode()) {
5880 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005881 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5882 // block. If in the same block, we're encouraging jump threading. If
5883 // not, we are just pessimizing the code by making an i1 phi.
5884 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00005885 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00005886 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005887 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005888 case Instruction::SIToFP:
5889 case Instruction::UIToFP:
5890 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5891 return NV;
5892 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005893 case Instruction::Select:
5894 // If either operand of the select is a constant, we can fold the
5895 // comparison into the select arms, which will cause one to be
5896 // constant folded and the select turned into a bitwise or.
5897 Value *Op1 = 0, *Op2 = 0;
5898 if (LHSI->hasOneUse()) {
5899 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5900 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005901 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005902 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00005903 Op2 = Builder->CreateFCmp(I.getPredicate(),
5904 LHSI->getOperand(2), RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005905 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5906 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005907 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005908 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00005909 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5910 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005911 }
5912 }
5913
5914 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005915 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005916 break;
5917 }
5918 }
5919
5920 return Changed ? &I : 0;
5921}
5922
5923Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5924 bool Changed = SimplifyCompare(I);
5925 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5926 const Type *Ty = Op0->getType();
5927
5928 // icmp X, X
5929 if (Op0 == Op1)
Chris Lattner41c09932009-09-02 05:12:37 +00005930 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005931 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005932
5933 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner41c09932009-09-02 05:12:37 +00005934 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lambf78cd322007-12-18 21:32:20 +00005935
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005936 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5937 // addresses never equal each other! We already know that Op0 != Op1.
Chris Lattner95ac4eb2009-10-05 02:47:47 +00005938 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005939 isa<ConstantPointerNull>(Op0)) &&
Chris Lattner95ac4eb2009-10-05 02:47:47 +00005940 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005941 isa<ConstantPointerNull>(Op1)))
Owen Anderson35b47072009-08-13 21:58:54 +00005942 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005943 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005944
5945 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson35b47072009-08-13 21:58:54 +00005946 if (Ty == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005947 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005948 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00005949 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattnerc7694852009-08-30 07:44:24 +00005950 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmancdff2122009-08-12 16:23:25 +00005951 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005952 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005953 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005954 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005955
5956 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00005957 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005958 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005959 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattnerc7694852009-08-30 07:44:24 +00005960 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00005961 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005962 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005963 case ICmpInst::ICMP_SGT:
5964 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005965 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005966 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00005967 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00005968 return BinaryOperator::CreateAnd(Not, Op0);
5969 }
5970 case ICmpInst::ICMP_UGE:
5971 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5972 // FALL THROUGH
5973 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattnerc7694852009-08-30 07:44:24 +00005974 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00005975 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005976 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005977 case ICmpInst::ICMP_SGE:
5978 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5979 // FALL THROUGH
5980 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00005981 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00005982 return BinaryOperator::CreateOr(Not, Op0);
5983 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005984 }
5985 }
5986
Dan Gohman7934d592009-04-25 17:12:48 +00005987 unsigned BitWidth = 0;
5988 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00005989 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5990 else if (Ty->isIntOrIntVector())
5991 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00005992
5993 bool isSignBit = false;
5994
Dan Gohman58c09632008-09-16 18:46:06 +00005995 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005996 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00005997 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00005998
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005999 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6000 if (I.isEquality() && CI->isNullValue() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006001 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006002 // (icmp cond A B) if cond is equality
Dan Gohmane6803b82009-08-25 23:17:54 +00006003 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00006004 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006005
Dan Gohman58c09632008-09-16 18:46:06 +00006006 // If we have an icmp le or icmp ge instruction, turn it into the
6007 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6008 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00006009 switch (I.getPredicate()) {
6010 default: break;
6011 case ICmpInst::ICMP_ULE:
6012 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006013 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006014 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006015 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006016 case ICmpInst::ICMP_SLE:
6017 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006018 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006019 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006020 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006021 case ICmpInst::ICMP_UGE:
6022 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006023 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006024 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006025 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006026 case ICmpInst::ICMP_SGE:
6027 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006028 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006029 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006030 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006031 }
6032
Chris Lattnera1308652008-07-11 05:40:05 +00006033 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006034 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006035 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006036 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6037 }
6038
6039 // See if we can fold the comparison based on range information we can get
6040 // by checking whether bits are known to be zero or one in the input.
6041 if (BitWidth != 0) {
6042 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6043 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6044
6045 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006046 isSignBit ? APInt::getSignBit(BitWidth)
6047 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006048 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006049 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006050 if (SimplifyDemandedBits(I.getOperandUse(1),
6051 APInt::getAllOnesValue(BitWidth),
6052 Op1KnownZero, Op1KnownOne, 0))
6053 return &I;
6054
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006055 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006056 // in. Compute the Min, Max and RHS values based on the known bits. For the
6057 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006058 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6059 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6060 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6061 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6062 Op0Min, Op0Max);
6063 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6064 Op1Min, Op1Max);
6065 } else {
6066 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6067 Op0Min, Op0Max);
6068 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6069 Op1Min, Op1Max);
6070 }
6071
Chris Lattnera1308652008-07-11 05:40:05 +00006072 // If Min and Max are known to be the same, then SimplifyDemandedBits
6073 // figured out that the LHS is a constant. Just constant fold this now so
6074 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006075 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006076 return new ICmpInst(I.getPredicate(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006077 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006078 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006079 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006080 ConstantInt::get(*Context, Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006081
Chris Lattnera1308652008-07-11 05:40:05 +00006082 // Based on the range information we know about the LHS, see if we can
6083 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006084 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006085 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner62d0f232008-07-11 05:08:55 +00006086 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006087 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006088 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006089 break;
6090 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006091 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006092 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006093 break;
6094 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006095 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006096 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006097 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006098 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006099 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006100 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006101 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6102 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006103 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006104 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006105
6106 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6107 if (CI->isMinValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006108 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006109 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006110 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006111 break;
6112 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006113 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006114 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006115 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006116 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006117
6118 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006119 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006120 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6121 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006122 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006123 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006124
6125 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6126 if (CI->isMaxValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006127 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006128 Constant::getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006129 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006130 break;
6131 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006132 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006133 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006134 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006135 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006136 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006137 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006138 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6139 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006140 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006141 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006142 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006143 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006144 case ICmpInst::ICMP_SGT:
6145 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006146 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006147 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006148 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006149
6150 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006151 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006152 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6153 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006154 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006155 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006156 }
6157 break;
6158 case ICmpInst::ICMP_SGE:
6159 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6160 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006161 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006162 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006163 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006164 break;
6165 case ICmpInst::ICMP_SLE:
6166 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6167 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006168 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006169 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006170 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006171 break;
6172 case ICmpInst::ICMP_UGE:
6173 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6174 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006175 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006176 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006177 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006178 break;
6179 case ICmpInst::ICMP_ULE:
6180 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6181 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006182 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006183 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006184 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006185 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006186 }
Dan Gohman7934d592009-04-25 17:12:48 +00006187
6188 // Turn a signed comparison into an unsigned one if both operands
6189 // are known to have the same sign.
6190 if (I.isSignedPredicate() &&
6191 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6192 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohmane6803b82009-08-25 23:17:54 +00006193 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006194 }
6195
6196 // Test if the ICmpInst instruction is used exclusively by a select as
6197 // part of a minimum or maximum operation. If so, refrain from doing
6198 // any other folding. This helps out other analyses which understand
6199 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6200 // and CodeGen. And in this case, at least one of the comparison
6201 // operands has at least one user besides the compare (the select),
6202 // which would often largely negate the benefit of folding anyway.
6203 if (I.hasOneUse())
6204 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6205 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6206 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6207 return 0;
6208
6209 // See if we are doing a comparison between a constant and an instruction that
6210 // can be folded into the comparison.
6211 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006212 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6213 // instruction, see if that instruction also has constants so that the
6214 // instruction can be folded into the icmp
6215 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6216 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6217 return Res;
6218 }
6219
6220 // Handle icmp with constant (but not simple integer constant) RHS
6221 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6222 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6223 switch (LHSI->getOpcode()) {
6224 case Instruction::GetElementPtr:
6225 if (RHSC->isNullValue()) {
6226 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6227 bool isAllZeros = true;
6228 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6229 if (!isa<Constant>(LHSI->getOperand(i)) ||
6230 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6231 isAllZeros = false;
6232 break;
6233 }
6234 if (isAllZeros)
Dan Gohmane6803b82009-08-25 23:17:54 +00006235 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersonaac28372009-07-31 20:28:14 +00006236 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006237 }
6238 break;
6239
6240 case Instruction::PHI:
Chris Lattner9b61abd2009-09-27 20:46:36 +00006241 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattnera2417ba2008-06-08 20:52:11 +00006242 // block. If in the same block, we're encouraging jump threading. If
6243 // not, we are just pessimizing the code by making an i1 phi.
6244 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00006245 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00006246 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006247 break;
6248 case Instruction::Select: {
6249 // If either operand of the select is a constant, we can fold the
6250 // comparison into the select arms, which will cause one to be
6251 // constant folded and the select turned into a bitwise or.
6252 Value *Op1 = 0, *Op2 = 0;
6253 if (LHSI->hasOneUse()) {
6254 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6255 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006256 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006257 // Insert a new ICmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006258 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6259 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006260 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6261 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006262 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006263 // Insert a new ICmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006264 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6265 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006266 }
6267 }
6268
6269 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006270 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006271 break;
6272 }
6273 case Instruction::Malloc:
6274 // If we have (malloc != null), and if the malloc has a single use, we
6275 // can assume it is successful and remove the malloc.
6276 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner3183fb62009-08-30 06:13:40 +00006277 Worklist.Add(LHSI);
Victor Hernandez48c3c542009-09-18 22:35:49 +00006278 return ReplaceInstUsesWith(I,
6279 ConstantInt::get(Type::getInt1Ty(*Context),
6280 !I.isTrueWhenEqual()));
6281 }
6282 break;
6283 case Instruction::Call:
6284 // If we have (malloc != null), and if the malloc has a single use, we
6285 // can assume it is successful and remove the malloc.
6286 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6287 isa<ConstantPointerNull>(RHSC)) {
6288 Worklist.Add(LHSI);
6289 return ReplaceInstUsesWith(I,
6290 ConstantInt::get(Type::getInt1Ty(*Context),
6291 !I.isTrueWhenEqual()));
6292 }
6293 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006294 }
6295 }
6296
6297 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohman17f46f72009-07-28 01:40:03 +00006298 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006299 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6300 return NI;
Dan Gohman17f46f72009-07-28 01:40:03 +00006301 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006302 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6303 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6304 return NI;
6305
6306 // Test to see if the operands of the icmp are casted versions of other
6307 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6308 // now.
6309 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6310 if (isa<PointerType>(Op0->getType()) &&
6311 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6312 // We keep moving the cast from the left operand over to the right
6313 // operand, where it can often be eliminated completely.
6314 Op0 = CI->getOperand(0);
6315
6316 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6317 // so eliminate it as well.
6318 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6319 Op1 = CI2->getOperand(0);
6320
6321 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006322 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006323 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00006324 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006325 } else {
6326 // Otherwise, cast the RHS right before the icmp
Chris Lattner78628292009-08-30 19:47:22 +00006327 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006328 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006329 }
Dan Gohmane6803b82009-08-25 23:17:54 +00006330 return new ICmpInst(I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006331 }
6332 }
6333
6334 if (isa<CastInst>(Op0)) {
6335 // Handle the special case of: icmp (cast bool to X), <cst>
6336 // This comes up when you have code like
6337 // int X = A < B;
6338 // if (X) ...
6339 // For generality, we handle any zero-extension of any operand comparison
6340 // with a constant or another cast from the same type.
6341 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6342 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6343 return R;
6344 }
6345
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006346 // See if it's the same type of instruction on the left and right.
6347 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6348 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006349 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006350 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006351 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006352 default: break;
6353 case Instruction::Add:
6354 case Instruction::Sub:
6355 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006356 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohmane6803b82009-08-25 23:17:54 +00006357 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006358 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006359 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6360 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6361 if (CI->getValue().isSignBit()) {
6362 ICmpInst::Predicate Pred = I.isSignedPredicate()
6363 ? I.getUnsignedPredicate()
6364 : I.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006365 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006366 Op1I->getOperand(0));
6367 }
6368
6369 if (CI->getValue().isMaxSignedValue()) {
6370 ICmpInst::Predicate Pred = I.isSignedPredicate()
6371 ? I.getUnsignedPredicate()
6372 : I.getSignedPredicate();
6373 Pred = I.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006374 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006375 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006376 }
6377 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006378 break;
6379 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006380 if (!I.isEquality())
6381 break;
6382
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006383 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6384 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6385 // Mask = -1 >> count-trailing-zeros(Cst).
6386 if (!CI->isZero() && !CI->isOne()) {
6387 const APInt &AP = CI->getValue();
Owen Andersoneacb44d2009-07-24 23:12:02 +00006388 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006389 APInt::getLowBitsSet(AP.getBitWidth(),
6390 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006391 AP.countTrailingZeros()));
Chris Lattnerc7694852009-08-30 07:44:24 +00006392 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6393 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohmane6803b82009-08-25 23:17:54 +00006394 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006395 }
6396 }
6397 break;
6398 }
6399 }
6400 }
6401 }
6402
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006403 // ~x < ~y --> y < x
6404 { Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00006405 if (match(Op0, m_Not(m_Value(A))) &&
6406 match(Op1, m_Not(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006407 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006408 }
6409
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006410 if (I.isEquality()) {
6411 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006412
6413 // -x == -y --> x == y
Dan Gohmancdff2122009-08-12 16:23:25 +00006414 if (match(Op0, m_Neg(m_Value(A))) &&
6415 match(Op1, m_Neg(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006416 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006417
Dan Gohmancdff2122009-08-12 16:23:25 +00006418 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006419 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6420 Value *OtherVal = A == Op1 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006421 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006422 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006423 }
6424
Dan Gohmancdff2122009-08-12 16:23:25 +00006425 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006426 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006427 ConstantInt *C1, *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00006428 if (match(B, m_ConstantInt(C1)) &&
6429 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006430 Constant *NC =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006431 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnerc7694852009-08-30 07:44:24 +00006432 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6433 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattner3b874082008-11-16 05:38:51 +00006434 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006435
6436 // A^B == A^D -> B == D
Dan Gohmane6803b82009-08-25 23:17:54 +00006437 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6438 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6439 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6440 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006441 }
6442 }
6443
Dan Gohmancdff2122009-08-12 16:23:25 +00006444 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006445 (A == Op0 || B == Op0)) {
6446 // A == (A^B) -> B == 0
6447 Value *OtherVal = A == Op0 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006448 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006449 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006450 }
Chris Lattner3b874082008-11-16 05:38:51 +00006451
6452 // (A-B) == A -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006453 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006454 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006455 Constant::getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006456
6457 // A == (A-B) -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006458 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006459 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006460 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006461
6462 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6463 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006464 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6465 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006466 Value *X = 0, *Y = 0, *Z = 0;
6467
6468 if (A == C) {
6469 X = B; Y = D; Z = A;
6470 } else if (A == D) {
6471 X = B; Y = C; Z = A;
6472 } else if (B == C) {
6473 X = A; Y = D; Z = B;
6474 } else if (B == D) {
6475 X = A; Y = C; Z = B;
6476 }
6477
6478 if (X) { // Build (X^Y) & Z
Chris Lattnerc7694852009-08-30 07:44:24 +00006479 Op1 = Builder->CreateXor(X, Y, "tmp");
6480 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006481 I.setOperand(0, Op1);
Owen Andersonaac28372009-07-31 20:28:14 +00006482 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006483 return &I;
6484 }
6485 }
6486 }
6487 return Changed ? &I : 0;
6488}
6489
6490
6491/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6492/// and CmpRHS are both known to be integer constants.
6493Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6494 ConstantInt *DivRHS) {
6495 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6496 const APInt &CmpRHSV = CmpRHS->getValue();
6497
6498 // FIXME: If the operand types don't match the type of the divide
6499 // then don't attempt this transform. The code below doesn't have the
6500 // logic to deal with a signed divide and an unsigned compare (and
6501 // vice versa). This is because (x /s C1) <s C2 produces different
6502 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6503 // (x /u C1) <u C2. Simply casting the operands and result won't
6504 // work. :( The if statement below tests that condition and bails
6505 // if it finds it.
6506 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6507 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6508 return 0;
6509 if (DivRHS->isZero())
6510 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006511 if (DivIsSigned && DivRHS->isAllOnesValue())
6512 return 0; // The overflow computation also screws up here
6513 if (DivRHS->isOne())
6514 return 0; // Not worth bothering, and eliminates some funny cases
6515 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006516
6517 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6518 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6519 // C2 (CI). By solving for X we can turn this into a range check
6520 // instead of computing a divide.
Owen Anderson02b48c32009-07-29 18:55:55 +00006521 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006522
6523 // Determine if the product overflows by seeing if the product is
6524 // not equal to the divide. Make sure we do the same kind of divide
6525 // as in the LHS instruction that we're folding.
Owen Anderson02b48c32009-07-29 18:55:55 +00006526 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6527 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006528
6529 // Get the ICmp opcode
6530 ICmpInst::Predicate Pred = ICI.getPredicate();
6531
6532 // Figure out the interval that is being checked. For example, a comparison
6533 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6534 // Compute this interval based on the constants involved and the signedness of
6535 // the compare/divide. This computes a half-open interval, keeping track of
6536 // whether either value in the interval overflows. After analysis each
6537 // overflow variable is set to 0 if it's corresponding bound variable is valid
6538 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6539 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006540 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006541
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006542 if (!DivIsSigned) { // udiv
6543 // e.g. X/5 op 3 --> [15, 20)
6544 LoBound = Prod;
6545 HiOverflow = LoOverflow = ProdOV;
6546 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006547 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006548 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006549 if (CmpRHSV == 0) { // (X / pos) op 0
6550 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006551 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006552 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006553 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006554 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6555 HiOverflow = LoOverflow = ProdOV;
6556 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006557 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006558 } else { // (X / pos) op neg
6559 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006560 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006561 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6562 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006563 ConstantInt* DivNeg =
Owen Anderson02b48c32009-07-29 18:55:55 +00006564 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Anderson24be4c12009-07-03 00:17:18 +00006565 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006566 true) ? -1 : 0;
6567 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006568 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006569 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006570 if (CmpRHSV == 0) { // (X / neg) op 0
6571 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006572 LoBound = AddOne(DivRHS);
Owen Anderson02b48c32009-07-29 18:55:55 +00006573 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006574 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6575 HiOverflow = 1; // [INTMIN+1, overflow)
6576 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6577 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006578 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006579 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006580 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006581 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6582 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006583 LoOverflow = AddWithOverflow(LoBound, HiBound,
6584 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006585 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006586 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6587 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006588 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006589 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006590 }
6591
6592 // Dividing by a negative swaps the condition. LT <-> GT
6593 Pred = ICmpInst::getSwappedPredicate(Pred);
6594 }
6595
6596 Value *X = DivI->getOperand(0);
6597 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006598 default: llvm_unreachable("Unhandled icmp opcode!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006599 case ICmpInst::ICMP_EQ:
6600 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006601 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006602 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006603 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006604 ICmpInst::ICMP_UGE, X, LoBound);
6605 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006606 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006607 ICmpInst::ICMP_ULT, X, HiBound);
6608 else
6609 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6610 case ICmpInst::ICMP_NE:
6611 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006612 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006613 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006614 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006615 ICmpInst::ICMP_ULT, X, LoBound);
6616 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006617 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006618 ICmpInst::ICMP_UGE, X, HiBound);
6619 else
6620 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6621 case ICmpInst::ICMP_ULT:
6622 case ICmpInst::ICMP_SLT:
6623 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006624 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006625 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006626 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006627 return new ICmpInst(Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006628 case ICmpInst::ICMP_UGT:
6629 case ICmpInst::ICMP_SGT:
6630 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006631 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006632 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006633 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006634 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohmane6803b82009-08-25 23:17:54 +00006635 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006636 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006637 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006638 }
6639}
6640
6641
6642/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6643///
6644Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6645 Instruction *LHSI,
6646 ConstantInt *RHS) {
6647 const APInt &RHSV = RHS->getValue();
6648
6649 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006650 case Instruction::Trunc:
6651 if (ICI.isEquality() && LHSI->hasOneUse()) {
6652 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6653 // of the high bits truncated out of x are known.
6654 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6655 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6656 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6657 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6658 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6659
6660 // If all the high bits are known, we can do this xform.
6661 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6662 // Pull in the high bits from known-ones set.
6663 APInt NewRHS(RHS->getValue());
6664 NewRHS.zext(SrcBits);
6665 NewRHS |= KnownOne;
Dan Gohmane6803b82009-08-25 23:17:54 +00006666 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006667 ConstantInt::get(*Context, NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00006668 }
6669 }
6670 break;
6671
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006672 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6673 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6674 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6675 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006676 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6677 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006678 Value *CompareVal = LHSI->getOperand(0);
6679
6680 // If the sign bit of the XorCST is not set, there is no change to
6681 // the operation, just stop using the Xor.
6682 if (!XorCST->getValue().isNegative()) {
6683 ICI.setOperand(0, CompareVal);
Chris Lattner3183fb62009-08-30 06:13:40 +00006684 Worklist.Add(LHSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006685 return &ICI;
6686 }
6687
6688 // Was the old condition true if the operand is positive?
6689 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6690
6691 // If so, the new one isn't.
6692 isTrueIfPositive ^= true;
6693
6694 if (isTrueIfPositive)
Dan Gohmane6803b82009-08-25 23:17:54 +00006695 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006696 SubOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006697 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006698 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006699 AddOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006700 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006701
6702 if (LHSI->hasOneUse()) {
6703 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6704 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6705 const APInt &SignBit = XorCST->getValue();
6706 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6707 ? ICI.getUnsignedPredicate()
6708 : ICI.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006709 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006710 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006711 }
6712
6713 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006714 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006715 const APInt &NotSignBit = XorCST->getValue();
6716 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6717 ? ICI.getUnsignedPredicate()
6718 : ICI.getSignedPredicate();
6719 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006720 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006721 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006722 }
6723 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006724 }
6725 break;
6726 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6727 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6728 LHSI->getOperand(0)->hasOneUse()) {
6729 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6730
6731 // If the LHS is an AND of a truncating cast, we can widen the
6732 // and/compare to be the input width without changing the value
6733 // produced, eliminating a cast.
6734 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6735 // We can do this transformation if either the AND constant does not
6736 // have its sign bit set or if it is an equality comparison.
6737 // Extending a relational comparison when we're checking the sign
6738 // bit would not work.
6739 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006740 (ICI.isEquality() ||
6741 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006742 uint32_t BitWidth =
6743 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6744 APInt NewCST = AndCST->getValue();
6745 NewCST.zext(BitWidth);
6746 APInt NewCI = RHSV;
6747 NewCI.zext(BitWidth);
Chris Lattnerc7694852009-08-30 07:44:24 +00006748 Value *NewAnd =
6749 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006750 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00006751 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006752 ConstantInt::get(*Context, NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006753 }
6754 }
6755
6756 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6757 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6758 // happens a LOT in code produced by the C front-end, for bitfield
6759 // access.
6760 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6761 if (Shift && !Shift->isShift())
6762 Shift = 0;
6763
6764 ConstantInt *ShAmt;
6765 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6766 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6767 const Type *AndTy = AndCST->getType(); // Type of the and.
6768
6769 // We can fold this as long as we can't shift unknown bits
6770 // into the mask. This can only happen with signed shift
6771 // rights, as they sign-extend.
6772 if (ShAmt) {
6773 bool CanFold = Shift->isLogicalShift();
6774 if (!CanFold) {
6775 // To test for the bad case of the signed shr, see if any
6776 // of the bits shifted in could be tested after the mask.
6777 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6778 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6779
6780 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6781 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6782 AndCST->getValue()) == 0)
6783 CanFold = true;
6784 }
6785
6786 if (CanFold) {
6787 Constant *NewCst;
6788 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006789 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006790 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006791 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006792
6793 // Check to see if we are shifting out any of the bits being
6794 // compared.
Owen Anderson02b48c32009-07-29 18:55:55 +00006795 if (ConstantExpr::get(Shift->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00006796 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006797 // If we shifted bits out, the fold is not going to work out.
6798 // As a special case, check to see if this means that the
6799 // result is always true or false now.
6800 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006801 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006802 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006803 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006804 } else {
6805 ICI.setOperand(1, NewCst);
6806 Constant *NewAndCST;
6807 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006808 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006809 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006810 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006811 LHSI->setOperand(1, NewAndCST);
6812 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +00006813 Worklist.Add(Shift); // Shift is dead.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006814 return &ICI;
6815 }
6816 }
6817 }
6818
6819 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6820 // preferable because it allows the C<<Y expression to be hoisted out
6821 // of a loop if Y is invariant and X is not.
6822 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00006823 ICI.isEquality() && !Shift->isArithmeticShift() &&
6824 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006825 // Compute C << Y.
6826 Value *NS;
6827 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerc7694852009-08-30 07:44:24 +00006828 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006829 } else {
6830 // Insert a logical shift.
Chris Lattnerc7694852009-08-30 07:44:24 +00006831 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006832 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006833
6834 // Compute X & (C << Y).
Chris Lattnerc7694852009-08-30 07:44:24 +00006835 Value *NewAnd =
6836 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006837
6838 ICI.setOperand(0, NewAnd);
6839 return &ICI;
6840 }
6841 }
6842 break;
6843
6844 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6845 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6846 if (!ShAmt) break;
6847
6848 uint32_t TypeBits = RHSV.getBitWidth();
6849
6850 // Check that the shift amount is in range. If not, don't perform
6851 // undefined shifts. When the shift is visited it will be
6852 // simplified.
6853 if (ShAmt->uge(TypeBits))
6854 break;
6855
6856 if (ICI.isEquality()) {
6857 // If we are comparing against bits always shifted out, the
6858 // comparison cannot succeed.
6859 Constant *Comp =
Owen Anderson02b48c32009-07-29 18:55:55 +00006860 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Anderson24be4c12009-07-03 00:17:18 +00006861 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006862 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6863 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00006864 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006865 return ReplaceInstUsesWith(ICI, Cst);
6866 }
6867
6868 if (LHSI->hasOneUse()) {
6869 // Otherwise strength reduce the shift into an and.
6870 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6871 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006872 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Anderson24be4c12009-07-03 00:17:18 +00006873 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006874
Chris Lattnerc7694852009-08-30 07:44:24 +00006875 Value *And =
6876 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006877 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006878 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006879 }
6880 }
6881
6882 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6883 bool TrueIfSigned = false;
6884 if (LHSI->hasOneUse() &&
6885 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6886 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneacb44d2009-07-24 23:12:02 +00006887 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006888 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattnerc7694852009-08-30 07:44:24 +00006889 Value *And =
6890 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006891 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00006892 And, Constant::getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006893 }
6894 break;
6895 }
6896
6897 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6898 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006899 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006900 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006901 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006902
Chris Lattner5ee84f82008-03-21 05:19:58 +00006903 // Check that the shift amount is in range. If not, don't perform
6904 // undefined shifts. When the shift is visited it will be
6905 // simplified.
6906 uint32_t TypeBits = RHSV.getBitWidth();
6907 if (ShAmt->uge(TypeBits))
6908 break;
6909
6910 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006911
Chris Lattner5ee84f82008-03-21 05:19:58 +00006912 // If we are comparing against bits always shifted out, the
6913 // comparison cannot succeed.
6914 APInt Comp = RHSV << ShAmtVal;
6915 if (LHSI->getOpcode() == Instruction::LShr)
6916 Comp = Comp.lshr(ShAmtVal);
6917 else
6918 Comp = Comp.ashr(ShAmtVal);
6919
6920 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6921 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00006922 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00006923 return ReplaceInstUsesWith(ICI, Cst);
6924 }
6925
6926 // Otherwise, check to see if the bits shifted out are known to be zero.
6927 // If so, we can compare against the unshifted value:
6928 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006929 if (LHSI->hasOneUse() &&
6930 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006931 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006932 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00006933 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006934 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006935
Evan Chengfb9292a2008-04-23 00:38:06 +00006936 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006937 // Otherwise strength reduce the shift into an and.
6938 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00006939 Constant *Mask = ConstantInt::get(*Context, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006940
Chris Lattnerc7694852009-08-30 07:44:24 +00006941 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6942 Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006943 return new ICmpInst(ICI.getPredicate(), And,
Owen Anderson02b48c32009-07-29 18:55:55 +00006944 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006945 }
6946 break;
6947 }
6948
6949 case Instruction::SDiv:
6950 case Instruction::UDiv:
6951 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6952 // Fold this div into the comparison, producing a range check.
6953 // Determine, based on the divide type, what the range is being
6954 // checked. If there is an overflow on the low or high side, remember
6955 // it, otherwise compute the range [low, hi) bounding the new value.
6956 // See: InsertRangeTest above for the kinds of replacements possible.
6957 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6958 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6959 DivRHS))
6960 return R;
6961 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006962
6963 case Instruction::Add:
6964 // Fold: icmp pred (add, X, C1), C2
6965
6966 if (!ICI.isEquality()) {
6967 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6968 if (!LHSC) break;
6969 const APInt &LHSV = LHSC->getValue();
6970
6971 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6972 .subtract(LHSV);
6973
6974 if (ICI.isSignedPredicate()) {
6975 if (CR.getLower().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006976 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006977 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006978 } else if (CR.getUpper().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006979 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006980 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006981 }
6982 } else {
6983 if (CR.getLower().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006984 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006985 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006986 } else if (CR.getUpper().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006987 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006988 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006989 }
6990 }
6991 }
6992 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006993 }
6994
6995 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6996 if (ICI.isEquality()) {
6997 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6998
6999 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7000 // the second operand is a constant, simplify a bit.
7001 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7002 switch (BO->getOpcode()) {
7003 case Instruction::SRem:
7004 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7005 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7006 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7007 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007008 Value *NewRem =
7009 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7010 BO->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00007011 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersonaac28372009-07-31 20:28:14 +00007012 Constant::getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007013 }
7014 }
7015 break;
7016 case Instruction::Add:
7017 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7018 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7019 if (BO->hasOneUse())
Dan Gohmane6803b82009-08-25 23:17:54 +00007020 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007021 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007022 } else if (RHSV == 0) {
7023 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7024 // efficiently invertible, or if the add has just this one use.
7025 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7026
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007027 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohmane6803b82009-08-25 23:17:54 +00007028 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007029 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohmane6803b82009-08-25 23:17:54 +00007030 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007031 else if (BO->hasOneUse()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007032 Value *Neg = Builder->CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007033 Neg->takeName(BO);
Dan Gohmane6803b82009-08-25 23:17:54 +00007034 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007035 }
7036 }
7037 break;
7038 case Instruction::Xor:
7039 // For the xor case, we can xor two constants together, eliminating
7040 // the explicit xor.
7041 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00007042 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007043 ConstantExpr::getXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007044
7045 // FALLTHROUGH
7046 case Instruction::Sub:
7047 // Replace (([sub|xor] A, B) != 0) with (A != B)
7048 if (RHSV == 0)
Dan Gohmane6803b82009-08-25 23:17:54 +00007049 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007050 BO->getOperand(1));
7051 break;
7052
7053 case Instruction::Or:
7054 // If bits are being or'd in that are not present in the constant we
7055 // are comparing against, then the comparison could never succeed!
7056 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007057 Constant *NotCI = ConstantExpr::getNot(RHS);
7058 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00007059 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007060 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007061 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007062 }
7063 break;
7064
7065 case Instruction::And:
7066 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7067 // If bits are being compared against that are and'd out, then the
7068 // comparison can never succeed!
7069 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007070 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007071 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007072 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007073
7074 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7075 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohmane6803b82009-08-25 23:17:54 +00007076 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007077 ICmpInst::ICMP_NE, LHSI,
Owen Andersonaac28372009-07-31 20:28:14 +00007078 Constant::getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007079
7080 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007081 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007082 Value *X = BO->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +00007083 Constant *Zero = Constant::getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007084 ICmpInst::Predicate pred = isICMP_NE ?
7085 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohmane6803b82009-08-25 23:17:54 +00007086 return new ICmpInst(pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007087 }
7088
7089 // ((X & ~7) == 0) --> X < 8
7090 if (RHSV == 0 && isHighOnes(BOC)) {
7091 Value *X = BO->getOperand(0);
Owen Anderson02b48c32009-07-29 18:55:55 +00007092 Constant *NegX = ConstantExpr::getNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007093 ICmpInst::Predicate pred = isICMP_NE ?
7094 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohmane6803b82009-08-25 23:17:54 +00007095 return new ICmpInst(pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007096 }
7097 }
7098 default: break;
7099 }
7100 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7101 // Handle icmp {eq|ne} <intrinsic>, intcst.
7102 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner3183fb62009-08-30 06:13:40 +00007103 Worklist.Add(II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007104 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007105 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007106 return &ICI;
7107 }
7108 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007109 }
7110 return 0;
7111}
7112
7113/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7114/// We only handle extending casts so far.
7115///
7116Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7117 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7118 Value *LHSCIOp = LHSCI->getOperand(0);
7119 const Type *SrcTy = LHSCIOp->getType();
7120 const Type *DestTy = LHSCI->getType();
7121 Value *RHSCIOp;
7122
7123 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7124 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007125 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7126 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007127 cast<IntegerType>(DestTy)->getBitWidth()) {
7128 Value *RHSOp = 0;
7129 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007130 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007131 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7132 RHSOp = RHSC->getOperand(0);
7133 // If the pointer types don't match, insert a bitcast.
7134 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner78628292009-08-30 19:47:22 +00007135 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007136 }
7137
7138 if (RHSOp)
Dan Gohmane6803b82009-08-25 23:17:54 +00007139 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007140 }
7141
7142 // The code below only handles extension cast instructions, so far.
7143 // Enforce this.
7144 if (LHSCI->getOpcode() != Instruction::ZExt &&
7145 LHSCI->getOpcode() != Instruction::SExt)
7146 return 0;
7147
7148 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7149 bool isSignedCmp = ICI.isSignedPredicate();
7150
7151 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7152 // Not an extension from the same type?
7153 RHSCIOp = CI->getOperand(0);
7154 if (RHSCIOp->getType() != LHSCIOp->getType())
7155 return 0;
7156
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007157 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007158 // and the other is a zext), then we can't handle this.
7159 if (CI->getOpcode() != LHSCI->getOpcode())
7160 return 0;
7161
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007162 // Deal with equality cases early.
7163 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007164 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007165
7166 // A signed comparison of sign extended values simplifies into a
7167 // signed comparison.
7168 if (isSignedCmp && isSignedExt)
Dan Gohmane6803b82009-08-25 23:17:54 +00007169 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007170
7171 // The other three cases all fold into an unsigned comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00007172 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007173 }
7174
7175 // If we aren't dealing with a constant on the RHS, exit early
7176 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7177 if (!CI)
7178 return 0;
7179
7180 // Compute the constant that would happen if we truncated to SrcTy then
7181 // reextended to DestTy.
Owen Anderson02b48c32009-07-29 18:55:55 +00007182 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7183 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007184 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007185
7186 // If the re-extended constant didn't change...
7187 if (Res2 == CI) {
7188 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7189 // For example, we might have:
Dan Gohman9e1657f2009-06-14 23:30:43 +00007190 // %A = sext i16 %X to i32
7191 // %B = icmp ugt i32 %A, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007192 // It is incorrect to transform this into
Dan Gohman9e1657f2009-06-14 23:30:43 +00007193 // %B = icmp ugt i16 %X, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007194 // because %A may have negative value.
7195 //
Chris Lattner3d816532008-07-11 04:09:09 +00007196 // However, we allow this when the compare is EQ/NE, because they are
7197 // signless.
7198 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007199 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00007200 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007201 }
7202
7203 // The re-extended constant changed so the constant cannot be represented
7204 // in the shorter type. Consequently, we cannot emit a simple comparison.
7205
7206 // First, handle some easy cases. We know the result cannot be equal at this
7207 // point so handle the ICI.isEquality() cases
7208 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007209 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007210 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007211 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007212
7213 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7214 // should have been folded away previously and not enter in here.
7215 Value *Result;
7216 if (isSignedCmp) {
7217 // We're performing a signed comparison.
7218 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00007219 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007220 else
Owen Anderson4f720fa2009-07-31 17:39:07 +00007221 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007222 } else {
7223 // We're performing an unsigned comparison.
7224 if (isSignedExt) {
7225 // We're performing an unsigned comp with a sign extended value.
7226 // This is true if the input is >= 0. [aka >s -1]
Owen Andersonaac28372009-07-31 20:28:14 +00007227 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattnerc7694852009-08-30 07:44:24 +00007228 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007229 } else {
7230 // Unsigned extend & unsigned compare -> always true.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007231 Result = ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007232 }
7233 }
7234
7235 // Finally, return the value computed.
7236 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007237 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007238 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007239
7240 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7241 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7242 "ICmp should be folded!");
7243 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00007244 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohmancdff2122009-08-12 16:23:25 +00007245 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007246}
7247
7248Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7249 return commonShiftTransforms(I);
7250}
7251
7252Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7253 return commonShiftTransforms(I);
7254}
7255
7256Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007257 if (Instruction *R = commonShiftTransforms(I))
7258 return R;
7259
7260 Value *Op0 = I.getOperand(0);
7261
7262 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7263 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7264 if (CSI->isAllOnesValue())
7265 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007266
Dan Gohman2526aea2009-06-16 19:55:29 +00007267 // See if we can turn a signed shr into an unsigned shr.
7268 if (MaskedValueIsZero(Op0,
7269 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7270 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7271
7272 // Arithmetic shifting an all-sign-bit value is a no-op.
7273 unsigned NumSignBits = ComputeNumSignBits(Op0);
7274 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7275 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007276
Chris Lattnere3c504f2007-12-06 01:59:46 +00007277 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007278}
7279
7280Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7281 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7282 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7283
7284 // shl X, 0 == X and shr X, 0 == X
7285 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00007286 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7287 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007288 return ReplaceInstUsesWith(I, Op0);
7289
7290 if (isa<UndefValue>(Op0)) {
7291 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7292 return ReplaceInstUsesWith(I, Op0);
7293 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007294 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007295 }
7296 if (isa<UndefValue>(Op1)) {
7297 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7298 return ReplaceInstUsesWith(I, Op0);
7299 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007300 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007301 }
7302
Dan Gohman2bc21562009-05-21 02:28:33 +00007303 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007304 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007305 return &I;
7306
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007307 // Try to fold constant and into select arguments.
7308 if (isa<Constant>(Op0))
7309 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7310 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7311 return R;
7312
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007313 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7314 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7315 return Res;
7316 return 0;
7317}
7318
7319Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7320 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007321 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007322
7323 // See if we can simplify any instructions used by the instruction whose sole
7324 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007325 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007326
Dan Gohman9e1657f2009-06-14 23:30:43 +00007327 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7328 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007329 //
7330 if (Op1->uge(TypeBits)) {
7331 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007332 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007333 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007334 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007335 return &I;
7336 }
7337 }
7338
7339 // ((X*C1) << C2) == (X * (C1 << C2))
7340 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7341 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7342 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007343 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007344 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007345
7346 // Try to fold constant and into select arguments.
7347 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7348 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7349 return R;
7350 if (isa<PHINode>(Op0))
7351 if (Instruction *NV = FoldOpIntoPhi(I))
7352 return NV;
7353
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007354 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7355 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7356 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7357 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7358 // place. Don't try to do this transformation in this case. Also, we
7359 // require that the input operand is a shift-by-constant so that we have
7360 // confidence that the shifts will get folded together. We could do this
7361 // xform in more cases, but it is unlikely to be profitable.
7362 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7363 isa<ConstantInt>(TrOp->getOperand(1))) {
7364 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00007365 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00007366 // (shift2 (shift1 & 0x00FF), c2)
7367 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007368
7369 // For logical shifts, the truncation has the effect of making the high
7370 // part of the register be zeros. Emulate this by inserting an AND to
7371 // clear the top bits as needed. This 'and' will usually be zapped by
7372 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007373 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7374 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007375 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7376
7377 // The mask we constructed says what the trunc would do if occurring
7378 // between the shifts. We want to know the effect *after* the second
7379 // shift. We know that it is a logical shift by a constant, so adjust the
7380 // mask as appropriate.
7381 if (I.getOpcode() == Instruction::Shl)
7382 MaskV <<= Op1->getZExtValue();
7383 else {
7384 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7385 MaskV = MaskV.lshr(Op1->getZExtValue());
7386 }
7387
Chris Lattnerc7694852009-08-30 07:44:24 +00007388 // shift1 & 0x00FF
7389 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7390 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007391
7392 // Return the value truncated to the interesting size.
7393 return new TruncInst(And, I.getType());
7394 }
7395 }
7396
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007397 if (Op0->hasOneUse()) {
7398 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7399 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7400 Value *V1, *V2;
7401 ConstantInt *CC;
7402 switch (Op0BO->getOpcode()) {
7403 default: break;
7404 case Instruction::Add:
7405 case Instruction::And:
7406 case Instruction::Or:
7407 case Instruction::Xor: {
7408 // These operators commute.
7409 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7410 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007411 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerad7516a2009-08-30 18:50:58 +00007412 m_Specific(Op1)))) {
7413 Value *YS = // (Y << C)
7414 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7415 // (X + (Y << C))
7416 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7417 Op0BO->getOperand(1)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007418 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007419 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007420 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7421 }
7422
7423 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7424 Value *Op0BOOp1 = Op0BO->getOperand(1);
7425 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7426 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007427 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007428 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007429 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007430 Value *YS = // (Y << C)
7431 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7432 Op0BO->getName());
7433 // X & (CC << C)
7434 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7435 V1->getName()+".mask");
Gabor Greifa645dd32008-05-16 19:29:10 +00007436 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007437 }
7438 }
7439
7440 // FALL THROUGH.
7441 case Instruction::Sub: {
7442 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7443 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007444 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007445 m_Specific(Op1)))) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007446 Value *YS = // (Y << C)
7447 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7448 // (X + (Y << C))
7449 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7450 Op0BO->getOperand(0)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007451 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007452 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007453 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7454 }
7455
7456 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7457 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7458 match(Op0BO->getOperand(0),
7459 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007460 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007461 cast<BinaryOperator>(Op0BO->getOperand(0))
7462 ->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007463 Value *YS = // (Y << C)
7464 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7465 // X & (CC << C)
7466 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7467 V1->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007468
Gabor Greifa645dd32008-05-16 19:29:10 +00007469 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007470 }
7471
7472 break;
7473 }
7474 }
7475
7476
7477 // If the operand is an bitwise operator with a constant RHS, and the
7478 // shift is the only use, we can pull it out of the shift.
7479 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7480 bool isValid = true; // Valid only for And, Or, Xor
7481 bool highBitSet = false; // Transform if high bit of constant set?
7482
7483 switch (Op0BO->getOpcode()) {
7484 default: isValid = false; break; // Do not perform transform!
7485 case Instruction::Add:
7486 isValid = isLeftShift;
7487 break;
7488 case Instruction::Or:
7489 case Instruction::Xor:
7490 highBitSet = false;
7491 break;
7492 case Instruction::And:
7493 highBitSet = true;
7494 break;
7495 }
7496
7497 // If this is a signed shift right, and the high bit is modified
7498 // by the logical operation, do not perform the transformation.
7499 // The highBitSet boolean indicates the value of the high bit of
7500 // the constant which would cause it to be modified for this
7501 // operation.
7502 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007503 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007504 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007505
7506 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007507 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007508
Chris Lattnerad7516a2009-08-30 18:50:58 +00007509 Value *NewShift =
7510 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007511 NewShift->takeName(Op0BO);
7512
Gabor Greifa645dd32008-05-16 19:29:10 +00007513 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007514 NewRHS);
7515 }
7516 }
7517 }
7518 }
7519
7520 // Find out if this is a shift of a shift by a constant.
7521 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7522 if (ShiftOp && !ShiftOp->isShift())
7523 ShiftOp = 0;
7524
7525 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7526 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7527 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7528 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7529 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7530 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7531 Value *X = ShiftOp->getOperand(0);
7532
7533 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007534
7535 const IntegerType *Ty = cast<IntegerType>(I.getType());
7536
7537 // Check for (X << c1) << c2 and (X >> c1) >> c2
7538 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007539 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7540 // saturates.
7541 if (AmtSum >= TypeBits) {
7542 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007543 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007544 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7545 }
7546
Gabor Greifa645dd32008-05-16 19:29:10 +00007547 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007548 ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007549 }
7550
7551 if (ShiftOp->getOpcode() == Instruction::LShr &&
7552 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007553 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00007554 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007555
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007556 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00007557 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007558 }
7559
7560 if (ShiftOp->getOpcode() == Instruction::AShr &&
7561 I.getOpcode() == Instruction::LShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007562 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007563 if (AmtSum >= TypeBits)
7564 AmtSum = TypeBits-1;
7565
Chris Lattnerad7516a2009-08-30 18:50:58 +00007566 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007567
7568 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007569 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007570 }
7571
7572 // Okay, if we get here, one shift must be left, and the other shift must be
7573 // right. See if the amounts are equal.
7574 if (ShiftAmt1 == ShiftAmt2) {
7575 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7576 if (I.getOpcode() == Instruction::Shl) {
7577 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007578 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007579 }
7580 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7581 if (I.getOpcode() == Instruction::LShr) {
7582 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007583 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007584 }
7585 // We can simplify ((X << C) >>s C) into a trunc + sext.
7586 // NOTE: we could do this for any C, but that would make 'unusual' integer
7587 // types. For now, just stick to ones well-supported by the code
7588 // generators.
7589 const Type *SExtType = 0;
7590 switch (Ty->getBitWidth() - ShiftAmt1) {
7591 case 1 :
7592 case 8 :
7593 case 16 :
7594 case 32 :
7595 case 64 :
7596 case 128:
Owen Anderson35b47072009-08-13 21:58:54 +00007597 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007598 break;
7599 default: break;
7600 }
Chris Lattnerad7516a2009-08-30 18:50:58 +00007601 if (SExtType)
7602 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007603 // Otherwise, we can't handle it yet.
7604 } else if (ShiftAmt1 < ShiftAmt2) {
7605 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7606
7607 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7608 if (I.getOpcode() == Instruction::Shl) {
7609 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7610 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007611 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007612
7613 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007614 return BinaryOperator::CreateAnd(Shift,
7615 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007616 }
7617
7618 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7619 if (I.getOpcode() == Instruction::LShr) {
7620 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007621 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007622
7623 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007624 return BinaryOperator::CreateAnd(Shift,
7625 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007626 }
7627
7628 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7629 } else {
7630 assert(ShiftAmt2 < ShiftAmt1);
7631 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7632
7633 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7634 if (I.getOpcode() == Instruction::Shl) {
7635 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7636 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007637 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7638 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007639
7640 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007641 return BinaryOperator::CreateAnd(Shift,
7642 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007643 }
7644
7645 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7646 if (I.getOpcode() == Instruction::LShr) {
7647 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007648 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007649
7650 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007651 return BinaryOperator::CreateAnd(Shift,
7652 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007653 }
7654
7655 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7656 }
7657 }
7658 return 0;
7659}
7660
7661
7662/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7663/// expression. If so, decompose it, returning some value X, such that Val is
7664/// X*Scale+Offset.
7665///
7666static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007667 int &Offset, LLVMContext *Context) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007668 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7669 "Unexpected allocation size type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007670 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7671 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007672 Scale = 0;
Owen Anderson35b47072009-08-13 21:58:54 +00007673 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007674 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7675 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7676 if (I->getOpcode() == Instruction::Shl) {
7677 // This is a value scaled by '1 << the shift amt'.
7678 Scale = 1U << RHS->getZExtValue();
7679 Offset = 0;
7680 return I->getOperand(0);
7681 } else if (I->getOpcode() == Instruction::Mul) {
7682 // This value is scaled by 'RHS'.
7683 Scale = RHS->getZExtValue();
7684 Offset = 0;
7685 return I->getOperand(0);
7686 } else if (I->getOpcode() == Instruction::Add) {
7687 // We have X+C. Check to see if we really have (X*C2)+C1,
7688 // where C1 is divisible by C2.
7689 unsigned SubScale;
7690 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00007691 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7692 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007693 Offset += RHS->getZExtValue();
7694 Scale = SubScale;
7695 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007696 }
7697 }
7698 }
7699
7700 // Otherwise, we can't look past this.
7701 Scale = 1;
7702 Offset = 0;
7703 return Val;
7704}
7705
7706
7707/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7708/// try to eliminate the cast by moving the type information into the alloc.
7709Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7710 AllocationInst &AI) {
7711 const PointerType *PTy = cast<PointerType>(CI.getType());
7712
Chris Lattnerad7516a2009-08-30 18:50:58 +00007713 BuilderTy AllocaBuilder(*Builder);
7714 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7715
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007716 // Remove any uses of AI that are dead.
7717 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7718
7719 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7720 Instruction *User = cast<Instruction>(*UI++);
7721 if (isInstructionTriviallyDead(User)) {
7722 while (UI != E && *UI == User)
7723 ++UI; // If this instruction uses AI more than once, don't break UI.
7724
7725 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00007726 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007727 EraseInstFromFunction(*User);
7728 }
7729 }
Dan Gohmana80e2712009-07-21 23:21:54 +00007730
7731 // This requires TargetData to get the alloca alignment and size information.
7732 if (!TD) return 0;
7733
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007734 // Get the type really allocated and the type casted to.
7735 const Type *AllocElTy = AI.getAllocatedType();
7736 const Type *CastElTy = PTy->getElementType();
7737 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7738
7739 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7740 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7741 if (CastElTyAlign < AllocElTyAlign) return 0;
7742
7743 // If the allocation has multiple uses, only promote it if we are strictly
7744 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007745 // same, we open the door to infinite loops of various kinds. (A reference
7746 // from a dbg.declare doesn't count as a use for this purpose.)
7747 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7748 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007749
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007750 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7751 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007752 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7753
7754 // See if we can satisfy the modulus by pulling a scale out of the array
7755 // size argument.
7756 unsigned ArraySizeScale;
7757 int ArrayOffset;
7758 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00007759 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7760 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007761
7762 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7763 // do the xform.
7764 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7765 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7766
7767 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7768 Value *Amt = 0;
7769 if (Scale == 1) {
7770 Amt = NumElements;
7771 } else {
Owen Anderson35b47072009-08-13 21:58:54 +00007772 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007773 // Insert before the alloca, not before the cast.
7774 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007775 }
7776
7777 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson35b47072009-08-13 21:58:54 +00007778 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007779 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007780 }
7781
7782 AllocationInst *New;
7783 if (isa<MallocInst>(AI))
Chris Lattnerad7516a2009-08-30 18:50:58 +00007784 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007785 else
Chris Lattnerad7516a2009-08-30 18:50:58 +00007786 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7787 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007788 New->takeName(&AI);
7789
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007790 // If the allocation has one real use plus a dbg.declare, just remove the
7791 // declare.
7792 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7793 EraseInstFromFunction(*DI);
7794 }
7795 // If the allocation has multiple real uses, insert a cast and change all
7796 // things that used it to use the new cast. This will also hack on CI, but it
7797 // will die soon.
7798 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007799 // New is the allocation instruction, pointer typed. AI is the original
7800 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerad7516a2009-08-30 18:50:58 +00007801 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007802 AI.replaceAllUsesWith(NewCast);
7803 }
7804 return ReplaceInstUsesWith(CI, New);
7805}
7806
7807/// CanEvaluateInDifferentType - Return true if we can take the specified value
7808/// and return it as type Ty without inserting any new casts and without
7809/// changing the computed value. This is used by code that tries to decide
7810/// whether promoting or shrinking integer operations to wider or smaller types
7811/// will allow us to eliminate a truncate or extend.
7812///
7813/// This is a truncation operation if Ty is smaller than V->getType(), or an
7814/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007815///
7816/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7817/// should return true if trunc(V) can be computed by computing V in the smaller
7818/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7819/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7820/// efficiently truncated.
7821///
7822/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7823/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7824/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007825bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00007826 unsigned CastOpc,
7827 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007828 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007829 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007830 return true;
7831
7832 Instruction *I = dyn_cast<Instruction>(V);
7833 if (!I) return false;
7834
Dan Gohman8fd520a2009-06-15 22:12:54 +00007835 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007836
Chris Lattneref70bb82007-08-02 06:11:14 +00007837 // If this is an extension or truncate, we can often eliminate it.
7838 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7839 // If this is a cast from the destination type, we can trivially eliminate
7840 // it, and this will remove a cast overall.
7841 if (I->getOperand(0)->getType() == Ty) {
7842 // If the first operand is itself a cast, and is eliminable, do not count
7843 // this as an eliminable cast. We would prefer to eliminate those two
7844 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007845 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007846 ++NumCastsRemoved;
7847 return true;
7848 }
7849 }
7850
7851 // We can't extend or shrink something that has multiple uses: doing so would
7852 // require duplicating the instruction in general, which isn't profitable.
7853 if (!I->hasOneUse()) return false;
7854
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007855 unsigned Opc = I->getOpcode();
7856 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007857 case Instruction::Add:
7858 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007859 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007860 case Instruction::And:
7861 case Instruction::Or:
7862 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007863 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007864 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007865 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007866 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007867 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007868
Eli Friedman08c45bc2009-07-13 22:46:01 +00007869 case Instruction::UDiv:
7870 case Instruction::URem: {
7871 // UDiv and URem can be truncated if all the truncated bits are zero.
7872 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7873 uint32_t BitWidth = Ty->getScalarSizeInBits();
7874 if (BitWidth < OrigBitWidth) {
7875 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7876 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7877 MaskedValueIsZero(I->getOperand(1), Mask)) {
7878 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7879 NumCastsRemoved) &&
7880 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7881 NumCastsRemoved);
7882 }
7883 }
7884 break;
7885 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007886 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007887 // If we are truncating the result of this SHL, and if it's a shift of a
7888 // constant amount, we can always perform a SHL in a smaller type.
7889 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007890 uint32_t BitWidth = Ty->getScalarSizeInBits();
7891 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007892 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007893 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007894 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007895 }
7896 break;
7897 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007898 // If this is a truncate of a logical shr, we can truncate it to a smaller
7899 // lshr iff we know that the bits we would otherwise be shifting in are
7900 // already zeros.
7901 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007902 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7903 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007904 if (BitWidth < OrigBitWidth &&
7905 MaskedValueIsZero(I->getOperand(0),
7906 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7907 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007908 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007909 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007910 }
7911 }
7912 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007913 case Instruction::ZExt:
7914 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007915 case Instruction::Trunc:
7916 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007917 // can safely replace it. Note that replacing it does not reduce the number
7918 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007919 if (Opc == CastOpc)
7920 return true;
7921
7922 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00007923 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007924 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007925 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007926 case Instruction::Select: {
7927 SelectInst *SI = cast<SelectInst>(I);
7928 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007929 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007930 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007931 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007932 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007933 case Instruction::PHI: {
7934 // We can change a phi if we can change all operands.
7935 PHINode *PN = cast<PHINode>(I);
7936 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7937 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007938 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00007939 return false;
7940 return true;
7941 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007942 default:
7943 // TODO: Can handle more cases here.
7944 break;
7945 }
7946
7947 return false;
7948}
7949
7950/// EvaluateInDifferentType - Given an expression that
7951/// CanEvaluateInDifferentType returns true for, actually insert the code to
7952/// evaluate the expression.
7953Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7954 bool isSigned) {
7955 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +00007956 return ConstantExpr::getIntegerCast(C, Ty,
Owen Anderson24be4c12009-07-03 00:17:18 +00007957 isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007958
7959 // Otherwise, it must be an instruction.
7960 Instruction *I = cast<Instruction>(V);
7961 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007962 unsigned Opc = I->getOpcode();
7963 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007964 case Instruction::Add:
7965 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007966 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007967 case Instruction::And:
7968 case Instruction::Or:
7969 case Instruction::Xor:
7970 case Instruction::AShr:
7971 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00007972 case Instruction::Shl:
7973 case Instruction::UDiv:
7974 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007975 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7976 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007977 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007978 break;
7979 }
7980 case Instruction::Trunc:
7981 case Instruction::ZExt:
7982 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007983 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007984 // just return the source. There's no need to insert it because it is not
7985 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007986 if (I->getOperand(0)->getType() == Ty)
7987 return I->getOperand(0);
7988
Chris Lattner4200c2062008-06-18 04:00:49 +00007989 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007990 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00007991 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00007992 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007993 case Instruction::Select: {
7994 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7995 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7996 Res = SelectInst::Create(I->getOperand(0), True, False);
7997 break;
7998 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007999 case Instruction::PHI: {
8000 PHINode *OPN = cast<PHINode>(I);
8001 PHINode *NPN = PHINode::Create(Ty);
8002 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8003 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8004 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8005 }
8006 Res = NPN;
8007 break;
8008 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008009 default:
8010 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00008011 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008012 break;
8013 }
8014
Chris Lattner4200c2062008-06-18 04:00:49 +00008015 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008016 return InsertNewInstBefore(Res, *I);
8017}
8018
8019/// @brief Implement the transforms common to all CastInst visitors.
8020Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8021 Value *Src = CI.getOperand(0);
8022
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008023 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8024 // eliminate it now.
8025 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8026 if (Instruction::CastOps opc =
8027 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8028 // The first cast (CSrc) is eliminable so we need to fix up or replace
8029 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008030 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008031 }
8032 }
8033
8034 // If we are casting a select then fold the cast into the select
8035 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8036 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8037 return NV;
8038
8039 // If we are casting a PHI then fold the cast into the PHI
8040 if (isa<PHINode>(Src))
8041 if (Instruction *NV = FoldOpIntoPhi(CI))
8042 return NV;
8043
8044 return 0;
8045}
8046
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008047/// FindElementAtOffset - Given a type and a constant offset, determine whether
8048/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008049/// the specified offset. If so, fill them into NewIndices and return the
8050/// resultant element type, otherwise return null.
8051static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8052 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008053 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008054 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008055 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008056 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008057
8058 // Start with the index over the outer type. Note that the type size
8059 // might be zero (even if the offset isn't zero) if the indexed type
8060 // is something like [0 x {int, int}]
Owen Anderson35b47072009-08-13 21:58:54 +00008061 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008062 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008063 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008064 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008065 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008066
Chris Lattnerce48c462009-01-11 20:15:20 +00008067 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008068 if (Offset < 0) {
8069 --FirstIdx;
8070 Offset += TySize;
8071 assert(Offset >= 0);
8072 }
8073 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8074 }
8075
Owen Andersoneacb44d2009-07-24 23:12:02 +00008076 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008077
8078 // Index into the types. If we fail, set OrigBase to null.
8079 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008080 // Indexing into tail padding between struct/array elements.
8081 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008082 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008083
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008084 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8085 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008086 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8087 "Offset must stay within the indexed type");
8088
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008089 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson35b47072009-08-13 21:58:54 +00008090 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008091
8092 Offset -= SL->getElementOffset(Elt);
8093 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008094 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008095 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008096 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00008097 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008098 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008099 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008100 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008101 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008102 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008103 }
8104 }
8105
Chris Lattner54dddc72009-01-24 01:00:13 +00008106 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008107}
8108
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008109/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8110Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8111 Value *Src = CI.getOperand(0);
8112
8113 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8114 // If casting the result of a getelementptr instruction with no offset, turn
8115 // this into a cast of the original pointer!
8116 if (GEP->hasAllZeroIndices()) {
8117 // Changing the cast operand is usually not a good idea but it is safe
8118 // here because the pointer operand is being replaced with another
8119 // pointer operand so the opcode doesn't need to change.
Chris Lattner3183fb62009-08-30 06:13:40 +00008120 Worklist.Add(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008121 CI.setOperand(0, GEP->getOperand(0));
8122 return &CI;
8123 }
8124
8125 // If the GEP has a single use, and the base pointer is a bitcast, and the
8126 // GEP computes a constant offset, see if we can convert these three
8127 // instructions into fewer. This typically happens with unions and other
8128 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008129 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008130 if (GEP->hasAllConstantIndices()) {
8131 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +00008132 ConstantInt *OffsetV =
8133 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008134 int64_t Offset = OffsetV->getSExtValue();
8135
8136 // Get the base pointer input of the bitcast, and the type it points to.
8137 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8138 const Type *GEPIdxTy =
8139 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008140 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008141 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008142 // If we were able to index down into an element, create the GEP
8143 // and bitcast the result. This eliminates one bitcast, potentially
8144 // two.
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008145 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8146 Builder->CreateInBoundsGEP(OrigBase,
8147 NewIndices.begin(), NewIndices.end()) :
8148 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008149 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008150
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008151 if (isa<BitCastInst>(CI))
8152 return new BitCastInst(NGEP, CI.getType());
8153 assert(isa<PtrToIntInst>(CI));
8154 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008155 }
8156 }
8157 }
8158 }
8159
8160 return commonCastTransforms(CI);
8161}
8162
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008163/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8164/// type like i42. We don't want to introduce operations on random non-legal
8165/// integer types where they don't already exist in the code. In the future,
8166/// we should consider making this based off target-data, so that 32-bit targets
8167/// won't get i64 operations etc.
8168static bool isSafeIntegerType(const Type *Ty) {
8169 switch (Ty->getPrimitiveSizeInBits()) {
8170 case 8:
8171 case 16:
8172 case 32:
8173 case 64:
8174 return true;
8175 default:
8176 return false;
8177 }
8178}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008179
Eli Friedman827e37a2009-07-13 20:58:59 +00008180/// commonIntCastTransforms - This function implements the common transforms
8181/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008182Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8183 if (Instruction *Result = commonCastTransforms(CI))
8184 return Result;
8185
8186 Value *Src = CI.getOperand(0);
8187 const Type *SrcTy = Src->getType();
8188 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008189 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8190 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008191
8192 // See if we can simplify any instructions used by the LHS whose sole
8193 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008194 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008195 return &CI;
8196
8197 // If the source isn't an instruction or has more than one use then we
8198 // can't do anything more.
8199 Instruction *SrcI = dyn_cast<Instruction>(Src);
8200 if (!SrcI || !Src->hasOneUse())
8201 return 0;
8202
8203 // Attempt to propagate the cast into the instruction for int->int casts.
8204 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008205 // Only do this if the dest type is a simple type, don't convert the
8206 // expression tree to something weird like i93 unless the source is also
8207 // strange.
8208 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman8fd520a2009-06-15 22:12:54 +00008209 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8210 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng814a00c2009-01-16 02:11:43 +00008211 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008212 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008213 // eliminates the cast, so it is always a win. If this is a zero-extension,
8214 // we need to do an AND to maintain the clear top-part of the computation,
8215 // so we require that the input have eliminated at least one cast. If this
8216 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008217 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008218 bool DoXForm = false;
8219 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008220 switch (CI.getOpcode()) {
8221 default:
8222 // All the others use floating point so we shouldn't actually
8223 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008224 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008225 case Instruction::Trunc:
8226 DoXForm = true;
8227 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008228 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008229 DoXForm = NumCastsRemoved >= 1;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008230 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008231 // If it's unnecessary to issue an AND to clear the high bits, it's
8232 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008233 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008234 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8235 if (MaskedValueIsZero(TryRes, Mask))
8236 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008237
8238 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008239 if (TryI->use_empty())
8240 EraseInstFromFunction(*TryI);
8241 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008242 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008243 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008244 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008245 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008246 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008247 // If we do not have to emit the truncate + sext pair, then it's always
8248 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008249 //
8250 // It's not safe to eliminate the trunc + sext pair if one of the
8251 // eliminated cast is a truncate. e.g.
8252 // t2 = trunc i32 t1 to i16
8253 // t3 = sext i16 t2 to i32
8254 // !=
8255 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008256 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008257 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8258 if (NumSignBits > (DestBitSize - SrcBitSize))
8259 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008260
8261 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008262 if (TryI->use_empty())
8263 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008264 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008265 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008266 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008267 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008268
8269 if (DoXForm) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00008270 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8271 " to avoid cast: " << CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008272 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8273 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008274 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008275 // Just replace this cast with the result.
8276 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008277
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008278 assert(Res->getType() == DestTy);
8279 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008280 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008281 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008282 // Just replace this cast with the result.
8283 return ReplaceInstUsesWith(CI, Res);
8284 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008285 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008286
8287 // If the high bits are already zero, just replace this cast with the
8288 // result.
8289 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8290 if (MaskedValueIsZero(Res, Mask))
8291 return ReplaceInstUsesWith(CI, Res);
8292
8293 // We need to emit an AND to clear the high bits.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008294 Constant *C = ConstantInt::get(*Context,
8295 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008296 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008297 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008298 case Instruction::SExt: {
8299 // If the high bits are already filled with sign bit, just replace this
8300 // cast with the result.
8301 unsigned NumSignBits = ComputeNumSignBits(Res);
8302 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008303 return ReplaceInstUsesWith(CI, Res);
8304
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008305 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008306 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008307 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008308 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008309 }
8310 }
8311
8312 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8313 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8314
8315 switch (SrcI->getOpcode()) {
8316 case Instruction::Add:
8317 case Instruction::Mul:
8318 case Instruction::And:
8319 case Instruction::Or:
8320 case Instruction::Xor:
8321 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008322 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8323 // Don't insert two casts unless at least one can be eliminated.
8324 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008325 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008326 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8327 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008328 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008329 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8330 }
8331 }
8332
8333 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8334 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8335 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson4f720fa2009-07-31 17:39:07 +00008336 Op1 == ConstantInt::getTrue(*Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008337 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008338 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Anderson24be4c12009-07-03 00:17:18 +00008339 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008340 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008341 }
8342 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008343
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008344 case Instruction::Shl: {
8345 // Canonicalize trunc inside shl, if we can.
8346 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8347 if (CI && DestBitSize < SrcBitSize &&
8348 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008349 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8350 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008351 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008352 }
8353 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008354 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008355 }
8356 return 0;
8357}
8358
8359Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8360 if (Instruction *Result = commonIntCastTransforms(CI))
8361 return Result;
8362
8363 Value *Src = CI.getOperand(0);
8364 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008365 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8366 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008367
8368 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008369 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008370 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008371 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersonaac28372009-07-31 20:28:14 +00008372 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohmane6803b82009-08-25 23:17:54 +00008373 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008374 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008375
Chris Lattner32177f82009-03-24 18:15:30 +00008376 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8377 ConstantInt *ShAmtV = 0;
8378 Value *ShiftOp = 0;
8379 if (Src->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00008380 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner32177f82009-03-24 18:15:30 +00008381 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8382
8383 // Get a mask for the bits shifting in.
8384 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8385 if (MaskedValueIsZero(ShiftOp, Mask)) {
8386 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00008387 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008388
8389 // Okay, we can shrink this. Truncate the input, then return a new
8390 // shift.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008391 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Anderson02b48c32009-07-29 18:55:55 +00008392 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008393 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008394 }
8395 }
8396
8397 return 0;
8398}
8399
Evan Chenge3779cf2008-03-24 00:21:34 +00008400/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8401/// in order to eliminate the icmp.
8402Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8403 bool DoXform) {
8404 // If we are just checking for a icmp eq of a single bit and zext'ing it
8405 // to an integer, then shift the bit to the appropriate place and then
8406 // cast to integer to avoid the comparison.
8407 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8408 const APInt &Op1CV = Op1C->getValue();
8409
8410 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8411 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8412 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8413 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8414 if (!DoXform) return ICI;
8415
8416 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008417 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008418 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008419 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008420 if (In->getType() != CI.getType())
Chris Lattnerad7516a2009-08-30 18:50:58 +00008421 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008422
8423 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008424 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008425 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chenge3779cf2008-03-24 00:21:34 +00008426 }
8427
8428 return ReplaceInstUsesWith(CI, In);
8429 }
8430
8431
8432
8433 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8434 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8435 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8436 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8437 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8438 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8439 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8440 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8441 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8442 // This only works for EQ and NE
8443 ICI->isEquality()) {
8444 // If Op1C some other power of two, convert:
8445 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8446 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8447 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8448 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8449
8450 APInt KnownZeroMask(~KnownZero);
8451 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8452 if (!DoXform) return ICI;
8453
8454 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8455 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8456 // (X&4) == 2 --> false
8457 // (X&4) != 2 --> true
Owen Anderson35b47072009-08-13 21:58:54 +00008458 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00008459 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008460 return ReplaceInstUsesWith(CI, Res);
8461 }
8462
8463 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8464 Value *In = ICI->getOperand(0);
8465 if (ShiftAmt) {
8466 // Perform a logical shr by shiftamt.
8467 // Insert the shift to put the result in the low bit.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008468 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8469 In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008470 }
8471
8472 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008473 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008474 In = Builder->CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008475 }
8476
8477 if (CI.getType() == In->getType())
8478 return ReplaceInstUsesWith(CI, In);
8479 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008480 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008481 }
8482 }
8483 }
8484
8485 return 0;
8486}
8487
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008488Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8489 // If one of the common conversion will work ..
8490 if (Instruction *Result = commonIntCastTransforms(CI))
8491 return Result;
8492
8493 Value *Src = CI.getOperand(0);
8494
Chris Lattner215d56e2009-02-17 20:47:23 +00008495 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8496 // types and if the sizes are just right we can convert this into a logical
8497 // 'and' which will be much cheaper than the pair of casts.
8498 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8499 // Get the sizes of the types involved. We know that the intermediate type
8500 // will be smaller than A or C, but don't know the relation between A and C.
8501 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008502 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8503 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8504 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008505 // If we're actually extending zero bits, then if
8506 // SrcSize < DstSize: zext(a & mask)
8507 // SrcSize == DstSize: a & mask
8508 // SrcSize > DstSize: trunc(a) & mask
8509 if (SrcSize < DstSize) {
8510 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008511 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008512 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattner215d56e2009-02-17 20:47:23 +00008513 return new ZExtInst(And, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008514 }
8515
8516 if (SrcSize == DstSize) {
Chris Lattner215d56e2009-02-17 20:47:23 +00008517 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008518 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008519 AndValue));
Chris Lattnerad7516a2009-08-30 18:50:58 +00008520 }
8521 if (SrcSize > DstSize) {
8522 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattner215d56e2009-02-17 20:47:23 +00008523 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008524 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008525 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008526 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008527 }
8528 }
8529
Evan Chenge3779cf2008-03-24 00:21:34 +00008530 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8531 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008532
Evan Chenge3779cf2008-03-24 00:21:34 +00008533 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8534 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8535 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8536 // of the (zext icmp) will be transformed.
8537 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8538 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8539 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8540 (transformZExtICmp(LHS, CI, false) ||
8541 transformZExtICmp(RHS, CI, false))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008542 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8543 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008544 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008545 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008546 }
8547
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008548 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008549 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8550 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8551 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8552 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008553 if (TI0->getType() == CI.getType())
8554 return
8555 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00008556 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008557 }
8558
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008559 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8560 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8561 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8562 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8563 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8564 And->getOperand(1) == C)
8565 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8566 Value *TI0 = TI->getOperand(0);
8567 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00008568 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008569 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008570 return BinaryOperator::CreateXor(NewAnd, ZC);
8571 }
8572 }
8573
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008574 return 0;
8575}
8576
8577Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8578 if (Instruction *I = commonIntCastTransforms(CI))
8579 return I;
8580
8581 Value *Src = CI.getOperand(0);
8582
Dan Gohman35b76162008-10-30 20:40:10 +00008583 // Canonicalize sign-extend from i1 to a select.
Owen Anderson35b47072009-08-13 21:58:54 +00008584 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman35b76162008-10-30 20:40:10 +00008585 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00008586 Constant::getAllOnesValue(CI.getType()),
8587 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008588
8589 // See if the value being truncated is already sign extended. If so, just
8590 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00008591 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00008592 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008593 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8594 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8595 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008596 unsigned NumSignBits = ComputeNumSignBits(Op);
8597
8598 if (OpBits == DestBits) {
8599 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8600 // bits, it is already ready.
8601 if (NumSignBits > DestBits-MidBits)
8602 return ReplaceInstUsesWith(CI, Op);
8603 } else if (OpBits < DestBits) {
8604 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8605 // bits, just sext from i32.
8606 if (NumSignBits > OpBits-MidBits)
8607 return new SExtInst(Op, CI.getType(), "tmp");
8608 } else {
8609 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8610 // bits, just truncate to i32.
8611 if (NumSignBits > OpBits-MidBits)
8612 return new TruncInst(Op, CI.getType(), "tmp");
8613 }
8614 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008615
8616 // If the input is a shl/ashr pair of a same constant, then this is a sign
8617 // extension from a smaller value. If we could trust arbitrary bitwidth
8618 // integers, we could turn this into a truncate to the smaller bit and then
8619 // use a sext for the whole extension. Since we don't, look deeper and check
8620 // for a truncate. If the source and dest are the same type, eliminate the
8621 // trunc and extend and just do shifts. For example, turn:
8622 // %a = trunc i32 %i to i8
8623 // %b = shl i8 %a, 6
8624 // %c = ashr i8 %b, 6
8625 // %d = sext i8 %c to i32
8626 // into:
8627 // %a = shl i32 %i, 30
8628 // %d = ashr i32 %a, 30
8629 Value *A = 0;
8630 ConstantInt *BA = 0, *CA = 0;
8631 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohmancdff2122009-08-12 16:23:25 +00008632 m_ConstantInt(CA))) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008633 BA == CA && isa<TruncInst>(A)) {
8634 Value *I = cast<TruncInst>(A)->getOperand(0);
8635 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008636 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8637 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008638 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00008639 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008640 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner8a2d0592008-08-06 07:35:52 +00008641 return BinaryOperator::CreateAShr(I, ShAmtV);
8642 }
8643 }
8644
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008645 return 0;
8646}
8647
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008648/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8649/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008650static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008651 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008652 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008653 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008654 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8655 if (!losesInfo)
Owen Andersond363a0e2009-07-27 20:59:43 +00008656 return ConstantFP::get(*Context, F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008657 return 0;
8658}
8659
8660/// LookThroughFPExtensions - If this is an fp extension instruction, look
8661/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00008662static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008663 if (Instruction *I = dyn_cast<Instruction>(V))
8664 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00008665 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008666
8667 // If this value is a constant, return the constant in the smallest FP type
8668 // that can accurately represent it. This allows us to turn
8669 // (float)((double)X+2.0) into x+2.0f.
8670 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +00008671 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008672 return V; // No constant folding of this.
8673 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00008674 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008675 return V;
Owen Anderson35b47072009-08-13 21:58:54 +00008676 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008677 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00008678 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008679 return V;
8680 // Don't try to shrink to various long double types.
8681 }
8682
8683 return V;
8684}
8685
8686Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8687 if (Instruction *I = commonCastTransforms(CI))
8688 return I;
8689
Dan Gohman7ce405e2009-06-04 22:49:04 +00008690 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008691 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008692 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008693 // many builtins (sqrt, etc).
8694 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8695 if (OpI && OpI->hasOneUse()) {
8696 switch (OpI->getOpcode()) {
8697 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008698 case Instruction::FAdd:
8699 case Instruction::FSub:
8700 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008701 case Instruction::FDiv:
8702 case Instruction::FRem:
8703 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00008704 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8705 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008706 if (LHSTrunc->getType() != SrcTy &&
8707 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008708 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008709 // If the source types were both smaller than the destination type of
8710 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008711 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8712 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008713 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8714 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00008715 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008716 }
8717 }
8718 break;
8719 }
8720 }
8721 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008722}
8723
8724Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8725 return commonCastTransforms(CI);
8726}
8727
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008728Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008729 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8730 if (OpI == 0)
8731 return commonCastTransforms(FI);
8732
8733 // fptoui(uitofp(X)) --> X
8734 // fptoui(sitofp(X)) --> X
8735 // This is safe if the intermediate type has enough bits in its mantissa to
8736 // accurately represent all values of X. For example, do not do this with
8737 // i64->float->i64. This is also safe for sitofp case, because any negative
8738 // 'X' value would cause an undefined result for the fptoui.
8739 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8740 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008741 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008742 OpI->getType()->getFPMantissaWidth())
8743 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008744
8745 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008746}
8747
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008748Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008749 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8750 if (OpI == 0)
8751 return commonCastTransforms(FI);
8752
8753 // fptosi(sitofp(X)) --> X
8754 // fptosi(uitofp(X)) --> X
8755 // This is safe if the intermediate type has enough bits in its mantissa to
8756 // accurately represent all values of X. For example, do not do this with
8757 // i64->float->i64. This is also safe for sitofp case, because any negative
8758 // 'X' value would cause an undefined result for the fptoui.
8759 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8760 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008761 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008762 OpI->getType()->getFPMantissaWidth())
8763 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008764
8765 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008766}
8767
8768Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8769 return commonCastTransforms(CI);
8770}
8771
8772Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8773 return commonCastTransforms(CI);
8774}
8775
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008776Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8777 // If the destination integer type is smaller than the intptr_t type for
8778 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8779 // trunc to be exposed to other transforms. Don't do this for extending
8780 // ptrtoint's, because we don't know if the target sign or zero extends its
8781 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008782 if (TD &&
8783 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008784 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8785 TD->getIntPtrType(CI.getContext()),
8786 "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008787 return new TruncInst(P, CI.getType());
8788 }
8789
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008790 return commonPointerCastTransforms(CI);
8791}
8792
Chris Lattner7c1626482008-01-08 07:23:51 +00008793Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008794 // If the source integer type is larger than the intptr_t type for
8795 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8796 // allows the trunc to be exposed to other transforms. Don't do this for
8797 // extending inttoptr's, because we don't know if the target sign or zero
8798 // extends to pointers.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008799 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008800 TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008801 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8802 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008803 return new IntToPtrInst(P, CI.getType());
8804 }
8805
Chris Lattner7c1626482008-01-08 07:23:51 +00008806 if (Instruction *I = commonCastTransforms(CI))
8807 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00008808
Chris Lattner7c1626482008-01-08 07:23:51 +00008809 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008810}
8811
8812Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8813 // If the operands are integer typed then apply the integer transforms,
8814 // otherwise just apply the common ones.
8815 Value *Src = CI.getOperand(0);
8816 const Type *SrcTy = Src->getType();
8817 const Type *DestTy = CI.getType();
8818
Eli Friedman5013d3f2009-07-13 20:53:00 +00008819 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008820 if (Instruction *I = commonPointerCastTransforms(CI))
8821 return I;
8822 } else {
8823 if (Instruction *Result = commonCastTransforms(CI))
8824 return Result;
8825 }
8826
8827
8828 // Get rid of casts from one type to the same type. These are useless and can
8829 // be replaced by the operand.
8830 if (DestTy == Src->getType())
8831 return ReplaceInstUsesWith(CI, Src);
8832
8833 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8834 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8835 const Type *DstElTy = DstPTy->getElementType();
8836 const Type *SrcElTy = SrcPTy->getElementType();
8837
Nate Begemandf5b3612008-03-31 00:22:16 +00008838 // If the address spaces don't match, don't eliminate the bitcast, which is
8839 // required for changing types.
8840 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8841 return 0;
8842
Victor Hernandez48c3c542009-09-18 22:35:49 +00008843 // If we are casting a alloca to a pointer to a type of the same
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008844 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez48c3c542009-09-18 22:35:49 +00008845 // There is no need to modify malloc calls because it is their bitcast that
8846 // needs to be cleaned up.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008847 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8848 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8849 return V;
8850
8851 // If the source and destination are pointers, and this cast is equivalent
8852 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8853 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson35b47072009-08-13 21:58:54 +00008854 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008855 unsigned NumZeros = 0;
8856 while (SrcElTy != DstElTy &&
8857 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8858 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8859 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8860 ++NumZeros;
8861 }
8862
8863 // If we found a path from the src to dest, create the getelementptr now.
8864 if (SrcElTy == DstElTy) {
8865 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008866 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8867 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008868 }
8869 }
8870
Eli Friedman1d31dee2009-07-18 23:06:53 +00008871 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8872 if (DestVTy->getNumElements() == 1) {
8873 if (!isa<VectorType>(SrcTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008874 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00008875 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattnerd6164c22009-08-30 20:01:10 +00008876 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00008877 }
8878 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8879 }
8880 }
8881
8882 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8883 if (SrcVTy->getNumElements() == 1) {
8884 if (!isa<VectorType>(DestTy)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008885 Value *Elem =
8886 Builder->CreateExtractElement(Src,
8887 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00008888 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8889 }
8890 }
8891 }
8892
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008893 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8894 if (SVI->hasOneUse()) {
8895 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8896 // a bitconvert to a vector with the same # elts.
8897 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00008898 cast<VectorType>(DestTy)->getNumElements() ==
8899 SVI->getType()->getNumElements() &&
8900 SVI->getType()->getNumElements() ==
8901 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008902 CastInst *Tmp;
8903 // If either of the operands is a cast from CI.getType(), then
8904 // evaluating the shuffle in the casted destination's type will allow
8905 // us to eliminate at least one cast.
8906 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8907 Tmp->getOperand(0)->getType() == DestTy) ||
8908 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8909 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008910 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8911 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008912 // Return a new shuffle vector. Use the same element ID's, as we
8913 // know the vector types match #elts.
8914 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8915 }
8916 }
8917 }
8918 }
8919 return 0;
8920}
8921
8922/// GetSelectFoldableOperands - We want to turn code that looks like this:
8923/// %C = or %A, %B
8924/// %D = select %cond, %C, %A
8925/// into:
8926/// %C = select %cond, %B, 0
8927/// %D = or %A, %C
8928///
8929/// Assuming that the specified instruction is an operand to the select, return
8930/// a bitmask indicating which operands of this instruction are foldable if they
8931/// equal the other incoming value of the select.
8932///
8933static unsigned GetSelectFoldableOperands(Instruction *I) {
8934 switch (I->getOpcode()) {
8935 case Instruction::Add:
8936 case Instruction::Mul:
8937 case Instruction::And:
8938 case Instruction::Or:
8939 case Instruction::Xor:
8940 return 3; // Can fold through either operand.
8941 case Instruction::Sub: // Can only fold on the amount subtracted.
8942 case Instruction::Shl: // Can only fold on the shift amount.
8943 case Instruction::LShr:
8944 case Instruction::AShr:
8945 return 1;
8946 default:
8947 return 0; // Cannot fold
8948 }
8949}
8950
8951/// GetSelectFoldableConstant - For the same transformation as the previous
8952/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00008953static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00008954 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008955 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008956 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008957 case Instruction::Add:
8958 case Instruction::Sub:
8959 case Instruction::Or:
8960 case Instruction::Xor:
8961 case Instruction::Shl:
8962 case Instruction::LShr:
8963 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00008964 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008965 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00008966 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008967 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00008968 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008969 }
8970}
8971
8972/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8973/// have the same opcode and only one use each. Try to simplify this.
8974Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8975 Instruction *FI) {
8976 if (TI->getNumOperands() == 1) {
8977 // If this is a non-volatile load or a cast from the same type,
8978 // merge.
8979 if (TI->isCast()) {
8980 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8981 return 0;
8982 } else {
8983 return 0; // unknown unary op.
8984 }
8985
8986 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008987 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00008988 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008989 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008990 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008991 TI->getType());
8992 }
8993
8994 // Only handle binary operators here.
8995 if (!isa<BinaryOperator>(TI))
8996 return 0;
8997
8998 // Figure out if the operations have any operands in common.
8999 Value *MatchOp, *OtherOpT, *OtherOpF;
9000 bool MatchIsOpZero;
9001 if (TI->getOperand(0) == FI->getOperand(0)) {
9002 MatchOp = TI->getOperand(0);
9003 OtherOpT = TI->getOperand(1);
9004 OtherOpF = FI->getOperand(1);
9005 MatchIsOpZero = true;
9006 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9007 MatchOp = TI->getOperand(1);
9008 OtherOpT = TI->getOperand(0);
9009 OtherOpF = FI->getOperand(0);
9010 MatchIsOpZero = false;
9011 } else if (!TI->isCommutative()) {
9012 return 0;
9013 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9014 MatchOp = TI->getOperand(0);
9015 OtherOpT = TI->getOperand(1);
9016 OtherOpF = FI->getOperand(0);
9017 MatchIsOpZero = true;
9018 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9019 MatchOp = TI->getOperand(1);
9020 OtherOpT = TI->getOperand(0);
9021 OtherOpF = FI->getOperand(1);
9022 MatchIsOpZero = true;
9023 } else {
9024 return 0;
9025 }
9026
9027 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009028 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9029 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009030 InsertNewInstBefore(NewSI, SI);
9031
9032 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9033 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009034 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009035 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009036 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009037 }
Edwin Törökbd448e32009-07-14 16:55:14 +00009038 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009039 return 0;
9040}
9041
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009042static bool isSelect01(Constant *C1, Constant *C2) {
9043 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9044 if (!C1I)
9045 return false;
9046 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9047 if (!C2I)
9048 return false;
9049 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9050}
9051
9052/// FoldSelectIntoOp - Try fold the select into one of the operands to
9053/// facilitate further optimization.
9054Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9055 Value *FalseVal) {
9056 // See the comment above GetSelectFoldableOperands for a description of the
9057 // transformation we are doing here.
9058 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9059 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9060 !isa<Constant>(FalseVal)) {
9061 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9062 unsigned OpToFold = 0;
9063 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9064 OpToFold = 1;
9065 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9066 OpToFold = 2;
9067 }
9068
9069 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009070 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009071 Value *OOp = TVI->getOperand(2-OpToFold);
9072 // Avoid creating select between 2 constants unless it's selecting
9073 // between 0 and 1.
9074 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9075 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9076 InsertNewInstBefore(NewSel, SI);
9077 NewSel->takeName(TVI);
9078 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9079 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009080 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009081 }
9082 }
9083 }
9084 }
9085 }
9086
9087 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9088 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9089 !isa<Constant>(TrueVal)) {
9090 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9091 unsigned OpToFold = 0;
9092 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9093 OpToFold = 1;
9094 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9095 OpToFold = 2;
9096 }
9097
9098 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009099 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009100 Value *OOp = FVI->getOperand(2-OpToFold);
9101 // Avoid creating select between 2 constants unless it's selecting
9102 // between 0 and 1.
9103 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9104 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9105 InsertNewInstBefore(NewSel, SI);
9106 NewSel->takeName(FVI);
9107 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9108 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009109 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009110 }
9111 }
9112 }
9113 }
9114 }
9115
9116 return 0;
9117}
9118
Dan Gohman58c09632008-09-16 18:46:06 +00009119/// visitSelectInstWithICmp - Visit a SelectInst that has an
9120/// ICmpInst as its first operand.
9121///
9122Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9123 ICmpInst *ICI) {
9124 bool Changed = false;
9125 ICmpInst::Predicate Pred = ICI->getPredicate();
9126 Value *CmpLHS = ICI->getOperand(0);
9127 Value *CmpRHS = ICI->getOperand(1);
9128 Value *TrueVal = SI.getTrueValue();
9129 Value *FalseVal = SI.getFalseValue();
9130
9131 // Check cases where the comparison is with a constant that
9132 // can be adjusted to fit the min/max idiom. We may edit ICI in
9133 // place here, so make sure the select is the only user.
9134 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009135 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009136 switch (Pred) {
9137 default: break;
9138 case ICmpInst::ICMP_ULT:
9139 case ICmpInst::ICMP_SLT: {
9140 // X < MIN ? T : F --> F
9141 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9142 return ReplaceInstUsesWith(SI, FalseVal);
9143 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009144 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009145 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9146 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9147 Pred = ICmpInst::getSwappedPredicate(Pred);
9148 CmpRHS = AdjustedRHS;
9149 std::swap(FalseVal, TrueVal);
9150 ICI->setPredicate(Pred);
9151 ICI->setOperand(1, CmpRHS);
9152 SI.setOperand(1, TrueVal);
9153 SI.setOperand(2, FalseVal);
9154 Changed = true;
9155 }
9156 break;
9157 }
9158 case ICmpInst::ICMP_UGT:
9159 case ICmpInst::ICMP_SGT: {
9160 // X > MAX ? T : F --> F
9161 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9162 return ReplaceInstUsesWith(SI, FalseVal);
9163 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009164 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009165 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9166 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9167 Pred = ICmpInst::getSwappedPredicate(Pred);
9168 CmpRHS = AdjustedRHS;
9169 std::swap(FalseVal, TrueVal);
9170 ICI->setPredicate(Pred);
9171 ICI->setOperand(1, CmpRHS);
9172 SI.setOperand(1, TrueVal);
9173 SI.setOperand(2, FalseVal);
9174 Changed = true;
9175 }
9176 break;
9177 }
9178 }
9179
Dan Gohman35b76162008-10-30 20:40:10 +00009180 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9181 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009182 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohmancdff2122009-08-12 16:23:25 +00009183 if (match(TrueVal, m_ConstantInt<-1>()) &&
9184 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009185 Pred = ICI->getPredicate();
Dan Gohmancdff2122009-08-12 16:23:25 +00009186 else if (match(TrueVal, m_ConstantInt<0>()) &&
9187 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009188 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9189
Dan Gohman35b76162008-10-30 20:40:10 +00009190 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9191 // If we are just checking for a icmp eq of a single bit and zext'ing it
9192 // to an integer, then shift the bit to the appropriate place and then
9193 // cast to integer to avoid the comparison.
9194 const APInt &Op1CV = CI->getValue();
9195
9196 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9197 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9198 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009199 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009200 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00009201 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009202 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009203 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00009204 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00009205 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009206 if (In->getType() != SI.getType())
9207 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009208 true/*SExt*/, "tmp", ICI);
9209
9210 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohmancdff2122009-08-12 16:23:25 +00009211 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman35b76162008-10-30 20:40:10 +00009212 In->getName()+".not"), *ICI);
9213
9214 return ReplaceInstUsesWith(SI, In);
9215 }
9216 }
9217 }
9218
Dan Gohman58c09632008-09-16 18:46:06 +00009219 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9220 // Transform (X == Y) ? X : Y -> Y
9221 if (Pred == ICmpInst::ICMP_EQ)
9222 return ReplaceInstUsesWith(SI, FalseVal);
9223 // Transform (X != Y) ? X : Y -> X
9224 if (Pred == ICmpInst::ICMP_NE)
9225 return ReplaceInstUsesWith(SI, TrueVal);
9226 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9227
9228 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9229 // Transform (X == Y) ? Y : X -> X
9230 if (Pred == ICmpInst::ICMP_EQ)
9231 return ReplaceInstUsesWith(SI, FalseVal);
9232 // Transform (X != Y) ? Y : X -> Y
9233 if (Pred == ICmpInst::ICMP_NE)
9234 return ReplaceInstUsesWith(SI, TrueVal);
9235 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9236 }
9237
9238 /// NOTE: if we wanted to, this is where to detect integer ABS
9239
9240 return Changed ? &SI : 0;
9241}
9242
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009243/// isDefinedInBB - Return true if the value is an instruction defined in the
9244/// specified basicblock.
9245static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9246 const Instruction *I = dyn_cast<Instruction>(V);
9247 return I != 0 && I->getParent() == BB;
9248}
9249
9250
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009251Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9252 Value *CondVal = SI.getCondition();
9253 Value *TrueVal = SI.getTrueValue();
9254 Value *FalseVal = SI.getFalseValue();
9255
9256 // select true, X, Y -> X
9257 // select false, X, Y -> Y
9258 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9259 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9260
9261 // select C, X, X -> X
9262 if (TrueVal == FalseVal)
9263 return ReplaceInstUsesWith(SI, TrueVal);
9264
9265 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9266 return ReplaceInstUsesWith(SI, FalseVal);
9267 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9268 return ReplaceInstUsesWith(SI, TrueVal);
9269 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9270 if (isa<Constant>(TrueVal))
9271 return ReplaceInstUsesWith(SI, TrueVal);
9272 else
9273 return ReplaceInstUsesWith(SI, FalseVal);
9274 }
9275
Owen Anderson35b47072009-08-13 21:58:54 +00009276 if (SI.getType() == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009277 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9278 if (C->getZExtValue()) {
9279 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009280 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009281 } else {
9282 // Change: A = select B, false, C --> A = and !B, C
9283 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009284 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009285 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009286 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009287 }
9288 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9289 if (C->getZExtValue() == false) {
9290 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009291 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009292 } else {
9293 // Change: A = select B, C, true --> A = or !B, C
9294 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009295 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009296 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009297 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009298 }
9299 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009300
9301 // select a, b, a -> a&b
9302 // select a, a, b -> a|b
9303 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009304 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009305 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009306 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009307 }
9308
9309 // Selecting between two integer constants?
9310 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9311 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9312 // select C, 1, 0 -> zext C to int
9313 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009314 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009315 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9316 // select C, 0, 1 -> zext !C to int
9317 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009318 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009319 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009320 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009321 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009322
9323 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009324 // If one of the constants is zero (we know they can't both be) and we
9325 // have an icmp instruction with zero, and we have an 'and' with the
9326 // non-constant value, eliminate this whole mess. This corresponds to
9327 // cases like this: ((X & 27) ? 27 : 0)
9328 if (TrueValC->isZero() || FalseValC->isZero())
9329 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9330 cast<Constant>(IC->getOperand(1))->isNullValue())
9331 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9332 if (ICA->getOpcode() == Instruction::And &&
9333 isa<ConstantInt>(ICA->getOperand(1)) &&
9334 (ICA->getOperand(1) == TrueValC ||
9335 ICA->getOperand(1) == FalseValC) &&
9336 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9337 // Okay, now we know that everything is set up, we just don't
9338 // know whether we have a icmp_ne or icmp_eq and whether the
9339 // true or false val is the zero.
9340 bool ShouldNotVal = !TrueValC->isZero();
9341 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9342 Value *V = ICA;
9343 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009344 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009345 Instruction::Xor, V, ICA->getOperand(1)), SI);
9346 return ReplaceInstUsesWith(SI, V);
9347 }
9348 }
9349 }
9350
9351 // See if we are selecting two values based on a comparison of the two values.
9352 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9353 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9354 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009355 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9356 // This is not safe in general for floating point:
9357 // consider X== -0, Y== +0.
9358 // It becomes safe if either operand is a nonzero constant.
9359 ConstantFP *CFPt, *CFPf;
9360 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9361 !CFPt->getValueAPF().isZero()) ||
9362 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9363 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009364 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009365 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009366 // Transform (X != Y) ? X : Y -> X
9367 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9368 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009369 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009370
9371 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9372 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009373 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9374 // This is not safe in general for floating point:
9375 // consider X== -0, Y== +0.
9376 // It becomes safe if either operand is a nonzero constant.
9377 ConstantFP *CFPt, *CFPf;
9378 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9379 !CFPt->getValueAPF().isZero()) ||
9380 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9381 !CFPf->getValueAPF().isZero()))
9382 return ReplaceInstUsesWith(SI, FalseVal);
9383 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009384 // Transform (X != Y) ? Y : X -> Y
9385 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9386 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009387 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009388 }
Dan Gohman58c09632008-09-16 18:46:06 +00009389 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009390 }
9391
9392 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009393 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9394 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9395 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009396
9397 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9398 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9399 if (TI->hasOneUse() && FI->hasOneUse()) {
9400 Instruction *AddOp = 0, *SubOp = 0;
9401
9402 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9403 if (TI->getOpcode() == FI->getOpcode())
9404 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9405 return IV;
9406
9407 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9408 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009409 if ((TI->getOpcode() == Instruction::Sub &&
9410 FI->getOpcode() == Instruction::Add) ||
9411 (TI->getOpcode() == Instruction::FSub &&
9412 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009413 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009414 } else if ((FI->getOpcode() == Instruction::Sub &&
9415 TI->getOpcode() == Instruction::Add) ||
9416 (FI->getOpcode() == Instruction::FSub &&
9417 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009418 AddOp = TI; SubOp = FI;
9419 }
9420
9421 if (AddOp) {
9422 Value *OtherAddOp = 0;
9423 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9424 OtherAddOp = AddOp->getOperand(1);
9425 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9426 OtherAddOp = AddOp->getOperand(0);
9427 }
9428
9429 if (OtherAddOp) {
9430 // So at this point we know we have (Y -> OtherAddOp):
9431 // select C, (add X, Y), (sub X, Z)
9432 Value *NegVal; // Compute -Z
9433 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00009434 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009435 } else {
9436 NegVal = InsertNewInstBefore(
Dan Gohmancdff2122009-08-12 16:23:25 +00009437 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00009438 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009439 }
9440
9441 Value *NewTrueOp = OtherAddOp;
9442 Value *NewFalseOp = NegVal;
9443 if (AddOp != TI)
9444 std::swap(NewTrueOp, NewFalseOp);
9445 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009446 SelectInst::Create(CondVal, NewTrueOp,
9447 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009448
9449 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009450 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009451 }
9452 }
9453 }
9454
9455 // See if we can fold the select into one of our operands.
9456 if (SI.getType()->isInteger()) {
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009457 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9458 if (FoldI)
9459 return FoldI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009460 }
9461
Chris Lattnerf7843b72009-09-27 19:57:57 +00009462 // See if we can fold the select into a phi node. The true/false values have
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009463 // to be live in the predecessor blocks. If they are instructions in SI's
9464 // block, we can't map to the predecessor.
Chris Lattnerf7843b72009-09-27 19:57:57 +00009465 if (isa<PHINode>(SI.getCondition()) &&
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009466 (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9467 isa<PHINode>(SI.getTrueValue())) &&
9468 (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9469 isa<PHINode>(SI.getFalseValue())))
Chris Lattnerf7843b72009-09-27 19:57:57 +00009470 if (Instruction *NV = FoldOpIntoPhi(SI))
9471 return NV;
9472
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009473 if (BinaryOperator::isNot(CondVal)) {
9474 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9475 SI.setOperand(1, FalseVal);
9476 SI.setOperand(2, TrueVal);
9477 return &SI;
9478 }
9479
9480 return 0;
9481}
9482
Dan Gohman2d648bb2008-04-10 18:43:06 +00009483/// EnforceKnownAlignment - If the specified pointer points to an object that
9484/// we control, modify the object's alignment to PrefAlign. This isn't
9485/// often possible though. If alignment is important, a more reliable approach
9486/// is to simply align all global variables and allocation instructions to
9487/// their preferred alignment from the beginning.
9488///
9489static unsigned EnforceKnownAlignment(Value *V,
9490 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009491
Dan Gohman2d648bb2008-04-10 18:43:06 +00009492 User *U = dyn_cast<User>(V);
9493 if (!U) return Align;
9494
Dan Gohman9545fb02009-07-17 20:47:02 +00009495 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009496 default: break;
9497 case Instruction::BitCast:
9498 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9499 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009500 // If all indexes are zero, it is just the alignment of the base pointer.
9501 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009502 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009503 if (!isa<Constant>(*i) ||
9504 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009505 AllZeroOperands = false;
9506 break;
9507 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009508
9509 if (AllZeroOperands) {
9510 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009511 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009512 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009513 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009514 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009515 }
9516
9517 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9518 // If there is a large requested alignment and we can, bump up the alignment
9519 // of the global.
9520 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009521 if (GV->getAlignment() >= PrefAlign)
9522 Align = GV->getAlignment();
9523 else {
9524 GV->setAlignment(PrefAlign);
9525 Align = PrefAlign;
9526 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009527 }
Chris Lattnere8ad9ae2009-09-27 21:42:46 +00009528 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9529 // If there is a requested alignment and if this is an alloca, round up.
9530 if (AI->getAlignment() >= PrefAlign)
9531 Align = AI->getAlignment();
9532 else {
9533 AI->setAlignment(PrefAlign);
9534 Align = PrefAlign;
Dan Gohman2d648bb2008-04-10 18:43:06 +00009535 }
9536 }
9537
9538 return Align;
9539}
9540
9541/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9542/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9543/// and it is more than the alignment of the ultimate object, see if we can
9544/// increase the alignment of the ultimate object, making this check succeed.
9545unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9546 unsigned PrefAlign) {
9547 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9548 sizeof(PrefAlign) * CHAR_BIT;
9549 APInt Mask = APInt::getAllOnesValue(BitWidth);
9550 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9551 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9552 unsigned TrailZ = KnownZero.countTrailingOnes();
9553 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9554
9555 if (PrefAlign > Align)
9556 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9557
9558 // We don't need to make any adjustment.
9559 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009560}
9561
Chris Lattner00ae5132008-01-13 23:50:23 +00009562Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009563 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009564 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009565 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009566 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009567
9568 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009569 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009570 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00009571 return MI;
9572 }
9573
9574 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9575 // load/store.
9576 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9577 if (MemOpLength == 0) return 0;
9578
Chris Lattnerc669fb62008-01-14 00:28:35 +00009579 // Source and destination pointer types are always "i8*" for intrinsic. See
9580 // if the size is something we can handle with a single primitive load/store.
9581 // A single load+store correctly handles overlapping memory in the memmove
9582 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009583 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009584 if (Size == 0) return MI; // Delete this mem transfer.
9585
9586 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009587 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009588
Chris Lattnerc669fb62008-01-14 00:28:35 +00009589 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00009590 Type *NewPtrTy =
Owen Anderson35b47072009-08-13 21:58:54 +00009591 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009592
9593 // Memcpy forces the use of i8* for the source and destination. That means
9594 // that if you're using memcpy to move one double around, you'll get a cast
9595 // from double* to i8*. We'd much rather use a double load+store rather than
9596 // an i64 load+store, here because this improves the odds that the source or
9597 // dest address will be promotable. See if we can find a better type than the
9598 // integer datatype.
9599 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9600 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00009601 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009602 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9603 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009604 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009605 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9606 if (STy->getNumElements() == 1)
9607 SrcETy = STy->getElementType(0);
9608 else
9609 break;
9610 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9611 if (ATy->getNumElements() == 1)
9612 SrcETy = ATy->getElementType();
9613 else
9614 break;
9615 } else
9616 break;
9617 }
9618
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009619 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009620 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009621 }
9622 }
9623
9624
Chris Lattner00ae5132008-01-13 23:50:23 +00009625 // If the memcpy/memmove provides better alignment info than we can
9626 // infer, use it.
9627 SrcAlign = std::max(SrcAlign, CopyAlign);
9628 DstAlign = std::max(DstAlign, CopyAlign);
9629
Chris Lattner78628292009-08-30 19:47:22 +00009630 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9631 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009632 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9633 InsertNewInstBefore(L, *MI);
9634 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9635
9636 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009637 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009638 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009639}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009640
Chris Lattner5af8a912008-04-30 06:39:11 +00009641Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9642 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009643 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009644 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009645 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +00009646 return MI;
9647 }
9648
9649 // Extract the length and alignment and fill if they are constant.
9650 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9651 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson35b47072009-08-13 21:58:54 +00009652 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner5af8a912008-04-30 06:39:11 +00009653 return 0;
9654 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009655 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009656
9657 // If the length is zero, this is a no-op
9658 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9659
9660 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9661 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson35b47072009-08-13 21:58:54 +00009662 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00009663
9664 Value *Dest = MI->getDest();
Chris Lattner78628292009-08-30 19:47:22 +00009665 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner5af8a912008-04-30 06:39:11 +00009666
9667 // Alignment 0 is identity for alignment 1 for memset, but not store.
9668 if (Alignment == 0) Alignment = 1;
9669
9670 // Extract the fill value and store.
9671 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +00009672 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +00009673 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009674
9675 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009676 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00009677 return MI;
9678 }
9679
9680 return 0;
9681}
9682
9683
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009684/// visitCallInst - CallInst simplification. This mostly only handles folding
9685/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9686/// the heavy lifting.
9687///
9688Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraa295aa2009-05-13 17:39:14 +00009689 // If the caller function is nounwind, mark the call as nounwind, even if the
9690 // callee isn't.
9691 if (CI.getParent()->getParent()->doesNotThrow() &&
9692 !CI.doesNotThrow()) {
9693 CI.setDoesNotThrow();
9694 return &CI;
9695 }
9696
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009697 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9698 if (!II) return visitCallSite(&CI);
9699
9700 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9701 // visitCallSite.
9702 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9703 bool Changed = false;
9704
9705 // memmove/cpy/set of zero bytes is a noop.
9706 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9707 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9708
9709 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9710 if (CI->getZExtValue() == 1) {
9711 // Replace the instruction with just byte operations. We would
9712 // transform other cases to loads/stores, but we don't know if
9713 // alignment is sufficient.
9714 }
9715 }
9716
9717 // If we have a memmove and the source operation is a constant global,
9718 // then the source and dest pointers can't alias, so we can change this
9719 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009720 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009721 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9722 if (GVSrc->isConstant()) {
9723 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009724 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9725 const Type *Tys[1];
9726 Tys[0] = CI.getOperand(3)->getType();
9727 CI.setOperand(0,
9728 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009729 Changed = true;
9730 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009731
9732 // memmove(x,x,size) -> noop.
9733 if (MMI->getSource() == MMI->getDest())
9734 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009735 }
9736
9737 // If we can determine a pointer alignment that is bigger than currently
9738 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009739 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009740 if (Instruction *I = SimplifyMemTransfer(MI))
9741 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009742 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9743 if (Instruction *I = SimplifyMemSet(MSI))
9744 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009745 }
9746
9747 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009748 }
9749
9750 switch (II->getIntrinsicID()) {
9751 default: break;
9752 case Intrinsic::bswap:
9753 // bswap(bswap(x)) -> x
9754 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9755 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9756 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9757 break;
9758 case Intrinsic::ppc_altivec_lvx:
9759 case Intrinsic::ppc_altivec_lvxl:
9760 case Intrinsic::x86_sse_loadu_ps:
9761 case Intrinsic::x86_sse2_loadu_pd:
9762 case Intrinsic::x86_sse2_loadu_dq:
9763 // Turn PPC lvx -> load if the pointer is known aligned.
9764 // Turn X86 loadups -> load if the pointer is known aligned.
9765 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner78628292009-08-30 19:47:22 +00009766 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9767 PointerType::getUnqual(II->getType()));
Chris Lattner989ba312008-06-18 04:33:20 +00009768 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009769 }
Chris Lattner989ba312008-06-18 04:33:20 +00009770 break;
9771 case Intrinsic::ppc_altivec_stvx:
9772 case Intrinsic::ppc_altivec_stvxl:
9773 // Turn stvx -> store if the pointer is known aligned.
9774 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9775 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009776 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00009777 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00009778 return new StoreInst(II->getOperand(1), Ptr);
9779 }
9780 break;
9781 case Intrinsic::x86_sse_storeu_ps:
9782 case Intrinsic::x86_sse2_storeu_pd:
9783 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009784 // Turn X86 storeu -> store if the pointer is known aligned.
9785 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9786 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009787 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00009788 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00009789 return new StoreInst(II->getOperand(2), Ptr);
9790 }
9791 break;
9792
9793 case Intrinsic::x86_sse_cvttss2si: {
9794 // These intrinsics only demands the 0th element of its input vector. If
9795 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00009796 unsigned VWidth =
9797 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9798 APInt DemandedElts(VWidth, 1);
9799 APInt UndefElts(VWidth, 0);
9800 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00009801 UndefElts)) {
9802 II->setOperand(1, V);
9803 return II;
9804 }
9805 break;
9806 }
9807
9808 case Intrinsic::ppc_altivec_vperm:
9809 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9810 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9811 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009812
Chris Lattner989ba312008-06-18 04:33:20 +00009813 // Check that all of the elements are integer constants or undefs.
9814 bool AllEltsOk = true;
9815 for (unsigned i = 0; i != 16; ++i) {
9816 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9817 !isa<UndefValue>(Mask->getOperand(i))) {
9818 AllEltsOk = false;
9819 break;
9820 }
9821 }
9822
9823 if (AllEltsOk) {
9824 // Cast the input vectors to byte vectors.
Chris Lattner78628292009-08-30 19:47:22 +00009825 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9826 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00009827 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009828
Chris Lattner989ba312008-06-18 04:33:20 +00009829 // Only extract each element once.
9830 Value *ExtractedElts[32];
9831 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9832
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009833 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00009834 if (isa<UndefValue>(Mask->getOperand(i)))
9835 continue;
9836 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9837 Idx &= 31; // Match the hardware behavior.
9838
9839 if (ExtractedElts[Idx] == 0) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009840 ExtractedElts[Idx] =
9841 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9842 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9843 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009844 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009845
Chris Lattner989ba312008-06-18 04:33:20 +00009846 // Insert this value into the result vector.
Chris Lattnerad7516a2009-08-30 18:50:58 +00009847 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9848 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9849 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009850 }
Chris Lattner989ba312008-06-18 04:33:20 +00009851 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009852 }
Chris Lattner989ba312008-06-18 04:33:20 +00009853 }
9854 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009855
Chris Lattner989ba312008-06-18 04:33:20 +00009856 case Intrinsic::stackrestore: {
9857 // If the save is right next to the restore, remove the restore. This can
9858 // happen when variable allocas are DCE'd.
9859 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9860 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9861 BasicBlock::iterator BI = SS;
9862 if (&*++BI == II)
9863 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009864 }
Chris Lattner989ba312008-06-18 04:33:20 +00009865 }
9866
9867 // Scan down this block to see if there is another stack restore in the
9868 // same block without an intervening call/alloca.
9869 BasicBlock::iterator BI = II;
9870 TerminatorInst *TI = II->getParent()->getTerminator();
9871 bool CannotRemove = false;
9872 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez48c3c542009-09-18 22:35:49 +00009873 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner989ba312008-06-18 04:33:20 +00009874 CannotRemove = true;
9875 break;
9876 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00009877 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9878 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9879 // If there is a stackrestore below this one, remove this one.
9880 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9881 return EraseInstFromFunction(CI);
9882 // Otherwise, ignore the intrinsic.
9883 } else {
9884 // If we found a non-intrinsic call, we can't remove the stack
9885 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00009886 CannotRemove = true;
9887 break;
9888 }
Chris Lattner989ba312008-06-18 04:33:20 +00009889 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009890 }
Chris Lattner989ba312008-06-18 04:33:20 +00009891
9892 // If the stack restore is in a return/unwind block and if there are no
9893 // allocas or calls between the restore and the return, nuke the restore.
9894 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9895 return EraseInstFromFunction(CI);
9896 break;
9897 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009898 }
9899
9900 return visitCallSite(II);
9901}
9902
9903// InvokeInst simplification
9904//
9905Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9906 return visitCallSite(&II);
9907}
9908
Dale Johannesen96021832008-04-25 21:16:07 +00009909/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9910/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00009911static bool isSafeToEliminateVarargsCast(const CallSite CS,
9912 const CastInst * const CI,
9913 const TargetData * const TD,
9914 const int ix) {
9915 if (!CI->isLosslessCast())
9916 return false;
9917
9918 // The size of ByVal arguments is derived from the type, so we
9919 // can't change to a type with a different size. If the size were
9920 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +00009921 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +00009922 return true;
9923
9924 const Type* SrcTy =
9925 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9926 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9927 if (!SrcTy->isSized() || !DstTy->isSized())
9928 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +00009929 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +00009930 return false;
9931 return true;
9932}
9933
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009934// visitCallSite - Improvements for call and invoke instructions.
9935//
9936Instruction *InstCombiner::visitCallSite(CallSite CS) {
9937 bool Changed = false;
9938
9939 // If the callee is a constexpr cast of a function, attempt to move the cast
9940 // to the arguments of the call/invoke.
9941 if (transformConstExprCastCall(CS)) return 0;
9942
9943 Value *Callee = CS.getCalledValue();
9944
9945 if (Function *CalleeF = dyn_cast<Function>(Callee))
9946 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9947 Instruction *OldCall = CS.getInstruction();
9948 // If the call and callee calling conventions don't match, this call must
9949 // be unreachable, as the call is undefined.
Owen Anderson4f720fa2009-07-31 17:39:07 +00009950 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +00009951 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Anderson24be4c12009-07-03 00:17:18 +00009952 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009953 if (!OldCall->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00009954 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009955 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9956 return EraseInstFromFunction(*OldCall);
9957 return 0;
9958 }
9959
9960 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9961 // This instruction is not reachable, just remove it. We insert a store to
9962 // undef so that we know that this code is not reachable, despite the fact
9963 // that we can't modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +00009964 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +00009965 UndefValue::get(Type::getInt1PtrTy(*Context)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009966 CS.getInstruction());
9967
9968 if (!CS.getInstruction()->use_empty())
9969 CS.getInstruction()->
Owen Andersonb99ecca2009-07-30 23:03:37 +00009970 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009971
9972 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9973 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009974 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson4f720fa2009-07-31 17:39:07 +00009975 ConstantInt::getTrue(*Context), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009976 }
9977 return EraseInstFromFunction(*CS.getInstruction());
9978 }
9979
Duncan Sands74833f22007-09-17 10:26:40 +00009980 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9981 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9982 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9983 return transformCallThroughTrampoline(CS);
9984
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009985 const PointerType *PTy = cast<PointerType>(Callee->getType());
9986 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9987 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00009988 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009989 // See if we can optimize any arguments passed through the varargs area of
9990 // the call.
9991 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00009992 E = CS.arg_end(); I != E; ++I, ++ix) {
9993 CastInst *CI = dyn_cast<CastInst>(*I);
9994 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9995 *I = CI->getOperand(0);
9996 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009997 }
Dale Johannesen35615462008-04-23 18:34:37 +00009998 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009999 }
10000
Duncan Sands2937e352007-12-19 21:13:37 +000010001 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010002 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010003 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010004 Changed = true;
10005 }
10006
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010007 return Changed ? CS.getInstruction() : 0;
10008}
10009
10010// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10011// attempt to move the cast to the arguments of the call/invoke.
10012//
10013bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10014 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10015 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10016 if (CE->getOpcode() != Instruction::BitCast ||
10017 !isa<Function>(CE->getOperand(0)))
10018 return false;
10019 Function *Callee = cast<Function>(CE->getOperand(0));
10020 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010021 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010022
10023 // Okay, this is a cast from a function to a different type. Unless doing so
10024 // would cause a type conversion of one of our arguments, change this call to
10025 // be a direct call with arguments casted to the appropriate types.
10026 //
10027 const FunctionType *FT = Callee->getFunctionType();
10028 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010029 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010030
Duncan Sands7901ce12008-06-01 07:38:42 +000010031 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010032 return false; // TODO: Handle multiple return values.
10033
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010034 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010035 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010036 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010037 // Conversion is ok if changing from one pointer type to another or from
10038 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +000010039 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010040 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000010041 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010042 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010043 return false; // Cannot transform this return value.
10044
Duncan Sands5c489582008-01-06 10:12:28 +000010045 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010046 // void -> non-void is handled specially
Owen Anderson35b47072009-08-13 21:58:54 +000010047 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010048 return false; // Cannot transform this return value.
10049
Chris Lattner1c8733e2008-03-12 17:45:29 +000010050 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010051 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010052 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010053 return false; // Attribute not compatible with transformed value.
10054 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010055
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010056 // If the callsite is an invoke instruction, and the return value is used by
10057 // a PHI node in a successor, we cannot change the return type of the call
10058 // because there is no place to put the cast instruction (without breaking
10059 // the critical edge). Bail out in this case.
10060 if (!Caller->use_empty())
10061 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10062 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10063 UI != E; ++UI)
10064 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10065 if (PN->getParent() == II->getNormalDest() ||
10066 PN->getParent() == II->getUnwindDest())
10067 return false;
10068 }
10069
10070 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10071 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10072
10073 CallSite::arg_iterator AI = CS.arg_begin();
10074 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10075 const Type *ParamTy = FT->getParamType(i);
10076 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010077
10078 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010079 return false; // Cannot transform this parameter value.
10080
Devang Patelf2a4a922008-09-26 22:53:05 +000010081 if (CallerPAL.getParamAttributes(i + 1)
10082 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010083 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010084
Duncan Sands7901ce12008-06-01 07:38:42 +000010085 // Converting from one pointer type to another or between a pointer and an
10086 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010087 bool isConvertible = ActTy == ParamTy ||
Owen Anderson35b47072009-08-13 21:58:54 +000010088 (TD && ((isa<PointerType>(ParamTy) ||
10089 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10090 (isa<PointerType>(ActTy) ||
10091 ActTy == TD->getIntPtrType(Caller->getContext()))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010092 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010093 }
10094
10095 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10096 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010097 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010098
Chris Lattner1c8733e2008-03-12 17:45:29 +000010099 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10100 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010101 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010102 // won't be dropping them. Check that these extra arguments have attributes
10103 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010104 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10105 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010106 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010107 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010108 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010109 return false;
10110 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010111
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010112 // Okay, we decided that this is a safe thing to do: go ahead and start
10113 // inserting cast instructions as necessary...
10114 std::vector<Value*> Args;
10115 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010116 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010117 attrVec.reserve(NumCommonArgs);
10118
10119 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010120 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010121
10122 // If the return value is not being used, the type may not be compatible
10123 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010124 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010125
10126 // Add the new return attributes.
10127 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010128 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010129
10130 AI = CS.arg_begin();
10131 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10132 const Type *ParamTy = FT->getParamType(i);
10133 if ((*AI)->getType() == ParamTy) {
10134 Args.push_back(*AI);
10135 } else {
10136 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10137 false, ParamTy, false);
Chris Lattnerad7516a2009-08-30 18:50:58 +000010138 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010139 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010140
10141 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010142 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010143 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010144 }
10145
10146 // If the function takes more arguments than the call was taking, add them
Chris Lattnerad7516a2009-08-30 18:50:58 +000010147 // now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010148 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +000010149 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010150
Chris Lattnerad7516a2009-08-30 18:50:58 +000010151 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010152 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010153 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +000010154 errs() << "WARNING: While resolving call to function '"
10155 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010156 } else {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010157 // Add all of the arguments in their promoted form to the arg list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010158 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10159 const Type *PTy = getPromotedType((*AI)->getType());
10160 if (PTy != (*AI)->getType()) {
10161 // Must promote to pass through va_arg area!
Chris Lattnerad7516a2009-08-30 18:50:58 +000010162 Instruction::CastOps opcode =
10163 CastInst::getCastOpcode(*AI, false, PTy, false);
10164 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010165 } else {
10166 Args.push_back(*AI);
10167 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010168
Duncan Sands4ced1f82008-01-13 08:02:44 +000010169 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010170 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010171 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010172 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010173 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010174 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010175
Devang Patelf2a4a922008-09-26 22:53:05 +000010176 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10177 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10178
Owen Anderson35b47072009-08-13 21:58:54 +000010179 if (NewRetTy == Type::getVoidTy(*Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010180 Caller->setName(""); // Void type should not have a name.
10181
Eric Christopher3e7381f2009-07-25 02:45:27 +000010182 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10183 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010184
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010185 Instruction *NC;
10186 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010187 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010188 Args.begin(), Args.end(),
10189 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010190 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010191 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010192 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010193 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10194 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010195 CallInst *CI = cast<CallInst>(Caller);
10196 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010197 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010198 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010199 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010200 }
10201
10202 // Insert a cast of the return type as necessary.
10203 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010204 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson35b47072009-08-13 21:58:54 +000010205 if (NV->getType() != Type::getVoidTy(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010206 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010207 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010208 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010209
10210 // If this is an invoke instruction, we should insert it after the first
10211 // non-phi, instruction in the normal successor block.
10212 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010213 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010214 InsertNewInstBefore(NC, *I);
10215 } else {
10216 // Otherwise, it's a call, just insert cast right after the call instr
10217 InsertNewInstBefore(NC, *Caller);
10218 }
Chris Lattner4796b622009-08-30 06:22:51 +000010219 Worklist.AddUsersToWorkList(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010220 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010221 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010222 }
10223 }
10224
Chris Lattner26b7f942009-08-31 05:17:58 +000010225
10226 if (!Caller->use_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010227 Caller->replaceAllUsesWith(NV);
Chris Lattner26b7f942009-08-31 05:17:58 +000010228
10229 EraseInstFromFunction(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010230 return true;
10231}
10232
Duncan Sands74833f22007-09-17 10:26:40 +000010233// transformCallThroughTrampoline - Turn a call to a function created by the
10234// init_trampoline intrinsic into a direct call to the underlying function.
10235//
10236Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10237 Value *Callee = CS.getCalledValue();
10238 const PointerType *PTy = cast<PointerType>(Callee->getType());
10239 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010240 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010241
10242 // If the call already has the 'nest' attribute somewhere then give up -
10243 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010244 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010245 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010246
10247 IntrinsicInst *Tramp =
10248 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10249
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010250 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010251 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10252 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10253
Devang Pateld222f862008-09-25 21:00:45 +000010254 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010255 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010256 unsigned NestIdx = 1;
10257 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010258 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010259
10260 // Look for a parameter marked with the 'nest' attribute.
10261 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10262 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010263 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010264 // Record the parameter type and any other attributes.
10265 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010266 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010267 break;
10268 }
10269
10270 if (NestTy) {
10271 Instruction *Caller = CS.getInstruction();
10272 std::vector<Value*> NewArgs;
10273 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10274
Devang Pateld222f862008-09-25 21:00:45 +000010275 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010276 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010277
Duncan Sands74833f22007-09-17 10:26:40 +000010278 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010279 // mean appending it. Likewise for attributes.
10280
Devang Patelf2a4a922008-09-26 22:53:05 +000010281 // Add any result attributes.
10282 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010283 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010284
Duncan Sands74833f22007-09-17 10:26:40 +000010285 {
10286 unsigned Idx = 1;
10287 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10288 do {
10289 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010290 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010291 Value *NestVal = Tramp->getOperand(3);
10292 if (NestVal->getType() != NestTy)
10293 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10294 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010295 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010296 }
10297
10298 if (I == E)
10299 break;
10300
Duncan Sands48b81112008-01-14 19:52:09 +000010301 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010302 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010303 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010304 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010305 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010306
10307 ++Idx, ++I;
10308 } while (1);
10309 }
10310
Devang Patelf2a4a922008-09-26 22:53:05 +000010311 // Add any function attributes.
10312 if (Attributes Attr = Attrs.getFnAttributes())
10313 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10314
Duncan Sands74833f22007-09-17 10:26:40 +000010315 // The trampoline may have been bitcast to a bogus type (FTy).
10316 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010317 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010318
Duncan Sands74833f22007-09-17 10:26:40 +000010319 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010320 NewTypes.reserve(FTy->getNumParams()+1);
10321
Duncan Sands74833f22007-09-17 10:26:40 +000010322 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010323 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010324 {
10325 unsigned Idx = 1;
10326 FunctionType::param_iterator I = FTy->param_begin(),
10327 E = FTy->param_end();
10328
10329 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010330 if (Idx == NestIdx)
10331 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010332 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010333
10334 if (I == E)
10335 break;
10336
Duncan Sands48b81112008-01-14 19:52:09 +000010337 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010338 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010339
10340 ++Idx, ++I;
10341 } while (1);
10342 }
10343
10344 // Replace the trampoline call with a direct call. Let the generic
10345 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010346 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +000010347 FTy->isVarArg());
10348 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010349 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +000010350 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010351 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +000010352 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10353 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010354
10355 Instruction *NewCaller;
10356 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010357 NewCaller = InvokeInst::Create(NewCallee,
10358 II->getNormalDest(), II->getUnwindDest(),
10359 NewArgs.begin(), NewArgs.end(),
10360 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010361 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010362 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010363 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010364 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10365 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010366 if (cast<CallInst>(Caller)->isTailCall())
10367 cast<CallInst>(NewCaller)->setTailCall();
10368 cast<CallInst>(NewCaller)->
10369 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010370 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010371 }
Owen Anderson35b47072009-08-13 21:58:54 +000010372 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sands74833f22007-09-17 10:26:40 +000010373 Caller->replaceAllUsesWith(NewCaller);
10374 Caller->eraseFromParent();
Chris Lattner3183fb62009-08-30 06:13:40 +000010375 Worklist.Remove(Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010376 return 0;
10377 }
10378 }
10379
10380 // Replace the trampoline call with a direct call. Since there is no 'nest'
10381 // parameter, there is no need to adjust the argument list. Let the generic
10382 // code sort out any function type mismatches.
10383 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010384 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +000010385 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010386 CS.setCalledFunction(NewCallee);
10387 return CS.getInstruction();
10388}
10389
Dan Gohman09cf2b62009-09-16 16:50:24 +000010390/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10391/// and if a/b/c and the add's all have a single use, turn this into a phi
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010392/// and a single binop.
10393Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10394 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010395 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010396 unsigned Opc = FirstInst->getOpcode();
10397 Value *LHSVal = FirstInst->getOperand(0);
10398 Value *RHSVal = FirstInst->getOperand(1);
10399
10400 const Type *LHSType = LHSVal->getType();
10401 const Type *RHSType = RHSVal->getType();
10402
Dan Gohman09cf2b62009-09-16 16:50:24 +000010403 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010404 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010405 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10406 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10407 // Verify type of the LHS matches so we don't fold cmp's of different
10408 // types or GEP's with different index types.
10409 I->getOperand(0)->getType() != LHSType ||
10410 I->getOperand(1)->getType() != RHSType)
10411 return 0;
10412
10413 // If they are CmpInst instructions, check their predicates
10414 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10415 if (cast<CmpInst>(I)->getPredicate() !=
10416 cast<CmpInst>(FirstInst)->getPredicate())
10417 return 0;
10418
10419 // Keep track of which operand needs a phi node.
10420 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10421 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10422 }
Dan Gohman09cf2b62009-09-16 16:50:24 +000010423
10424 // If both LHS and RHS would need a PHI, don't do this transformation,
10425 // because it would increase the number of PHIs entering the block,
10426 // which leads to higher register pressure. This is especially
10427 // bad when the PHIs are in the header of a loop.
10428 if (!LHSVal && !RHSVal)
10429 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010430
Chris Lattner30078012008-12-01 03:42:51 +000010431 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010432
10433 Value *InLHS = FirstInst->getOperand(0);
10434 Value *InRHS = FirstInst->getOperand(1);
10435 PHINode *NewLHS = 0, *NewRHS = 0;
10436 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010437 NewLHS = PHINode::Create(LHSType,
10438 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010439 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10440 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10441 InsertNewInstBefore(NewLHS, PN);
10442 LHSVal = NewLHS;
10443 }
10444
10445 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010446 NewRHS = PHINode::Create(RHSType,
10447 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010448 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10449 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10450 InsertNewInstBefore(NewRHS, PN);
10451 RHSVal = NewRHS;
10452 }
10453
10454 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010455 if (NewLHS || NewRHS) {
10456 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10457 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10458 if (NewLHS) {
10459 Value *NewInLHS = InInst->getOperand(0);
10460 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10461 }
10462 if (NewRHS) {
10463 Value *NewInRHS = InInst->getOperand(1);
10464 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10465 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010466 }
10467 }
10468
10469 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010470 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010471 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohmane6803b82009-08-25 23:17:54 +000010472 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson6601fcd2009-07-09 23:48:35 +000010473 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010474}
10475
Chris Lattner9e1916e2008-12-01 02:34:36 +000010476Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10477 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10478
10479 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10480 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010481 // This is true if all GEP bases are allocas and if all indices into them are
10482 // constants.
10483 bool AllBasePointersAreAllocas = true;
Dan Gohman37a534b2009-09-16 02:01:52 +000010484
10485 // We don't want to replace this phi if the replacement would require
Dan Gohman09cf2b62009-09-16 16:50:24 +000010486 // more than one phi, which leads to higher register pressure. This is
10487 // especially bad when the PHIs are in the header of a loop.
Dan Gohman37a534b2009-09-16 02:01:52 +000010488 bool NeededPhi = false;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010489
Dan Gohman09cf2b62009-09-16 16:50:24 +000010490 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010491 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10492 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10493 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10494 GEP->getNumOperands() != FirstInst->getNumOperands())
10495 return 0;
10496
Chris Lattneradf354b2009-02-21 00:46:50 +000010497 // Keep track of whether or not all GEPs are of alloca pointers.
10498 if (AllBasePointersAreAllocas &&
10499 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10500 !GEP->hasAllConstantIndices()))
10501 AllBasePointersAreAllocas = false;
10502
Chris Lattner9e1916e2008-12-01 02:34:36 +000010503 // Compare the operand lists.
10504 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10505 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10506 continue;
10507
10508 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10509 // if one of the PHIs has a constant for the index. The index may be
10510 // substantially cheaper to compute for the constants, so making it a
10511 // variable index could pessimize the path. This also handles the case
10512 // for struct indices, which must always be constant.
10513 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10514 isa<ConstantInt>(GEP->getOperand(op)))
10515 return 0;
10516
10517 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10518 return 0;
Dan Gohman37a534b2009-09-16 02:01:52 +000010519
10520 // If we already needed a PHI for an earlier operand, and another operand
10521 // also requires a PHI, we'd be introducing more PHIs than we're
10522 // eliminating, which increases register pressure on entry to the PHI's
10523 // block.
10524 if (NeededPhi)
10525 return 0;
10526
Chris Lattner9e1916e2008-12-01 02:34:36 +000010527 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohman37a534b2009-09-16 02:01:52 +000010528 NeededPhi = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010529 }
10530 }
10531
Chris Lattneradf354b2009-02-21 00:46:50 +000010532 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010533 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010534 // offset calculation, but all the predecessors will have to materialize the
10535 // stack address into a register anyway. We'd actually rather *clone* the
10536 // load up into the predecessors so that we have a load of a gep of an alloca,
10537 // which can usually all be folded into the load.
10538 if (AllBasePointersAreAllocas)
10539 return 0;
10540
Chris Lattner9e1916e2008-12-01 02:34:36 +000010541 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10542 // that is variable.
10543 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10544
10545 bool HasAnyPHIs = false;
10546 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10547 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10548 Value *FirstOp = FirstInst->getOperand(i);
10549 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10550 FirstOp->getName()+".pn");
10551 InsertNewInstBefore(NewPN, PN);
10552
10553 NewPN->reserveOperandSpace(e);
10554 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10555 OperandPhis[i] = NewPN;
10556 FixedOperands[i] = NewPN;
10557 HasAnyPHIs = true;
10558 }
10559
10560
10561 // Add all operands to the new PHIs.
10562 if (HasAnyPHIs) {
10563 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10564 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10565 BasicBlock *InBB = PN.getIncomingBlock(i);
10566
10567 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10568 if (PHINode *OpPhi = OperandPhis[op])
10569 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10570 }
10571 }
10572
10573 Value *Base = FixedOperands[0];
Dan Gohmanf3a08b82009-09-07 23:54:19 +000010574 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10575 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10576 FixedOperands.end()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000010577 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10578 FixedOperands.end());
Chris Lattner9e1916e2008-12-01 02:34:36 +000010579}
10580
10581
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010582/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10583/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010584/// obvious the value of the load is not changed from the point of the load to
10585/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010586///
10587/// Finally, it is safe, but not profitable, to sink a load targetting a
10588/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10589/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010590static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010591 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10592
10593 for (++BBI; BBI != E; ++BBI)
10594 if (BBI->mayWriteToMemory())
10595 return false;
10596
10597 // Check for non-address taken alloca. If not address-taken already, it isn't
10598 // profitable to do this xform.
10599 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10600 bool isAddressTaken = false;
10601 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10602 UI != E; ++UI) {
10603 if (isa<LoadInst>(UI)) continue;
10604 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10605 // If storing TO the alloca, then the address isn't taken.
10606 if (SI->getOperand(1) == AI) continue;
10607 }
10608 isAddressTaken = true;
10609 break;
10610 }
10611
Chris Lattneradf354b2009-02-21 00:46:50 +000010612 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010613 return false;
10614 }
10615
Chris Lattneradf354b2009-02-21 00:46:50 +000010616 // If this load is a load from a GEP with a constant offset from an alloca,
10617 // then we don't want to sink it. In its present form, it will be
10618 // load [constant stack offset]. Sinking it will cause us to have to
10619 // materialize the stack addresses in each predecessor in a register only to
10620 // do a shared load from register in the successor.
10621 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10622 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10623 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10624 return false;
10625
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010626 return true;
10627}
10628
10629
10630// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10631// operator and they all are only used by the PHI, PHI together their
10632// inputs, and do the operation once, to the result of the PHI.
10633Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10634 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10635
10636 // Scan the instruction, looking for input operations that can be folded away.
10637 // If all input operands to the phi are the same instruction (e.g. a cast from
10638 // the same type or "+42") we can pull the operation through the PHI, reducing
10639 // code size and simplifying code.
10640 Constant *ConstantOp = 0;
10641 const Type *CastSrcTy = 0;
10642 bool isVolatile = false;
10643 if (isa<CastInst>(FirstInst)) {
10644 CastSrcTy = FirstInst->getOperand(0)->getType();
10645 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10646 // Can fold binop, compare or shift here if the RHS is a constant,
10647 // otherwise call FoldPHIArgBinOpIntoPHI.
10648 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10649 if (ConstantOp == 0)
10650 return FoldPHIArgBinOpIntoPHI(PN);
10651 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10652 isVolatile = LI->isVolatile();
10653 // We can't sink the load if the loaded value could be modified between the
10654 // load and the PHI.
10655 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010656 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010657 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010658
10659 // If the PHI is of volatile loads and the load block has multiple
10660 // successors, sinking it would remove a load of the volatile value from
10661 // the path through the other successor.
10662 if (isVolatile &&
10663 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10664 return 0;
10665
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010666 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010667 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010668 } else {
10669 return 0; // Cannot fold this operation.
10670 }
10671
10672 // Check to see if all arguments are the same operation.
10673 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10674 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10675 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10676 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10677 return 0;
10678 if (CastSrcTy) {
10679 if (I->getOperand(0)->getType() != CastSrcTy)
10680 return 0; // Cast operation must match.
10681 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10682 // We can't sink the load if the loaded value could be modified between
10683 // the load and the PHI.
10684 if (LI->isVolatile() != isVolatile ||
10685 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010686 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010687 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010688
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010689 // If the PHI is of volatile loads and the load block has multiple
10690 // successors, sinking it would remove a load of the volatile value from
10691 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010692 if (isVolatile &&
10693 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10694 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010695
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010696 } else if (I->getOperand(1) != ConstantOp) {
10697 return 0;
10698 }
10699 }
10700
10701 // Okay, they are all the same operation. Create a new PHI node of the
10702 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010703 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10704 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010705 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10706
10707 Value *InVal = FirstInst->getOperand(0);
10708 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10709
10710 // Add all operands to the new PHI.
10711 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10712 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10713 if (NewInVal != InVal)
10714 InVal = 0;
10715 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10716 }
10717
10718 Value *PhiVal;
10719 if (InVal) {
10720 // The new PHI unions all of the same values together. This is really
10721 // common, so we handle it intelligently here for compile-time speed.
10722 PhiVal = InVal;
10723 delete NewPN;
10724 } else {
10725 InsertNewInstBefore(NewPN, PN);
10726 PhiVal = NewPN;
10727 }
10728
10729 // Insert and return the new operation.
10730 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010731 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010732 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010733 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010734 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohmane6803b82009-08-25 23:17:54 +000010735 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010736 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010737 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10738
10739 // If this was a volatile load that we are merging, make sure to loop through
10740 // and mark all the input loads as non-volatile. If we don't do this, we will
10741 // insert a new volatile load and the old ones will not be deletable.
10742 if (isVolatile)
10743 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10744 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10745
10746 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010747}
10748
10749/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10750/// that is dead.
10751static bool DeadPHICycle(PHINode *PN,
10752 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10753 if (PN->use_empty()) return true;
10754 if (!PN->hasOneUse()) return false;
10755
10756 // Remember this node, and if we find the cycle, return.
10757 if (!PotentiallyDeadPHIs.insert(PN))
10758 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010759
10760 // Don't scan crazily complex things.
10761 if (PotentiallyDeadPHIs.size() == 16)
10762 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010763
10764 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10765 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10766
10767 return false;
10768}
10769
Chris Lattner27b695d2007-11-06 21:52:06 +000010770/// PHIsEqualValue - Return true if this phi node is always equal to
10771/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10772/// z = some value; x = phi (y, z); y = phi (x, z)
10773static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10774 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10775 // See if we already saw this PHI node.
10776 if (!ValueEqualPHIs.insert(PN))
10777 return true;
10778
10779 // Don't scan crazily complex things.
10780 if (ValueEqualPHIs.size() == 16)
10781 return false;
10782
10783 // Scan the operands to see if they are either phi nodes or are equal to
10784 // the value.
10785 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10786 Value *Op = PN->getIncomingValue(i);
10787 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10788 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10789 return false;
10790 } else if (Op != NonPhiInVal)
10791 return false;
10792 }
10793
10794 return true;
10795}
10796
10797
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010798// PHINode simplification
10799//
10800Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10801 // If LCSSA is around, don't mess with Phi nodes
10802 if (MustPreserveLCSSA) return 0;
10803
10804 if (Value *V = PN.hasConstantValue())
10805 return ReplaceInstUsesWith(PN, V);
10806
10807 // If all PHI operands are the same operation, pull them through the PHI,
10808 // reducing code size.
10809 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010810 isa<Instruction>(PN.getIncomingValue(1)) &&
10811 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10812 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10813 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10814 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010815 PN.getIncomingValue(0)->hasOneUse())
10816 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10817 return Result;
10818
10819 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10820 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10821 // PHI)... break the cycle.
10822 if (PN.hasOneUse()) {
10823 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10824 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10825 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10826 PotentiallyDeadPHIs.insert(&PN);
10827 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010828 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010829 }
10830
10831 // If this phi has a single use, and if that use just computes a value for
10832 // the next iteration of a loop, delete the phi. This occurs with unused
10833 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10834 // common case here is good because the only other things that catch this
10835 // are induction variable analysis (sometimes) and ADCE, which is only run
10836 // late.
10837 if (PHIUser->hasOneUse() &&
10838 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10839 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010840 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010841 }
10842 }
10843
Chris Lattner27b695d2007-11-06 21:52:06 +000010844 // We sometimes end up with phi cycles that non-obviously end up being the
10845 // same value, for example:
10846 // z = some value; x = phi (y, z); y = phi (x, z)
10847 // where the phi nodes don't necessarily need to be in the same block. Do a
10848 // quick check to see if the PHI node only contains a single non-phi value, if
10849 // so, scan to see if the phi cycle is actually equal to that value.
10850 {
10851 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10852 // Scan for the first non-phi operand.
10853 while (InValNo != NumOperandVals &&
10854 isa<PHINode>(PN.getIncomingValue(InValNo)))
10855 ++InValNo;
10856
10857 if (InValNo != NumOperandVals) {
10858 Value *NonPhiInVal = PN.getOperand(InValNo);
10859
10860 // Scan the rest of the operands to see if there are any conflicts, if so
10861 // there is no need to recursively scan other phis.
10862 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10863 Value *OpVal = PN.getIncomingValue(InValNo);
10864 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10865 break;
10866 }
10867
10868 // If we scanned over all operands, then we have one unique value plus
10869 // phi values. Scan PHI nodes to see if they all merge in each other or
10870 // the value.
10871 if (InValNo == NumOperandVals) {
10872 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10873 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10874 return ReplaceInstUsesWith(PN, NonPhiInVal);
10875 }
10876 }
10877 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010878 return 0;
10879}
10880
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010881Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10882 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerf3a23592009-08-30 20:36:46 +000010883 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010884 if (GEP.getNumOperands() == 1)
10885 return ReplaceInstUsesWith(GEP, PtrOp);
10886
10887 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010888 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010889
10890 bool HasZeroPointerIndex = false;
10891 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10892 HasZeroPointerIndex = C->isNullValue();
10893
10894 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10895 return ReplaceInstUsesWith(GEP, PtrOp);
10896
10897 // Eliminate unneeded casts for indices.
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010898 if (TD) {
10899 bool MadeChange = false;
10900 unsigned PtrSize = TD->getPointerSizeInBits();
10901
10902 gep_type_iterator GTI = gep_type_begin(GEP);
10903 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10904 I != E; ++I, ++GTI) {
10905 if (!isa<SequentialType>(*GTI)) continue;
10906
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010907 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010908 // to what we need. If narrower, sign-extend it to what we need. This
10909 // explicit cast can make subsequent optimizations more obvious.
10910 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010911 if (OpBits == PtrSize)
10912 continue;
10913
Chris Lattnerd6164c22009-08-30 20:01:10 +000010914 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010915 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010916 }
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010917 if (MadeChange) return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010918 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010919
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010920 // Combine Indices - If the source pointer to this getelementptr instruction
10921 // is a getelementptr instruction, combine the indices of the two
10922 // getelementptr instructions into a single instruction.
10923 //
Dan Gohman17f46f72009-07-28 01:40:03 +000010924 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010925 // Note that if our source is a gep chain itself that we wait for that
10926 // chain to be resolved before we perform this transformation. This
10927 // avoids us creating a TON of code in some cases.
10928 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010929 if (GetElementPtrInst *SrcGEP =
10930 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10931 if (SrcGEP->getNumOperands() == 2)
10932 return 0; // Wait until our source is folded to completion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010933
10934 SmallVector<Value*, 8> Indices;
10935
10936 // Find out whether the last index in the source GEP is a sequential idx.
10937 bool EndsWithSequential = false;
Chris Lattner1c641fc2009-08-30 05:30:55 +000010938 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10939 I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010940 EndsWithSequential = !isa<StructType>(*I);
10941
10942 // Can we combine the two pointer arithmetics offsets?
10943 if (EndsWithSequential) {
10944 // Replace: gep (gep %P, long B), long A, ...
10945 // With: T = long A+B; gep %P, T, ...
10946 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010947 Value *Sum;
10948 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10949 Value *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +000010950 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010951 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +000010952 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010953 Sum = SO1;
10954 } else {
Chris Lattner1c641fc2009-08-30 05:30:55 +000010955 // If they aren't the same type, then the input hasn't been processed
10956 // by the loop above yet (which canonicalizes sequential index types to
10957 // intptr_t). Just avoid transforming this until the input has been
10958 // normalized.
10959 if (SO1->getType() != GO1->getType())
10960 return 0;
Chris Lattnerad7516a2009-08-30 18:50:58 +000010961 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010962 }
10963
Chris Lattner1c641fc2009-08-30 05:30:55 +000010964 // Update the GEP in place if possible.
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010965 if (Src->getNumOperands() == 2) {
10966 GEP.setOperand(0, Src->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010967 GEP.setOperand(1, Sum);
10968 return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010969 }
Chris Lattner1c641fc2009-08-30 05:30:55 +000010970 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010971 Indices.push_back(Sum);
Chris Lattner1c641fc2009-08-30 05:30:55 +000010972 Indices.append(GEP.op_begin()+2, GEP.op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010973 } else if (isa<Constant>(*GEP.idx_begin()) &&
10974 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010975 Src->getNumOperands() != 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010976 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner1c641fc2009-08-30 05:30:55 +000010977 Indices.append(Src->op_begin()+1, Src->op_end());
10978 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010979 }
10980
Dan Gohmanf3a08b82009-09-07 23:54:19 +000010981 if (!Indices.empty())
10982 return (cast<GEPOperator>(&GEP)->isInBounds() &&
10983 Src->isInBounds()) ?
10984 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
10985 Indices.end(), GEP.getName()) :
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010986 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010987 Indices.end(), GEP.getName());
Chris Lattner95ba1ec2009-08-30 05:00:50 +000010988 }
10989
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010990 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10991 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner95ba1ec2009-08-30 05:00:50 +000010992 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattnerf3a23592009-08-30 20:36:46 +000010993
Chris Lattner83288fa2009-08-30 20:38:21 +000010994 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
10995 // want to change the gep until the bitcasts are eliminated.
10996 if (getBitCastOperand(X)) {
10997 Worklist.AddValue(PtrOp);
10998 return 0;
10999 }
11000
Chris Lattnerf3a23592009-08-30 20:36:46 +000011001 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11002 // into : GEP [10 x i8]* X, i32 0, ...
11003 //
11004 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11005 // into : GEP i8* X, ...
11006 //
11007 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011008 if (HasZeroPointerIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011009 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11010 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011011 if (const ArrayType *CATy =
11012 dyn_cast<ArrayType>(CPTy->getElementType())) {
11013 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11014 if (CATy->getElementType() == XTy->getElementType()) {
11015 // -> GEP i8* X, ...
11016 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011017 return cast<GEPOperator>(&GEP)->isInBounds() ?
11018 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11019 GEP.getName()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000011020 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11021 GEP.getName());
Chris Lattnerf3a23592009-08-30 20:36:46 +000011022 }
11023
11024 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sandscf866e62009-03-02 09:18:21 +000011025 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011026 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011027 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011028 // At this point, we know that the cast source type is a pointer
11029 // to an array of the same type as the destination pointer
11030 // array. Because the array type is never stepped over (there
11031 // is a leading zero) we can fold the cast into this GEP.
11032 GEP.setOperand(0, X);
11033 return &GEP;
11034 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011035 }
11036 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011037 } else if (GEP.getNumOperands() == 2) {
11038 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011039 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11040 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011041 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11042 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000011043 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011044 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11045 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011046 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011047 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011048 Idx[1] = GEP.getOperand(1);
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011049 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11050 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerad7516a2009-08-30 18:50:58 +000011051 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011052 // V and GEP are both pointer types --> BitCast
Chris Lattnerad7516a2009-08-30 18:50:58 +000011053 return new BitCastInst(NewGEP, GEP.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011054 }
11055
11056 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011057 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011058 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011059 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011060
Owen Anderson35b47072009-08-13 21:58:54 +000011061 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011062 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011063 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011064
11065 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11066 // allow either a mul, shift, or constant here.
11067 Value *NewIdx = 0;
11068 ConstantInt *Scale = 0;
11069 if (ArrayEltSize == 1) {
11070 NewIdx = GEP.getOperand(1);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011071 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011072 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011073 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011074 Scale = CI;
11075 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11076 if (Inst->getOpcode() == Instruction::Shl &&
11077 isa<ConstantInt>(Inst->getOperand(1))) {
11078 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11079 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +000011080 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011081 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011082 NewIdx = Inst->getOperand(0);
11083 } else if (Inst->getOpcode() == Instruction::Mul &&
11084 isa<ConstantInt>(Inst->getOperand(1))) {
11085 Scale = cast<ConstantInt>(Inst->getOperand(1));
11086 NewIdx = Inst->getOperand(0);
11087 }
11088 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011089
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011090 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011091 // out, perform the transformation. Note, we don't know whether Scale is
11092 // signed or not. We'll use unsigned version of division/modulo
11093 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011094 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011095 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011096 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011097 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011098 if (Scale->getZExtValue() != 1) {
Chris Lattnerbf09d632009-08-30 05:56:44 +000011099 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11100 false /*ZExt*/);
Chris Lattnerad7516a2009-08-30 18:50:58 +000011101 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011102 }
11103
11104 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011105 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011106 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011107 Idx[1] = NewIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011108 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11109 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11110 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011111 // The NewGEP must be pointer typed, so must the old one -> BitCast
11112 return new BitCastInst(NewGEP, GEP.getType());
11113 }
11114 }
11115 }
11116 }
Chris Lattner111ea772009-01-09 04:53:57 +000011117
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011118 /// See if we can simplify:
Chris Lattner5119c702009-08-30 05:55:36 +000011119 /// X = bitcast A* to B*
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011120 /// Y = gep X, <...constant indices...>
11121 /// into a gep of the original struct. This is important for SROA and alias
11122 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011123 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011124 if (TD &&
11125 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011126 // Determine how much the GEP moves the pointer. We are guaranteed to get
11127 // a constant back from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +000011128 ConstantInt *OffsetV =
11129 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011130 int64_t Offset = OffsetV->getSExtValue();
11131
11132 // If this GEP instruction doesn't move the pointer, just replace the GEP
11133 // with a bitcast of the real input to the dest type.
11134 if (Offset == 0) {
11135 // If the bitcast is of an allocation, and the allocation will be
11136 // converted to match the type of the cast, don't touch this.
Victor Hernandez48c3c542009-09-18 22:35:49 +000011137 if (isa<AllocationInst>(BCI->getOperand(0)) ||
11138 isMalloc(BCI->getOperand(0))) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011139 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11140 if (Instruction *I = visitBitCast(*BCI)) {
11141 if (I != BCI) {
11142 I->takeName(BCI);
11143 BCI->getParent()->getInstList().insert(BCI, I);
11144 ReplaceInstUsesWith(*BCI, I);
11145 }
11146 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011147 }
Chris Lattner111ea772009-01-09 04:53:57 +000011148 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011149 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011150 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011151
11152 // Otherwise, if the offset is non-zero, we need to find out if there is a
11153 // field at Offset in 'A's type. If so, we can pull the cast through the
11154 // GEP.
11155 SmallVector<Value*, 8> NewIndices;
11156 const Type *InTy =
11157 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000011158 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011159 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11160 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11161 NewIndices.end()) :
11162 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11163 NewIndices.end());
Chris Lattnerad7516a2009-08-30 18:50:58 +000011164
11165 if (NGEP->getType() == GEP.getType())
11166 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011167 NGEP->takeName(&GEP);
11168 return new BitCastInst(NGEP, GEP.getType());
11169 }
Chris Lattner111ea772009-01-09 04:53:57 +000011170 }
11171 }
11172
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011173 return 0;
11174}
11175
11176Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11177 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011178 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011179 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11180 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011181 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011182 AllocationInst *New = 0;
11183
11184 // Create and insert the replacement instruction...
11185 if (isa<MallocInst>(AI))
Chris Lattnerad7516a2009-08-30 18:50:58 +000011186 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011187 else {
11188 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerad7516a2009-08-30 18:50:58 +000011189 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011190 }
Chris Lattnerad7516a2009-08-30 18:50:58 +000011191 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011192
11193 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011194 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011195 //
11196 BasicBlock::iterator It = New;
Dale Johannesena499d0d2009-03-11 22:19:43 +000011197 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011198
11199 // Now that I is pointing to the first non-allocation-inst in the block,
11200 // insert our getelementptr instruction...
11201 //
Owen Anderson35b47072009-08-13 21:58:54 +000011202 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011203 Value *Idx[2];
11204 Idx[0] = NullIdx;
11205 Idx[1] = NullIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011206 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11207 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011208
11209 // Now make everything use the getelementptr instead of the original
11210 // allocation.
11211 return ReplaceInstUsesWith(AI, V);
11212 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +000011213 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011214 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011215 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011216
Dan Gohmana80e2712009-07-21 23:21:54 +000011217 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000011218 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011219 // Note that we only do this for alloca's, because malloc should allocate
11220 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011221 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +000011222 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000011223
11224 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11225 if (AI.getAlignment() == 0)
11226 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11227 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011228
11229 return 0;
11230}
11231
11232Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11233 Value *Op = FI.getOperand(0);
11234
11235 // free undef -> unreachable.
11236 if (isa<UndefValue>(Op)) {
11237 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000011238 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000011239 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011240 return EraseInstFromFunction(FI);
11241 }
11242
11243 // If we have 'free null' delete the instruction. This can happen in stl code
11244 // when lots of inlining happens.
11245 if (isa<ConstantPointerNull>(Op))
11246 return EraseInstFromFunction(FI);
11247
11248 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11249 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11250 FI.setOperand(0, CI->getOperand(0));
11251 return &FI;
11252 }
11253
11254 // Change free (gep X, 0,0,0,0) into free(X)
11255 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11256 if (GEPI->hasAllZeroIndices()) {
Chris Lattner3183fb62009-08-30 06:13:40 +000011257 Worklist.Add(GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011258 FI.setOperand(0, GEPI->getOperand(0));
11259 return &FI;
11260 }
11261 }
11262
11263 // Change free(malloc) into nothing, if the malloc has a single use.
11264 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11265 if (MI->hasOneUse()) {
11266 EraseInstFromFunction(FI);
11267 return EraseInstFromFunction(*MI);
11268 }
Victor Hernandez48c3c542009-09-18 22:35:49 +000011269 if (isMalloc(Op)) {
11270 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11271 if (Op->hasOneUse() && CI->hasOneUse()) {
11272 EraseInstFromFunction(FI);
11273 EraseInstFromFunction(*CI);
11274 return EraseInstFromFunction(*cast<Instruction>(Op));
11275 }
11276 } else {
11277 // Op is a call to malloc
11278 if (Op->hasOneUse()) {
11279 EraseInstFromFunction(FI);
11280 return EraseInstFromFunction(*cast<Instruction>(Op));
11281 }
11282 }
11283 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011284
11285 return 0;
11286}
11287
11288
11289/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011290static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011291 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011292 User *CI = cast<User>(LI.getOperand(0));
11293 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011294 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011295
Nick Lewycky291c5942009-05-08 06:47:37 +000011296 if (TD) {
11297 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11298 // Instead of loading constant c string, use corresponding integer value
11299 // directly if string length is small enough.
11300 std::string Str;
11301 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11302 unsigned len = Str.length();
11303 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11304 unsigned numBits = Ty->getPrimitiveSizeInBits();
11305 // Replace LI with immediate integer store.
11306 if ((numBits >> 3) == len + 1) {
11307 APInt StrVal(numBits, 0);
11308 APInt SingleChar(numBits, 0);
11309 if (TD->isLittleEndian()) {
11310 for (signed i = len-1; i >= 0; i--) {
11311 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11312 StrVal = (StrVal << 8) | SingleChar;
11313 }
11314 } else {
11315 for (unsigned i = 0; i < len; i++) {
11316 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11317 StrVal = (StrVal << 8) | SingleChar;
11318 }
11319 // Append NULL at the end.
11320 SingleChar = 0;
Bill Wendling44a36ea2008-02-26 10:53:30 +000011321 StrVal = (StrVal << 8) | SingleChar;
11322 }
Owen Andersoneacb44d2009-07-24 23:12:02 +000011323 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky291c5942009-05-08 06:47:37 +000011324 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling44a36ea2008-02-26 10:53:30 +000011325 }
Devang Patela0f8ea82007-10-18 19:52:32 +000011326 }
11327 }
11328 }
11329
Mon P Wangbd05ed82009-02-07 22:19:29 +000011330 const PointerType *DestTy = cast<PointerType>(CI->getType());
11331 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011332 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011333
11334 // If the address spaces don't match, don't eliminate the cast.
11335 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11336 return 0;
11337
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011338 const Type *SrcPTy = SrcTy->getElementType();
11339
11340 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11341 isa<VectorType>(DestPTy)) {
11342 // If the source is an array, the code below will not succeed. Check to
11343 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11344 // constants.
11345 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11346 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11347 if (ASrcTy->getNumElements() != 0) {
11348 Value *Idxs[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011349 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Anderson02b48c32009-07-29 18:55:55 +000011350 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011351 SrcTy = cast<PointerType>(CastOp->getType());
11352 SrcPTy = SrcTy->getElementType();
11353 }
11354
Dan Gohmana80e2712009-07-21 23:21:54 +000011355 if (IC.getTargetData() &&
11356 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011357 isa<VectorType>(SrcPTy)) &&
11358 // Do not allow turning this into a load of an integer, which is then
11359 // casted to a pointer, this pessimizes pointer analysis a lot.
11360 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000011361 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11362 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011363
11364 // Okay, we are casting from one integer or pointer type to another of
11365 // the same size. Instead of casting the pointer before the load, cast
11366 // the result of the loaded value.
Chris Lattnerad7516a2009-08-30 18:50:58 +000011367 Value *NewLoad =
11368 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011369 // Now cast the result of the load.
11370 return new BitCastInst(NewLoad, LI.getType());
11371 }
11372 }
11373 }
11374 return 0;
11375}
11376
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011377Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11378 Value *Op = LI.getOperand(0);
11379
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011380 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011381 if (TD) {
11382 unsigned KnownAlign =
11383 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11384 if (KnownAlign >
11385 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11386 LI.getAlignment()))
11387 LI.setAlignment(KnownAlign);
11388 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011389
Chris Lattnerf3a23592009-08-30 20:36:46 +000011390 // load (cast X) --> cast (load X) iff safe.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011391 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011392 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011393 return Res;
11394
11395 // None of the following transforms are legal for volatile loads.
11396 if (LI.isVolatile()) return 0;
11397
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011398 // Do really simple store-to-load forwarding and load CSE, to catch cases
11399 // where there are several consequtive memory accesses to the same location,
11400 // separated by a few arithmetic operations.
11401 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011402 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11403 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011404
Christopher Lamb2c175392007-12-29 07:56:53 +000011405 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11406 const Value *GEPI0 = GEPI->getOperand(0);
11407 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +000011408 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011409 // Insert a new store to null instruction before the load to indicate
11410 // that this code is not reachable. We do this instead of inserting
11411 // an unreachable instruction directly because we cannot modify the
11412 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011413 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011414 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011415 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011416 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011417 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011418
11419 if (Constant *C = dyn_cast<Constant>(Op)) {
11420 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000011421 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +000011422 if (isa<UndefValue>(C) ||
11423 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011424 // Insert a new store to null instruction before the load to indicate that
11425 // this code is not reachable. We do this instead of inserting an
11426 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011427 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011428 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011429 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011430 }
11431
11432 // Instcombine load (constant global) into the value loaded.
11433 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands54e70f62009-03-21 21:27:31 +000011434 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011435 return ReplaceInstUsesWith(LI, GV->getInitializer());
11436
11437 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011438 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011439 if (CE->getOpcode() == Instruction::GetElementPtr) {
11440 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +000011441 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011442 if (Constant *V =
Dan Gohmanf49f7b02009-10-05 16:36:26 +000011443 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011444 return ReplaceInstUsesWith(LI, V);
11445 if (CE->getOperand(0)->isNullValue()) {
11446 // Insert a new store to null instruction before the load to indicate
11447 // that this code is not reachable. We do this instead of inserting
11448 // an unreachable instruction directly because we cannot modify the
11449 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011450 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011451 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011452 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011453 }
11454
11455 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000011456 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011457 return Res;
11458 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011459 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011460 }
Chris Lattner0270a112007-08-11 18:48:48 +000011461
11462 // If this load comes from anywhere in a constant global, and if the global
11463 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000011464 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands54e70f62009-03-21 21:27:31 +000011465 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner0270a112007-08-11 18:48:48 +000011466 if (GV->getInitializer()->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +000011467 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011468 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011469 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011470 }
11471 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011472
11473 if (Op->hasOneUse()) {
11474 // Change select and PHI nodes to select values instead of addresses: this
11475 // helps alias analysis out a lot, allows many others simplifications, and
11476 // exposes redundancy in the code.
11477 //
11478 // Note that we cannot do the transformation unless we know that the
11479 // introduced loads cannot trap! Something like this is valid as long as
11480 // the condition is always false: load (select bool %C, int* null, int* %G),
11481 // but it would not be valid if we transformed it to load from null
11482 // unconditionally.
11483 //
11484 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11485 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11486 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11487 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000011488 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11489 SI->getOperand(1)->getName()+".val");
11490 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11491 SI->getOperand(2)->getName()+".val");
Gabor Greifd6da1d02008-04-06 20:25:17 +000011492 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011493 }
11494
11495 // load (select (cond, null, P)) -> load P
11496 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11497 if (C->isNullValue()) {
11498 LI.setOperand(0, SI->getOperand(2));
11499 return &LI;
11500 }
11501
11502 // load (select (cond, P, null)) -> load P
11503 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11504 if (C->isNullValue()) {
11505 LI.setOperand(0, SI->getOperand(1));
11506 return &LI;
11507 }
11508 }
11509 }
11510 return 0;
11511}
11512
11513/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011514/// when possible. This makes it generally easy to do alias analysis and/or
11515/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011516static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11517 User *CI = cast<User>(SI.getOperand(1));
11518 Value *CastOp = CI->getOperand(0);
11519
11520 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011521 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11522 if (SrcTy == 0) return 0;
11523
11524 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011525
Chris Lattnera032c0e2009-01-16 20:08:59 +000011526 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11527 return 0;
11528
Chris Lattner54dddc72009-01-24 01:00:13 +000011529 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11530 /// to its first element. This allows us to handle things like:
11531 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11532 /// on 32-bit hosts.
11533 SmallVector<Value*, 4> NewGEPIndices;
11534
Chris Lattnera032c0e2009-01-16 20:08:59 +000011535 // If the source is an array, the code below will not succeed. Check to
11536 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11537 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011538 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11539 // Index through pointer.
Owen Anderson35b47072009-08-13 21:58:54 +000011540 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner54dddc72009-01-24 01:00:13 +000011541 NewGEPIndices.push_back(Zero);
11542
11543 while (1) {
11544 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011545 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011546 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011547 NewGEPIndices.push_back(Zero);
11548 SrcPTy = STy->getElementType(0);
11549 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11550 NewGEPIndices.push_back(Zero);
11551 SrcPTy = ATy->getElementType();
11552 } else {
11553 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011554 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011555 }
11556
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011557 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000011558 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011559
11560 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11561 return 0;
11562
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011563 // If the pointers point into different address spaces or if they point to
11564 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000011565 if (!IC.getTargetData() ||
11566 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011567 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000011568 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11569 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000011570 return 0;
11571
11572 // Okay, we are casting from one integer or pointer type to another of
11573 // the same size. Instead of casting the pointer before
11574 // the store, cast the value to be stored.
11575 Value *NewCast;
11576 Value *SIOp0 = SI.getOperand(0);
11577 Instruction::CastOps opcode = Instruction::BitCast;
11578 const Type* CastSrcTy = SIOp0->getType();
11579 const Type* CastDstTy = SrcPTy;
11580 if (isa<PointerType>(CastDstTy)) {
11581 if (CastSrcTy->isInteger())
11582 opcode = Instruction::IntToPtr;
11583 } else if (isa<IntegerType>(CastDstTy)) {
11584 if (isa<PointerType>(SIOp0->getType()))
11585 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011586 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011587
11588 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11589 // emit a GEP to index into its first field.
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011590 if (!NewGEPIndices.empty())
11591 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11592 NewGEPIndices.end());
Chris Lattner54dddc72009-01-24 01:00:13 +000011593
Chris Lattnerad7516a2009-08-30 18:50:58 +000011594 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11595 SIOp0->getName()+".c");
Chris Lattnera032c0e2009-01-16 20:08:59 +000011596 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011597}
11598
Chris Lattner6fd8c802008-11-27 08:56:30 +000011599/// equivalentAddressValues - Test if A and B will obviously have the same
11600/// value. This includes recognizing that %t0 and %t1 will have the same
11601/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000011602/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011603/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000011604/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011605/// %t2 = load i32* %t1
11606///
11607static bool equivalentAddressValues(Value *A, Value *B) {
11608 // Test if the values are trivially equivalent.
11609 if (A == B) return true;
11610
11611 // Test if the values come form identical arithmetic instructions.
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000011612 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11613 // its only used to compare two uses within the same basic block, which
11614 // means that they'll always either have the same value or one of them
11615 // will have an undefined value.
Chris Lattner6fd8c802008-11-27 08:56:30 +000011616 if (isa<BinaryOperator>(A) ||
11617 isa<CastInst>(A) ||
11618 isa<PHINode>(A) ||
11619 isa<GetElementPtrInst>(A))
11620 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000011621 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner6fd8c802008-11-27 08:56:30 +000011622 return true;
11623
11624 // Otherwise they may not be equivalent.
11625 return false;
11626}
11627
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011628// If this instruction has two uses, one of which is a llvm.dbg.declare,
11629// return the llvm.dbg.declare.
11630DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11631 if (!V->hasNUses(2))
11632 return 0;
11633 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11634 UI != E; ++UI) {
11635 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11636 return DI;
11637 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11638 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11639 return DI;
11640 }
11641 }
11642 return 0;
11643}
11644
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011645Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11646 Value *Val = SI.getOperand(0);
11647 Value *Ptr = SI.getOperand(1);
11648
11649 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11650 EraseInstFromFunction(SI);
11651 ++NumCombined;
11652 return 0;
11653 }
11654
11655 // If the RHS is an alloca with a single use, zapify the store, making the
11656 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011657 // If the RHS is an alloca with a two uses, the other one being a
11658 // llvm.dbg.declare, zapify the store and the declare, making the
11659 // alloca dead. We must do this to prevent declare's from affecting
11660 // codegen.
11661 if (!SI.isVolatile()) {
11662 if (Ptr->hasOneUse()) {
11663 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011664 EraseInstFromFunction(SI);
11665 ++NumCombined;
11666 return 0;
11667 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011668 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11669 if (isa<AllocaInst>(GEP->getOperand(0))) {
11670 if (GEP->getOperand(0)->hasOneUse()) {
11671 EraseInstFromFunction(SI);
11672 ++NumCombined;
11673 return 0;
11674 }
11675 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11676 EraseInstFromFunction(*DI);
11677 EraseInstFromFunction(SI);
11678 ++NumCombined;
11679 return 0;
11680 }
11681 }
11682 }
11683 }
11684 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11685 EraseInstFromFunction(*DI);
11686 EraseInstFromFunction(SI);
11687 ++NumCombined;
11688 return 0;
11689 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011690 }
11691
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011692 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011693 if (TD) {
11694 unsigned KnownAlign =
11695 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11696 if (KnownAlign >
11697 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11698 SI.getAlignment()))
11699 SI.setAlignment(KnownAlign);
11700 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011701
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011702 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011703 // stores to the same location, separated by a few arithmetic operations. This
11704 // situation often occurs with bitfield accesses.
11705 BasicBlock::iterator BBI = &SI;
11706 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11707 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000011708 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000011709 // Don't count debug info directives, lest they affect codegen,
11710 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11711 // It is necessary for correctness to skip those that feed into a
11712 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000011713 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000011714 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011715 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011716 continue;
11717 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011718
11719 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11720 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011721 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11722 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011723 ++NumDeadStore;
11724 ++BBI;
11725 EraseInstFromFunction(*PrevSI);
11726 continue;
11727 }
11728 break;
11729 }
11730
11731 // If this is a load, we have to stop. However, if the loaded value is from
11732 // the pointer we're loading and is producing the pointer we're storing,
11733 // then *this* store is dead (X = load P; store X -> P).
11734 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011735 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11736 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011737 EraseInstFromFunction(SI);
11738 ++NumCombined;
11739 return 0;
11740 }
11741 // Otherwise, this is a load from some other location. Stores before it
11742 // may not be dead.
11743 break;
11744 }
11745
11746 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011747 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011748 break;
11749 }
11750
11751
11752 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11753
11754 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner6807a242009-08-30 20:06:40 +000011755 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011756 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000011757 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011758 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner3183fb62009-08-30 06:13:40 +000011759 Worklist.Add(U); // Dropped a use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011760 ++NumCombined;
11761 }
11762 return 0; // Do not modify these!
11763 }
11764
11765 // store undef, Ptr -> noop
11766 if (isa<UndefValue>(Val)) {
11767 EraseInstFromFunction(SI);
11768 ++NumCombined;
11769 return 0;
11770 }
11771
11772 // If the pointer destination is a cast, see if we can fold the cast into the
11773 // source instead.
11774 if (isa<CastInst>(Ptr))
11775 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11776 return Res;
11777 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11778 if (CE->isCast())
11779 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11780 return Res;
11781
11782
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011783 // If this store is the last instruction in the basic block (possibly
11784 // excepting debug info instructions and the pointer bitcasts that feed
11785 // into them), and if the block ends with an unconditional branch, try
11786 // to move it to the successor block.
11787 BBI = &SI;
11788 do {
11789 ++BBI;
11790 } while (isa<DbgInfoIntrinsic>(BBI) ||
11791 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011792 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11793 if (BI->isUnconditional())
11794 if (SimplifyStoreAtEndOfBlock(SI))
11795 return 0; // xform done!
11796
11797 return 0;
11798}
11799
11800/// SimplifyStoreAtEndOfBlock - Turn things like:
11801/// if () { *P = v1; } else { *P = v2 }
11802/// into a phi node with a store in the successor.
11803///
11804/// Simplify things like:
11805/// *P = v1; if () { *P = v2; }
11806/// into a phi node with a store in the successor.
11807///
11808bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11809 BasicBlock *StoreBB = SI.getParent();
11810
11811 // Check to see if the successor block has exactly two incoming edges. If
11812 // so, see if the other predecessor contains a store to the same location.
11813 // if so, insert a PHI node (if needed) and move the stores down.
11814 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11815
11816 // Determine whether Dest has exactly two predecessors and, if so, compute
11817 // the other predecessor.
11818 pred_iterator PI = pred_begin(DestBB);
11819 BasicBlock *OtherBB = 0;
11820 if (*PI != StoreBB)
11821 OtherBB = *PI;
11822 ++PI;
11823 if (PI == pred_end(DestBB))
11824 return false;
11825
11826 if (*PI != StoreBB) {
11827 if (OtherBB)
11828 return false;
11829 OtherBB = *PI;
11830 }
11831 if (++PI != pred_end(DestBB))
11832 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000011833
11834 // Bail out if all the relevant blocks aren't distinct (this can happen,
11835 // for example, if SI is in an infinite loop)
11836 if (StoreBB == DestBB || OtherBB == DestBB)
11837 return false;
11838
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011839 // Verify that the other block ends in a branch and is not otherwise empty.
11840 BasicBlock::iterator BBI = OtherBB->getTerminator();
11841 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11842 if (!OtherBr || BBI == OtherBB->begin())
11843 return false;
11844
11845 // If the other block ends in an unconditional branch, check for the 'if then
11846 // else' case. there is an instruction before the branch.
11847 StoreInst *OtherStore = 0;
11848 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011849 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011850 // Skip over debugging info.
11851 while (isa<DbgInfoIntrinsic>(BBI) ||
11852 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11853 if (BBI==OtherBB->begin())
11854 return false;
11855 --BBI;
11856 }
11857 // If this isn't a store, or isn't a store to the same location, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011858 OtherStore = dyn_cast<StoreInst>(BBI);
11859 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11860 return false;
11861 } else {
11862 // Otherwise, the other block ended with a conditional branch. If one of the
11863 // destinations is StoreBB, then we have the if/then case.
11864 if (OtherBr->getSuccessor(0) != StoreBB &&
11865 OtherBr->getSuccessor(1) != StoreBB)
11866 return false;
11867
11868 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11869 // if/then triangle. See if there is a store to the same ptr as SI that
11870 // lives in OtherBB.
11871 for (;; --BBI) {
11872 // Check to see if we find the matching store.
11873 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11874 if (OtherStore->getOperand(1) != SI.getOperand(1))
11875 return false;
11876 break;
11877 }
Eli Friedman3a311d52008-06-13 22:02:12 +000011878 // If we find something that may be using or overwriting the stored
11879 // value, or if we run out of instructions, we can't do the xform.
11880 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011881 BBI == OtherBB->begin())
11882 return false;
11883 }
11884
11885 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000011886 // make sure nothing reads or overwrites the stored value in
11887 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011888 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11889 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000011890 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011891 return false;
11892 }
11893 }
11894
11895 // Insert a PHI node now if we need it.
11896 Value *MergedVal = OtherStore->getOperand(0);
11897 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000011898 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011899 PN->reserveOperandSpace(2);
11900 PN->addIncoming(SI.getOperand(0), SI.getParent());
11901 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11902 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11903 }
11904
11905 // Advance to a place where it is safe to insert the new store and
11906 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000011907 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011908 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11909 OtherStore->isVolatile()), *BBI);
11910
11911 // Nuke the old stores.
11912 EraseInstFromFunction(SI);
11913 EraseInstFromFunction(*OtherStore);
11914 ++NumCombined;
11915 return true;
11916}
11917
11918
11919Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11920 // Change br (not X), label True, label False to: br X, label False, True
11921 Value *X = 0;
11922 BasicBlock *TrueDest;
11923 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +000011924 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011925 !isa<Constant>(X)) {
11926 // Swap Destinations and condition...
11927 BI.setCondition(X);
11928 BI.setSuccessor(0, FalseDest);
11929 BI.setSuccessor(1, TrueDest);
11930 return &BI;
11931 }
11932
11933 // Cannonicalize fcmp_one -> fcmp_oeq
11934 FCmpInst::Predicate FPred; Value *Y;
11935 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000011936 TrueDest, FalseDest)) &&
11937 BI.getCondition()->hasOneUse())
11938 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11939 FPred == FCmpInst::FCMP_OGE) {
11940 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11941 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11942
11943 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011944 BI.setSuccessor(0, FalseDest);
11945 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000011946 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011947 return &BI;
11948 }
11949
11950 // Cannonicalize icmp_ne -> icmp_eq
11951 ICmpInst::Predicate IPred;
11952 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000011953 TrueDest, FalseDest)) &&
11954 BI.getCondition()->hasOneUse())
11955 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11956 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11957 IPred == ICmpInst::ICMP_SGE) {
11958 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11959 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11960 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011961 BI.setSuccessor(0, FalseDest);
11962 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000011963 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011964 return &BI;
11965 }
11966
11967 return 0;
11968}
11969
11970Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11971 Value *Cond = SI.getCondition();
11972 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11973 if (I->getOpcode() == Instruction::Add)
11974 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11975 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11976 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000011977 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +000011978 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011979 AddRHS));
11980 SI.setOperand(0, I->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +000011981 Worklist.Add(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011982 return &SI;
11983 }
11984 }
11985 return 0;
11986}
11987
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011988Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011989 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011990
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011991 if (!EV.hasIndices())
11992 return ReplaceInstUsesWith(EV, Agg);
11993
11994 if (Constant *C = dyn_cast<Constant>(Agg)) {
11995 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011996 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011997
11998 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +000011999 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012000
12001 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12002 // Extract the element indexed by the first index out of the constant
12003 Value *V = C->getOperand(*EV.idx_begin());
12004 if (EV.getNumIndices() > 1)
12005 // Extract the remaining indices out of the constant indexed by the
12006 // first index
12007 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12008 else
12009 return ReplaceInstUsesWith(EV, V);
12010 }
12011 return 0; // Can't handle other constants
12012 }
12013 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12014 // We're extracting from an insertvalue instruction, compare the indices
12015 const unsigned *exti, *exte, *insi, *inse;
12016 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12017 exte = EV.idx_end(), inse = IV->idx_end();
12018 exti != exte && insi != inse;
12019 ++exti, ++insi) {
12020 if (*insi != *exti)
12021 // The insert and extract both reference distinctly different elements.
12022 // This means the extract is not influenced by the insert, and we can
12023 // replace the aggregate operand of the extract with the aggregate
12024 // operand of the insert. i.e., replace
12025 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12026 // %E = extractvalue { i32, { i32 } } %I, 0
12027 // with
12028 // %E = extractvalue { i32, { i32 } } %A, 0
12029 return ExtractValueInst::Create(IV->getAggregateOperand(),
12030 EV.idx_begin(), EV.idx_end());
12031 }
12032 if (exti == exte && insi == inse)
12033 // Both iterators are at the end: Index lists are identical. Replace
12034 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12035 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12036 // with "i32 42"
12037 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12038 if (exti == exte) {
12039 // The extract list is a prefix of the insert list. i.e. replace
12040 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12041 // %E = extractvalue { i32, { i32 } } %I, 1
12042 // with
12043 // %X = extractvalue { i32, { i32 } } %A, 1
12044 // %E = insertvalue { i32 } %X, i32 42, 0
12045 // by switching the order of the insert and extract (though the
12046 // insertvalue should be left in, since it may have other uses).
Chris Lattnerad7516a2009-08-30 18:50:58 +000012047 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12048 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012049 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12050 insi, inse);
12051 }
12052 if (insi == inse)
12053 // The insert list is a prefix of the extract list
12054 // We can simply remove the common indices from the extract and make it
12055 // operate on the inserted value instead of the insertvalue result.
12056 // i.e., replace
12057 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12058 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12059 // with
12060 // %E extractvalue { i32 } { i32 42 }, 0
12061 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12062 exti, exte);
12063 }
12064 // Can't simplify extracts from other values. Note that nested extracts are
12065 // already simplified implicitely by the above (extract ( extract (insert) )
12066 // will be translated into extract ( insert ( extract ) ) first and then just
12067 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012068 return 0;
12069}
12070
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012071/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12072/// is to leave as a vector operation.
12073static bool CheapToScalarize(Value *V, bool isConstant) {
12074 if (isa<ConstantAggregateZero>(V))
12075 return true;
12076 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12077 if (isConstant) return true;
12078 // If all elts are the same, we can extract.
12079 Constant *Op0 = C->getOperand(0);
12080 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12081 if (C->getOperand(i) != Op0)
12082 return false;
12083 return true;
12084 }
12085 Instruction *I = dyn_cast<Instruction>(V);
12086 if (!I) return false;
12087
12088 // Insert element gets simplified to the inserted element or is deleted if
12089 // this is constant idx extract element and its a constant idx insertelt.
12090 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12091 isa<ConstantInt>(I->getOperand(2)))
12092 return true;
12093 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12094 return true;
12095 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12096 if (BO->hasOneUse() &&
12097 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12098 CheapToScalarize(BO->getOperand(1), isConstant)))
12099 return true;
12100 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12101 if (CI->hasOneUse() &&
12102 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12103 CheapToScalarize(CI->getOperand(1), isConstant)))
12104 return true;
12105
12106 return false;
12107}
12108
12109/// Read and decode a shufflevector mask.
12110///
12111/// It turns undef elements into values that are larger than the number of
12112/// elements in the input.
12113static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12114 unsigned NElts = SVI->getType()->getNumElements();
12115 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12116 return std::vector<unsigned>(NElts, 0);
12117 if (isa<UndefValue>(SVI->getOperand(2)))
12118 return std::vector<unsigned>(NElts, 2*NElts);
12119
12120 std::vector<unsigned> Result;
12121 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012122 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12123 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012124 Result.push_back(NElts*2); // undef -> 8
12125 else
Gabor Greif17396002008-06-12 21:37:33 +000012126 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012127 return Result;
12128}
12129
12130/// FindScalarElement - Given a vector and an element number, see if the scalar
12131/// value is already around as a register, for example if it were inserted then
12132/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012133static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012134 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012135 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12136 const VectorType *PTy = cast<VectorType>(V->getType());
12137 unsigned Width = PTy->getNumElements();
12138 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012139 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012140
12141 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012142 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012143 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +000012144 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012145 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12146 return CP->getOperand(EltNo);
12147 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12148 // If this is an insert to a variable element, we don't know what it is.
12149 if (!isa<ConstantInt>(III->getOperand(2)))
12150 return 0;
12151 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12152
12153 // If this is an insert to the element we are looking for, return the
12154 // inserted value.
12155 if (EltNo == IIElt)
12156 return III->getOperand(1);
12157
12158 // Otherwise, the insertelement doesn't modify the value, recurse on its
12159 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000012160 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012161 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012162 unsigned LHSWidth =
12163 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012164 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012165 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012166 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012167 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012168 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012169 else
Owen Andersonb99ecca2009-07-30 23:03:37 +000012170 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012171 }
12172
12173 // Otherwise, we don't know.
12174 return 0;
12175}
12176
12177Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012178 // If vector val is undef, replace extract with scalar undef.
12179 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012180 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012181
12182 // If vector val is constant 0, replace extract with scalar 0.
12183 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +000012184 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012185
12186 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012187 // If vector val is constant with all elements the same, replace EI with
12188 // that element. When the elements are not identical, we cannot replace yet
12189 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012190 Constant *op0 = C->getOperand(0);
Chris Lattner1ba36b72009-09-08 03:44:51 +000012191 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012192 if (C->getOperand(i) != op0) {
12193 op0 = 0;
12194 break;
12195 }
12196 if (op0)
12197 return ReplaceInstUsesWith(EI, op0);
12198 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000012199
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012200 // If extracting a specified index from the vector, see if we can recursively
12201 // find a previously computed scalar that was inserted into the vector.
12202 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12203 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner1ba36b72009-09-08 03:44:51 +000012204 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012205
12206 // If this is extracting an invalid index, turn this into undef, to avoid
12207 // crashing the code below.
12208 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +000012209 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012210
12211 // This instruction only demands the single element from the input vector.
12212 // If the input vector has a single use, simplify it based on this use
12213 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000012214 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012215 APInt UndefElts(VectorWidth, 0);
12216 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012217 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012218 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012219 EI.setOperand(0, V);
12220 return &EI;
12221 }
12222 }
12223
Owen Anderson24be4c12009-07-03 00:17:18 +000012224 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012225 return ReplaceInstUsesWith(EI, Elt);
12226
12227 // If the this extractelement is directly using a bitcast from a vector of
12228 // the same number of elements, see if we can find the source element from
12229 // it. In this case, we will end up needing to bitcast the scalars.
12230 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12231 if (const VectorType *VT =
12232 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12233 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012234 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12235 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012236 return new BitCastInst(Elt, EI.getType());
12237 }
12238 }
12239
12240 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattnera97bc602009-09-08 18:48:01 +000012241 // Push extractelement into predecessor operation if legal and
12242 // profitable to do so
12243 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12244 if (I->hasOneUse() &&
12245 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12246 Value *newEI0 =
12247 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12248 EI.getName()+".lhs");
12249 Value *newEI1 =
12250 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12251 EI.getName()+".rhs");
12252 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012253 }
Chris Lattnera97bc602009-09-08 18:48:01 +000012254 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012255 // Extracting the inserted element?
12256 if (IE->getOperand(2) == EI.getOperand(1))
12257 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12258 // If the inserted and extracted elements are constants, they must not
12259 // be the same value, extract from the pre-inserted value instead.
Chris Lattner78628292009-08-30 19:47:22 +000012260 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +000012261 Worklist.AddValue(EI.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012262 EI.setOperand(0, IE->getOperand(0));
12263 return &EI;
12264 }
12265 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12266 // If this is extracting an element from a shufflevector, figure out where
12267 // it came from and extract from the appropriate input element instead.
12268 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12269 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12270 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012271 unsigned LHSWidth =
12272 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12273
12274 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012275 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012276 else if (SrcIdx < LHSWidth*2) {
12277 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012278 Src = SVI->getOperand(1);
12279 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012280 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012281 }
Eric Christopher1ba36872009-07-25 02:28:41 +000012282 return ExtractElementInst::Create(Src,
Chris Lattner78628292009-08-30 19:47:22 +000012283 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12284 false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012285 }
12286 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000012287 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012288 }
12289 return 0;
12290}
12291
12292/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12293/// elements from either LHS or RHS, return the shuffle mask and true.
12294/// Otherwise, return false.
12295static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000012296 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012297 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012298 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12299 "Invalid CollectSingleShuffleElements");
12300 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12301
12302 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012303 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012304 return true;
12305 } else if (V == LHS) {
12306 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012307 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012308 return true;
12309 } else if (V == RHS) {
12310 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012311 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012312 return true;
12313 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12314 // If this is an insert of an extract from some other vector, include it.
12315 Value *VecOp = IEI->getOperand(0);
12316 Value *ScalarOp = IEI->getOperand(1);
12317 Value *IdxOp = IEI->getOperand(2);
12318
12319 if (!isa<ConstantInt>(IdxOp))
12320 return false;
12321 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12322
12323 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12324 // Okay, we can handle this if the vector we are insertinting into is
12325 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012326 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012327 // If so, update the mask to reflect the inserted undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012328 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012329 return true;
12330 }
12331 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12332 if (isa<ConstantInt>(EI->getOperand(1)) &&
12333 EI->getOperand(0)->getType() == V->getType()) {
12334 unsigned ExtractedIdx =
12335 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12336
12337 // This must be extracting from either LHS or RHS.
12338 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12339 // Okay, we can handle this if the vector we are insertinting into is
12340 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012341 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012342 // If so, update the mask to reflect the inserted value.
12343 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012344 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012345 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012346 } else {
12347 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012348 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012349 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012350
12351 }
12352 return true;
12353 }
12354 }
12355 }
12356 }
12357 }
12358 // TODO: Handle shufflevector here!
12359
12360 return false;
12361}
12362
12363/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12364/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12365/// that computes V and the LHS value of the shuffle.
12366static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012367 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012368 assert(isa<VectorType>(V->getType()) &&
12369 (RHS == 0 || V->getType() == RHS->getType()) &&
12370 "Invalid shuffle!");
12371 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12372
12373 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012374 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012375 return V;
12376 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012377 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012378 return V;
12379 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12380 // If this is an insert of an extract from some other vector, include it.
12381 Value *VecOp = IEI->getOperand(0);
12382 Value *ScalarOp = IEI->getOperand(1);
12383 Value *IdxOp = IEI->getOperand(2);
12384
12385 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12386 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12387 EI->getOperand(0)->getType() == V->getType()) {
12388 unsigned ExtractedIdx =
12389 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12390 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12391
12392 // Either the extracted from or inserted into vector must be RHSVec,
12393 // otherwise we'd end up with a shuffle of three inputs.
12394 if (EI->getOperand(0) == RHS || RHS == 0) {
12395 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000012396 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012397 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012398 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012399 return V;
12400 }
12401
12402 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012403 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12404 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012405 // Everything but the extracted element is replaced with the RHS.
12406 for (unsigned i = 0; i != NumElts; ++i) {
12407 if (i != InsertedIdx)
Owen Anderson35b47072009-08-13 21:58:54 +000012408 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012409 }
12410 return V;
12411 }
12412
12413 // If this insertelement is a chain that comes from exactly these two
12414 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000012415 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12416 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012417 return EI->getOperand(0);
12418
12419 }
12420 }
12421 }
12422 // TODO: Handle shufflevector here!
12423
12424 // Otherwise, can't do anything fancy. Return an identity vector.
12425 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012426 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012427 return V;
12428}
12429
12430Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12431 Value *VecOp = IE.getOperand(0);
12432 Value *ScalarOp = IE.getOperand(1);
12433 Value *IdxOp = IE.getOperand(2);
12434
12435 // Inserting an undef or into an undefined place, remove this.
12436 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12437 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000012438
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012439 // If the inserted element was extracted from some other vector, and if the
12440 // indexes are constant, try to turn this into a shufflevector operation.
12441 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12442 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12443 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000012444 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012445 unsigned ExtractedIdx =
12446 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12447 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12448
12449 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12450 return ReplaceInstUsesWith(IE, VecOp);
12451
12452 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012453 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012454
12455 // If we are extracting a value from a vector, then inserting it right
12456 // back into the same place, just use the input vector.
12457 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12458 return ReplaceInstUsesWith(IE, VecOp);
12459
12460 // We could theoretically do this for ANY input. However, doing so could
12461 // turn chains of insertelement instructions into a chain of shufflevector
12462 // instructions, and right now we do not merge shufflevectors. As such,
12463 // only do this in a situation where it is clear that there is benefit.
12464 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12465 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12466 // the values of VecOp, except then one read from EIOp0.
12467 // Build a new shuffle mask.
12468 std::vector<Constant*> Mask;
12469 if (isa<UndefValue>(VecOp))
Owen Anderson35b47072009-08-13 21:58:54 +000012470 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012471 else {
12472 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson35b47072009-08-13 21:58:54 +000012473 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012474 NumVectorElts));
12475 }
Owen Anderson24be4c12009-07-03 00:17:18 +000012476 Mask[InsertedIdx] =
Owen Anderson35b47072009-08-13 21:58:54 +000012477 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012478 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Anderson2f422e02009-07-28 21:19:26 +000012479 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012480 }
12481
12482 // If this insertelement isn't used by some other insertelement, turn it
12483 // (and any insertelements it points to), into one big shuffle.
12484 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12485 std::vector<Constant*> Mask;
12486 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000012487 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Andersonb99ecca2009-07-30 23:03:37 +000012488 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012489 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000012490 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +000012491 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012492 }
12493 }
12494 }
12495
Eli Friedmanbefee262009-06-06 20:08:03 +000012496 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12497 APInt UndefElts(VWidth, 0);
12498 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12499 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12500 return &IE;
12501
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012502 return 0;
12503}
12504
12505
12506Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12507 Value *LHS = SVI.getOperand(0);
12508 Value *RHS = SVI.getOperand(1);
12509 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12510
12511 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012512
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012513 // Undefined shuffle mask -> undefined value.
12514 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012515 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012516
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012517 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012518
12519 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12520 return 0;
12521
Evan Cheng63295ab2009-02-03 10:05:09 +000012522 APInt UndefElts(VWidth, 0);
12523 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12524 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012525 LHS = SVI.getOperand(0);
12526 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012527 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012528 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012529
12530 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12531 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12532 if (LHS == RHS || isa<UndefValue>(LHS)) {
12533 if (isa<UndefValue>(LHS) && LHS == RHS) {
12534 // shuffle(undef,undef,mask) -> undef.
12535 return ReplaceInstUsesWith(SVI, LHS);
12536 }
12537
12538 // Remap any references to RHS to use LHS.
12539 std::vector<Constant*> Elts;
12540 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12541 if (Mask[i] >= 2*e)
Owen Anderson35b47072009-08-13 21:58:54 +000012542 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012543 else {
12544 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012545 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012546 Mask[i] = 2*e; // Turn into undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012547 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012548 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012549 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson35b47072009-08-13 21:58:54 +000012550 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012551 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012552 }
12553 }
12554 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +000012555 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +000012556 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012557 LHS = SVI.getOperand(0);
12558 RHS = SVI.getOperand(1);
12559 MadeChange = true;
12560 }
12561
12562 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12563 bool isLHSID = true, isRHSID = true;
12564
12565 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12566 if (Mask[i] >= e*2) continue; // Ignore undef values.
12567 // Is this an identity shuffle of the LHS value?
12568 isLHSID &= (Mask[i] == i);
12569
12570 // Is this an identity shuffle of the RHS value?
12571 isRHSID &= (Mask[i]-e == i);
12572 }
12573
12574 // Eliminate identity shuffles.
12575 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12576 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12577
12578 // If the LHS is a shufflevector itself, see if we can combine it with this
12579 // one without producing an unusual shuffle. Here we are really conservative:
12580 // we are absolutely afraid of producing a shuffle mask not in the input
12581 // program, because the code gen may not be smart enough to turn a merged
12582 // shuffle into two specific shuffles: it may produce worse code. As such,
12583 // we only merge two shuffles if the result is one of the two input shuffle
12584 // masks. In this case, merging the shuffles just removes one instruction,
12585 // which we know is safe. This is good for things like turning:
12586 // (splat(splat)) -> splat.
12587 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12588 if (isa<UndefValue>(RHS)) {
12589 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12590
12591 std::vector<unsigned> NewMask;
12592 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12593 if (Mask[i] >= 2*e)
12594 NewMask.push_back(2*e);
12595 else
12596 NewMask.push_back(LHSMask[Mask[i]]);
12597
12598 // If the result mask is equal to the src shuffle or this shuffle mask, do
12599 // the replacement.
12600 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000012601 unsigned LHSInNElts =
12602 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012603 std::vector<Constant*> Elts;
12604 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000012605 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson35b47072009-08-13 21:58:54 +000012606 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012607 } else {
Owen Anderson35b47072009-08-13 21:58:54 +000012608 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012609 }
12610 }
12611 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12612 LHSSVI->getOperand(1),
Owen Anderson2f422e02009-07-28 21:19:26 +000012613 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012614 }
12615 }
12616 }
12617
12618 return MadeChange ? &SVI : 0;
12619}
12620
12621
12622
12623
12624/// TryToSinkInstruction - Try to move the specified instruction from its
12625/// current block into the beginning of DestBlock, which can only happen if it's
12626/// safe to move the instruction past all of the instructions between it and the
12627/// end of its block.
12628static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12629 assert(I->hasOneUse() && "Invariants didn't hold!");
12630
12631 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000012632 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012633 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012634
12635 // Do not sink alloca instructions out of the entry block.
12636 if (isa<AllocaInst>(I) && I->getParent() ==
12637 &DestBlock->getParent()->getEntryBlock())
12638 return false;
12639
12640 // We can only sink load instructions if there is nothing between the load and
12641 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012642 if (I->mayReadFromMemory()) {
12643 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012644 Scan != E; ++Scan)
12645 if (Scan->mayWriteToMemory())
12646 return false;
12647 }
12648
Dan Gohman514277c2008-05-23 21:05:58 +000012649 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012650
Dale Johannesen24339f12009-03-03 01:09:07 +000012651 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012652 I->moveBefore(InsertPos);
12653 ++NumSunkInst;
12654 return true;
12655}
12656
12657
12658/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12659/// all reachable code to the worklist.
12660///
12661/// This has a couple of tricks to make the code faster and more powerful. In
12662/// particular, we constant fold and DCE instructions as we go, to avoid adding
12663/// them to the worklist (this significantly speeds up instcombine on code where
12664/// many instructions are dead or constant). Additionally, if we find a branch
12665/// whose condition is a known constant, we only visit the reachable successors.
12666///
12667static void AddReachableCodeToWorklist(BasicBlock *BB,
12668 SmallPtrSet<BasicBlock*, 64> &Visited,
12669 InstCombiner &IC,
12670 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000012671 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012672 Worklist.push_back(BB);
12673
12674 while (!Worklist.empty()) {
12675 BB = Worklist.back();
12676 Worklist.pop_back();
12677
12678 // We have now visited this block! If we've already been here, ignore it.
12679 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012680
12681 DbgInfoIntrinsic *DBI_Prev = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012682 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12683 Instruction *Inst = BBI++;
12684
12685 // DCE instruction if trivially dead.
12686 if (isInstructionTriviallyDead(Inst)) {
12687 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +000012688 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012689 Inst->eraseFromParent();
12690 continue;
12691 }
12692
12693 // ConstantProp instruction if trivially constant.
Owen Andersond4d90a02009-07-06 18:42:36 +000012694 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012695 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12696 << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012697 Inst->replaceAllUsesWith(C);
12698 ++NumConstProp;
12699 Inst->eraseFromParent();
12700 continue;
12701 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000012702
Devang Patel794140c2008-11-19 18:56:50 +000012703 // If there are two consecutive llvm.dbg.stoppoint calls then
12704 // it is likely that the optimizer deleted code in between these
12705 // two intrinsics.
12706 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12707 if (DBI_Next) {
12708 if (DBI_Prev
12709 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12710 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner3183fb62009-08-30 06:13:40 +000012711 IC.Worklist.Remove(DBI_Prev);
Devang Patel794140c2008-11-19 18:56:50 +000012712 DBI_Prev->eraseFromParent();
12713 }
12714 DBI_Prev = DBI_Next;
Zhou Sheng77e03b92009-02-23 10:14:11 +000012715 } else {
12716 DBI_Prev = 0;
Devang Patel794140c2008-11-19 18:56:50 +000012717 }
12718
Chris Lattner3183fb62009-08-30 06:13:40 +000012719 IC.Worklist.Add(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012720 }
12721
12722 // Recursively visit successors. If this is a branch or switch on a
12723 // constant, only visit the reachable successor.
12724 TerminatorInst *TI = BB->getTerminator();
12725 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12726 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12727 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012728 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012729 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012730 continue;
12731 }
12732 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12733 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12734 // See if this is an explicit destination.
12735 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12736 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012737 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012738 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012739 continue;
12740 }
12741
12742 // Otherwise it is the default destination.
12743 Worklist.push_back(SI->getSuccessor(0));
12744 continue;
12745 }
12746 }
12747
12748 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12749 Worklist.push_back(TI->getSuccessor(i));
12750 }
12751}
12752
12753bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner21d79e22009-08-31 06:57:37 +000012754 MadeIRChange = false;
Dan Gohmana80e2712009-07-21 23:21:54 +000012755 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012756
Daniel Dunbar005975c2009-07-25 00:23:56 +000012757 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12758 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012759
12760 {
12761 // Do a depth-first traversal of the function, populate the worklist with
12762 // the reachable instructions. Ignore blocks that are not reachable. Keep
12763 // track of which blocks we visit.
12764 SmallPtrSet<BasicBlock*, 64> Visited;
12765 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12766
12767 // Do a quick scan over the function. If we find any blocks that are
12768 // unreachable, remove any instructions inside of them. This prevents
12769 // the instcombine code from having to deal with some bad special cases.
12770 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12771 if (!Visited.count(BB)) {
12772 Instruction *Term = BB->getTerminator();
12773 while (Term != BB->begin()) { // Remove instrs bottom-up
12774 BasicBlock::iterator I = Term; --I;
12775
Chris Lattner8a6411c2009-08-23 04:37:46 +000012776 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +000012777 // A debug intrinsic shouldn't force another iteration if we weren't
12778 // going to do one without it.
12779 if (!isa<DbgInfoIntrinsic>(I)) {
12780 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000012781 MadeIRChange = true;
Dale Johannesendf356c62009-03-10 21:19:49 +000012782 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012783 if (!I->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +000012784 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012785 I->eraseFromParent();
12786 }
12787 }
12788 }
12789
Chris Lattner5119c702009-08-30 05:55:36 +000012790 while (!Worklist.isEmpty()) {
12791 Instruction *I = Worklist.RemoveOne();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012792 if (I == 0) continue; // skip null values.
12793
12794 // Check to see if we can DCE the instruction.
12795 if (isInstructionTriviallyDead(I)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012796 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner3183fb62009-08-30 06:13:40 +000012797 EraseInstFromFunction(*I);
12798 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000012799 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012800 continue;
12801 }
12802
12803 // Instruction isn't dead, see if we can constant propagate it.
Owen Andersond4d90a02009-07-06 18:42:36 +000012804 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012805 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012806
12807 // Add operands to the worklist.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012808 ReplaceInstUsesWith(*I, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012809 ++NumConstProp;
Chris Lattner3183fb62009-08-30 06:13:40 +000012810 EraseInstFromFunction(*I);
Chris Lattner21d79e22009-08-31 06:57:37 +000012811 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012812 continue;
12813 }
12814
Eli Friedman5c619182009-07-15 22:13:34 +000012815 if (TD) {
Nick Lewyckyadb67922008-05-25 20:56:15 +000012816 // See if we can constant fold its operands.
Chris Lattnerf6d58862009-01-31 07:04:22 +000012817 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12818 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Andersond4d90a02009-07-06 18:42:36 +000012819 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12820 F.getContext(), TD))
Chris Lattnerf6d58862009-01-31 07:04:22 +000012821 if (NewC != CE) {
Dan Gohman3af2d412009-10-05 16:31:55 +000012822 *i = NewC;
Chris Lattner21d79e22009-08-31 06:57:37 +000012823 MadeIRChange = true;
Chris Lattnerf6d58862009-01-31 07:04:22 +000012824 }
Nick Lewyckyadb67922008-05-25 20:56:15 +000012825 }
12826
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012827 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000012828 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012829 BasicBlock *BB = I->getParent();
12830 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12831 if (UserParent != BB) {
12832 bool UserIsSuccessor = false;
12833 // See if the user is one of our successors.
12834 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12835 if (*SI == UserParent) {
12836 UserIsSuccessor = true;
12837 break;
12838 }
12839
12840 // If the user is one of our immediate successors, and if that successor
12841 // only has us as a predecessors (we'd have to split the critical edge
12842 // otherwise), we can keep going.
12843 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12844 next(pred_begin(UserParent)) == pred_end(UserParent))
12845 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattner21d79e22009-08-31 06:57:37 +000012846 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012847 }
12848 }
12849
Chris Lattnerc7694852009-08-30 07:44:24 +000012850 // Now that we have an instruction, try combining it to simplify it.
12851 Builder->SetInsertPoint(I->getParent(), I);
12852
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012853#ifndef NDEBUG
12854 std::string OrigI;
12855#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +000012856 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000012857 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12858
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012859 if (Instruction *Result = visit(*I)) {
12860 ++NumCombined;
12861 // Should we replace the old instruction with a new one?
12862 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012863 DEBUG(errs() << "IC: Old = " << *I << '\n'
12864 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012865
12866 // Everything uses the new instruction now.
12867 I->replaceAllUsesWith(Result);
12868
12869 // Push the new instruction and any users onto the worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +000012870 Worklist.Add(Result);
Chris Lattner4796b622009-08-30 06:22:51 +000012871 Worklist.AddUsersToWorkList(*Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012872
12873 // Move the name to the new instruction first.
12874 Result->takeName(I);
12875
12876 // Insert the new instruction into the basic block...
12877 BasicBlock *InstParent = I->getParent();
12878 BasicBlock::iterator InsertPos = I;
12879
12880 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12881 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12882 ++InsertPos;
12883
12884 InstParent->getInstList().insert(InsertPos, Result);
12885
Chris Lattner3183fb62009-08-30 06:13:40 +000012886 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012887 } else {
12888#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +000012889 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12890 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012891#endif
12892
12893 // If the instruction was modified, it's possible that it is now dead.
12894 // if so, remove it.
12895 if (isInstructionTriviallyDead(I)) {
Chris Lattner3183fb62009-08-30 06:13:40 +000012896 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012897 } else {
Chris Lattner3183fb62009-08-30 06:13:40 +000012898 Worklist.Add(I);
Chris Lattner4796b622009-08-30 06:22:51 +000012899 Worklist.AddUsersToWorkList(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012900 }
12901 }
Chris Lattner21d79e22009-08-31 06:57:37 +000012902 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012903 }
12904 }
12905
Chris Lattner5119c702009-08-30 05:55:36 +000012906 Worklist.Zap();
Chris Lattner21d79e22009-08-31 06:57:37 +000012907 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012908}
12909
12910
12911bool InstCombiner::runOnFunction(Function &F) {
12912 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000012913 Context = &F.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012914
Chris Lattnerc7694852009-08-30 07:44:24 +000012915
12916 /// Builder - This is an IRBuilder that automatically inserts new
12917 /// instructions into the worklist when they are created.
12918 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12919 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12920 InstCombineIRInserter(Worklist));
12921 Builder = &TheBuilder;
12922
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012923 bool EverMadeChange = false;
12924
12925 // Iterate while there is work to do.
12926 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000012927 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012928 EverMadeChange = true;
Chris Lattnerc7694852009-08-30 07:44:24 +000012929
12930 Builder = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012931 return EverMadeChange;
12932}
12933
12934FunctionPass *llvm::createInstructionCombiningPass() {
12935 return new InstCombiner();
12936}