blob: 6826e1327350af033a9e185e1d048d2d9ce9d2b1 [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) {
Victor Hernandez48c3c542009-09-18 22:35:49 +000093 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner5119c702009-08-30 05:55:36 +000094 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
95 Worklist.push_back(I);
96 }
97
Chris Lattnerc5ad98f2009-08-30 06:27:41 +000098 void AddValue(Value *V) {
99 if (Instruction *I = dyn_cast<Instruction>(V))
100 Add(I);
101 }
102
Chris Lattner3183fb62009-08-30 06:13:40 +0000103 // Remove - remove I from the worklist if it exists.
Chris Lattner5119c702009-08-30 05:55:36 +0000104 void Remove(Instruction *I) {
105 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
106 if (It == WorklistMap.end()) return; // Not in worklist.
107
108 // Don't bother moving everything down, just null out the slot.
109 Worklist[It->second] = 0;
110
111 WorklistMap.erase(It);
112 }
113
114 Instruction *RemoveOne() {
115 Instruction *I = Worklist.back();
116 Worklist.pop_back();
117 WorklistMap.erase(I);
118 return I;
119 }
120
Chris Lattner4796b622009-08-30 06:22:51 +0000121 /// AddUsersToWorkList - When an instruction is simplified, add all users of
122 /// the instruction to the work lists because they might get more simplified
123 /// now.
124 ///
125 void AddUsersToWorkList(Instruction &I) {
126 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
127 UI != UE; ++UI)
128 Add(cast<Instruction>(*UI));
129 }
130
Chris Lattner5119c702009-08-30 05:55:36 +0000131
132 /// Zap - check that the worklist is empty and nuke the backing store for
133 /// the map if it is large.
134 void Zap() {
135 assert(WorklistMap.empty() && "Worklist empty, but map not?");
136
137 // Do an explicit clear, this shrinks the map if needed.
138 WorklistMap.clear();
139 }
140 };
141} // end anonymous namespace.
142
143
144namespace {
Chris Lattnerc7694852009-08-30 07:44:24 +0000145 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
146 /// just like the normal insertion helper, but also adds any new instructions
147 /// to the instcombine worklist.
148 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
149 InstCombineWorklist &Worklist;
150 public:
151 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
152
153 void InsertHelper(Instruction *I, const Twine &Name,
154 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
155 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
156 Worklist.Add(I);
157 }
158 };
159} // end anonymous namespace
160
161
162namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000163 class InstCombiner : public FunctionPass,
164 public InstVisitor<InstCombiner, Instruction*> {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000165 TargetData *TD;
166 bool MustPreserveLCSSA;
Chris Lattner21d79e22009-08-31 06:57:37 +0000167 bool MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000168 public:
Chris Lattner36ec3b42009-08-30 17:53:59 +0000169 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner3183fb62009-08-30 06:13:40 +0000170 InstCombineWorklist Worklist;
171
Chris Lattnerc7694852009-08-30 07:44:24 +0000172 /// Builder - This is an IRBuilder that automatically inserts new
173 /// instructions into the worklist when they are created.
Chris Lattnerad7516a2009-08-30 18:50:58 +0000174 typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
175 BuilderTy *Builder;
Chris Lattnerc7694852009-08-30 07:44:24 +0000176
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 static char ID; // Pass identification, replacement for typeid
Chris Lattnerc7694852009-08-30 07:44:24 +0000178 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179
Owen Anderson175b6542009-07-22 00:24:57 +0000180 LLVMContext *Context;
181 LLVMContext *getContext() const { return Context; }
Owen Anderson24be4c12009-07-03 00:17:18 +0000182
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183 public:
184 virtual bool runOnFunction(Function &F);
185
186 bool DoOneIteration(Function &F, unsigned ItNum);
187
188 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189 AU.addPreservedID(LCSSAID);
190 AU.setPreservesCFG();
191 }
192
Dan Gohmana80e2712009-07-21 23:21:54 +0000193 TargetData *getTargetData() const { return TD; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194
195 // Visitation implementation - Implement instruction combining for different
196 // instruction types. The semantics are as follows:
197 // Return Value:
198 // null - No change was made
199 // I - Change was made, I is still valid, I may be dead though
200 // otherwise - Change was made, replace I with returned instruction
201 //
202 Instruction *visitAdd(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000203 Instruction *visitFAdd(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000205 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000207 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208 Instruction *visitURem(BinaryOperator &I);
209 Instruction *visitSRem(BinaryOperator &I);
210 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000211 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 Instruction *commonRemTransforms(BinaryOperator &I);
213 Instruction *commonIRemTransforms(BinaryOperator &I);
214 Instruction *commonDivTransforms(BinaryOperator &I);
215 Instruction *commonIDivTransforms(BinaryOperator &I);
216 Instruction *visitUDiv(BinaryOperator &I);
217 Instruction *visitSDiv(BinaryOperator &I);
218 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000219 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +0000220 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000222 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner57e66fa2009-07-23 05:46:22 +0000223 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000224 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000225 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000226 Instruction *visitOr (BinaryOperator &I);
227 Instruction *visitXor(BinaryOperator &I);
228 Instruction *visitShl(BinaryOperator &I);
229 Instruction *visitAShr(BinaryOperator &I);
230 Instruction *visitLShr(BinaryOperator &I);
231 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000232 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
233 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 Instruction *visitFCmpInst(FCmpInst &I);
235 Instruction *visitICmpInst(ICmpInst &I);
236 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
237 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
238 Instruction *LHS,
239 ConstantInt *RHS);
240 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
241 ConstantInt *DivRHS);
242
Dan Gohman17f46f72009-07-28 01:40:03 +0000243 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244 ICmpInst::Predicate Cond, Instruction &I);
245 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
246 BinaryOperator &I);
247 Instruction *commonCastTransforms(CastInst &CI);
248 Instruction *commonIntCastTransforms(CastInst &CI);
249 Instruction *commonPointerCastTransforms(CastInst &CI);
250 Instruction *visitTrunc(TruncInst &CI);
251 Instruction *visitZExt(ZExtInst &CI);
252 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000253 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000255 Instruction *visitFPToUI(FPToUIInst &FI);
256 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 Instruction *visitUIToFP(CastInst &CI);
258 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000259 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000260 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000261 Instruction *visitBitCast(BitCastInst &CI);
262 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
263 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000264 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman58c09632008-09-16 18:46:06 +0000265 Instruction *visitSelectInst(SelectInst &SI);
266 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267 Instruction *visitCallInst(CallInst &CI);
268 Instruction *visitInvokeInst(InvokeInst &II);
269 Instruction *visitPHINode(PHINode &PN);
270 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
271 Instruction *visitAllocationInst(AllocationInst &AI);
272 Instruction *visitFreeInst(FreeInst &FI);
273 Instruction *visitLoadInst(LoadInst &LI);
274 Instruction *visitStoreInst(StoreInst &SI);
275 Instruction *visitBranchInst(BranchInst &BI);
276 Instruction *visitSwitchInst(SwitchInst &SI);
277 Instruction *visitInsertElementInst(InsertElementInst &IE);
278 Instruction *visitExtractElementInst(ExtractElementInst &EI);
279 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000280 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281
282 // visitInstruction - Specify what to return for unhandled instructions...
283 Instruction *visitInstruction(Instruction &I) { return 0; }
284
285 private:
286 Instruction *visitCallSite(CallSite CS);
287 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000288 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000289 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
290 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000291 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000292 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
293
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294
295 public:
296 // InsertNewInstBefore - insert an instruction New before instruction Old
297 // in the program. Add the new instruction to the worklist.
298 //
299 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
300 assert(New && New->getParent() == 0 &&
301 "New instruction already inserted into a basic block!");
302 BasicBlock *BB = Old.getParent();
303 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner3183fb62009-08-30 06:13:40 +0000304 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000305 return New;
306 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000307
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 // ReplaceInstUsesWith - This method is to be used when an instruction is
309 // found to be dead, replacable with another preexisting expression. Here
310 // we add all uses of I to the worklist, replace all uses of I with the new
311 // value, then return I, so that the inst combiner will know that I was
312 // modified.
313 //
314 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner4796b622009-08-30 06:22:51 +0000315 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +0000316
317 // If we are replacing the instruction with itself, this must be in a
318 // segment of unreachable code, so just clobber the instruction.
319 if (&I == V)
320 V = UndefValue::get(I.getType());
321
322 I.replaceAllUsesWith(V);
323 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324 }
325
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326 // EraseInstFromFunction - When dealing with an instruction that has side
327 // effects or produces a void value, we can't rely on DCE to delete the
328 // instruction. Instead, visit methods should return the value returned by
329 // this function.
330 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez48c3c542009-09-18 22:35:49 +0000331 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner26b7f942009-08-31 05:17:58 +0000332
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner3183fb62009-08-30 06:13:40 +0000334 // Make sure that we reprocess all operands now that we reduced their
335 // use counts.
Chris Lattnerc5ad98f2009-08-30 06:27:41 +0000336 if (I.getNumOperands() < 8) {
337 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
338 if (Instruction *Op = dyn_cast<Instruction>(*i))
339 Worklist.Add(Op);
340 }
Chris Lattner3183fb62009-08-30 06:13:40 +0000341 Worklist.Remove(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 I.eraseFromParent();
Chris Lattner21d79e22009-08-31 06:57:37 +0000343 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 return 0; // Don't do anything with FI
345 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000346
347 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
348 APInt &KnownOne, unsigned Depth = 0) const {
349 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
350 }
351
352 bool MaskedValueIsZero(Value *V, const APInt &Mask,
353 unsigned Depth = 0) const {
354 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
355 }
356 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
357 return llvm::ComputeNumSignBits(Op, TD, Depth);
358 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359
360 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361
362 /// SimplifyCommutative - This performs a few simplifications for
363 /// commutative operators.
364 bool SimplifyCommutative(BinaryOperator &I);
365
366 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
367 /// most-complex to least-complex order.
368 bool SimplifyCompare(CmpInst &I);
369
Chris Lattner676c78e2009-01-31 08:15:18 +0000370 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
371 /// based on the demanded bits.
372 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
373 APInt& KnownZero, APInt& KnownOne,
374 unsigned Depth);
375 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000376 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000377 unsigned Depth=0);
378
379 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
380 /// SimplifyDemandedBits knows about. See if the instruction has any
381 /// properties that allow us to simplify its operands.
382 bool SimplifyDemandedInstructionBits(Instruction &Inst);
383
Evan Cheng63295ab2009-02-03 10:05:09 +0000384 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
385 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386
Chris Lattnerf7843b72009-09-27 19:57:57 +0000387 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
388 // which has a PHI node as operand #0, see if we can fold the instruction
389 // into the PHI (which is only possible if all operands to the PHI are
390 // constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +0000391 //
392 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
393 // that would normally be unprofitable because they strongly encourage jump
394 // threading.
395 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396
397 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
398 // operator and they all are only used by the PHI, PHI together their
399 // inputs, and do the operation once, to the result of the PHI.
400 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
401 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000402 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
403
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404
405 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
406 ConstantInt *AndRHS, BinaryOperator &TheAnd);
407
408 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
409 bool isSub, Instruction &I);
410 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
411 bool isSigned, bool Inside, Instruction &IB);
412 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
413 Instruction *MatchBSwap(BinaryOperator &I);
414 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000415 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000416 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000417
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418
419 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000420
Dan Gohman8fd520a2009-06-15 22:12:54 +0000421 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000422 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000423 unsigned GetOrEnforceKnownAlignment(Value *V,
424 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000425
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426 };
Chris Lattner5119c702009-08-30 05:55:36 +0000427} // end anonymous namespace
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000428
Dan Gohman089efff2008-05-13 00:00:25 +0000429char InstCombiner::ID = 0;
430static RegisterPass<InstCombiner>
431X("instcombine", "Combine redundant instructions");
432
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433// getComplexity: Assign a complexity or rank value to LLVM Values...
434// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman5d138f92009-08-29 23:39:38 +0000435static unsigned getComplexity(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000436 if (isa<Instruction>(V)) {
Owen Anderson76f49252009-07-13 22:18:28 +0000437 if (BinaryOperator::isNeg(V) ||
438 BinaryOperator::isFNeg(V) ||
Dan Gohman7ce405e2009-06-04 22:49:04 +0000439 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000440 return 3;
441 return 4;
442 }
443 if (isa<Argument>(V)) return 3;
444 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
445}
446
447// isOnlyUse - Return true if this instruction will be deleted if we stop using
448// it.
449static bool isOnlyUse(Value *V) {
450 return V->hasOneUse() || isa<Constant>(V);
451}
452
453// getPromotedType - Return the specified type promoted as it would be to pass
454// though a va_arg area...
455static const Type *getPromotedType(const Type *Ty) {
456 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
457 if (ITy->getBitWidth() < 32)
Owen Anderson35b47072009-08-13 21:58:54 +0000458 return Type::getInt32Ty(Ty->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000459 }
460 return Ty;
461}
462
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000463/// getBitCastOperand - If the specified operand is a CastInst, a constant
464/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
465/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000466static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000467 if (Operator *O = dyn_cast<Operator>(V)) {
468 if (O->getOpcode() == Instruction::BitCast)
469 return O->getOperand(0);
470 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
471 if (GEP->hasAllZeroIndices())
472 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000473 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474 return 0;
475}
476
477/// This function is a wrapper around CastInst::isEliminableCastPair. It
478/// simply extracts arguments and returns what that function returns.
479static Instruction::CastOps
480isEliminableCastPair(
481 const CastInst *CI, ///< The first cast instruction
482 unsigned opcode, ///< The opcode of the second cast instruction
483 const Type *DstTy, ///< The target type for the second cast instruction
484 TargetData *TD ///< The target data for pointer size
485) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000486
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000487 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
488 const Type *MidTy = CI->getType(); // B from above
489
490 // Get the opcodes of the two Cast instructions
491 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
492 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
493
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000494 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmana80e2712009-07-21 23:21:54 +0000495 DstTy,
Owen Anderson35b47072009-08-13 21:58:54 +0000496 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000497
498 // We don't want to form an inttoptr or ptrtoint that converts to an integer
499 // type that differs from the pointer size.
Owen Anderson35b47072009-08-13 21:58:54 +0000500 if ((Res == Instruction::IntToPtr &&
Dan Gohman033445f2009-08-19 23:38:22 +0000501 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson35b47072009-08-13 21:58:54 +0000502 (Res == Instruction::PtrToInt &&
Dan Gohman033445f2009-08-19 23:38:22 +0000503 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000504 Res = 0;
505
506 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000507}
508
509/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
510/// in any code being generated. It does not require codegen if V is simple
511/// enough or if the cast can be folded into other casts.
512static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
513 const Type *Ty, TargetData *TD) {
514 if (V->getType() == Ty || isa<Constant>(V)) return false;
515
516 // If this is another cast that can be eliminated, it isn't codegen either.
517 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000518 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519 return false;
520 return true;
521}
522
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000523// SimplifyCommutative - This performs a few simplifications for commutative
524// operators:
525//
526// 1. Order operands such that they are listed from right (least complex) to
527// left (most complex). This puts constants before unary operators before
528// binary operators.
529//
530// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
531// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
532//
533bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
534 bool Changed = false;
Dan Gohman5d138f92009-08-29 23:39:38 +0000535 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 Changed = !I.swapOperands();
537
538 if (!I.isAssociative()) return Changed;
539 Instruction::BinaryOps Opcode = I.getOpcode();
540 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
541 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
542 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000543 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000544 cast<Constant>(I.getOperand(1)),
545 cast<Constant>(Op->getOperand(1)));
546 I.setOperand(0, Op->getOperand(0));
547 I.setOperand(1, Folded);
548 return true;
549 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
550 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
551 isOnlyUse(Op) && isOnlyUse(Op1)) {
552 Constant *C1 = cast<Constant>(Op->getOperand(1));
553 Constant *C2 = cast<Constant>(Op1->getOperand(1));
554
555 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000556 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000557 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000558 Op1->getOperand(0),
559 Op1->getName(), &I);
Chris Lattner3183fb62009-08-30 06:13:40 +0000560 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000561 I.setOperand(0, New);
562 I.setOperand(1, Folded);
563 return true;
564 }
565 }
566 return Changed;
567}
568
569/// SimplifyCompare - For a CmpInst this function just orders the operands
570/// so that theyare listed from right (least complex) to left (most complex).
571/// This puts constants before unary operators before binary operators.
572bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman5d138f92009-08-29 23:39:38 +0000573 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000574 return false;
575 I.swapOperands();
576 // Compare instructions are not associative so there's nothing else we can do.
577 return true;
578}
579
580// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
581// if the LHS is a constant zero (which is the 'negate' form).
582//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000583static inline Value *dyn_castNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000584 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 return BinaryOperator::getNegArgument(V);
586
587 // Constants can be considered to be negated values if they can be folded.
588 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000589 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000590
591 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
592 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000593 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000594
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000595 return 0;
596}
597
Dan Gohman7ce405e2009-06-04 22:49:04 +0000598// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
599// instruction if the LHS is a constant negative zero (which is the 'negate'
600// form).
601//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000602static inline Value *dyn_castFNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000603 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000604 return BinaryOperator::getFNegArgument(V);
605
606 // Constants can be considered to be negated values if they can be folded.
607 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000608 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000609
610 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
611 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000612 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000613
614 return 0;
615}
616
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000617static inline Value *dyn_castNotVal(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618 if (BinaryOperator::isNot(V))
619 return BinaryOperator::getNotArgument(V);
620
621 // Constants can be considered to be not'ed values...
622 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000623 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624 return 0;
625}
626
627// dyn_castFoldableMul - If this value is a multiply that can be folded into
628// other computations (because it has a constant operand), return the
629// non-constant operand of the multiply, and set CST to point to the multiplier.
630// Otherwise, return null.
631//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000632static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000633 if (V->hasOneUse() && V->getType()->isInteger())
634 if (Instruction *I = dyn_cast<Instruction>(V)) {
635 if (I->getOpcode() == Instruction::Mul)
636 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
637 return I->getOperand(0);
638 if (I->getOpcode() == Instruction::Shl)
639 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
640 // The multiplier is really 1 << CST.
641 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
642 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000643 CST = ConstantInt::get(V->getType()->getContext(),
644 APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000645 return I->getOperand(0);
646 }
647 }
648 return 0;
649}
650
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651/// AddOne - Add one to a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000652static Constant *AddOne(Constant *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000653 return ConstantExpr::getAdd(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000654 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655}
656/// SubOne - Subtract one from a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000657static Constant *SubOne(ConstantInt *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000658 return ConstantExpr::getSub(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000659 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000661/// MultiplyOverflows - True if the multiply can not be expressed in an int
662/// this size.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000663static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000664 uint32_t W = C1->getBitWidth();
665 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
666 if (sign) {
667 LHSExt.sext(W * 2);
668 RHSExt.sext(W * 2);
669 } else {
670 LHSExt.zext(W * 2);
671 RHSExt.zext(W * 2);
672 }
673
674 APInt MulExt = LHSExt * RHSExt;
675
676 if (sign) {
677 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
678 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
679 return MulExt.slt(Min) || MulExt.sgt(Max);
680 } else
681 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
682}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000683
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684
685/// ShrinkDemandedConstant - Check to see if the specified operand of the
686/// specified instruction is a constant integer. If so, check to see if there
687/// are any bits set in the constant that are not demanded. If so, shrink the
688/// constant and return true.
689static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000690 APInt Demanded) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691 assert(I && "No instruction?");
692 assert(OpNo < I->getNumOperands() && "Operand index too large");
693
694 // If the operand is not a constant integer, nothing to do.
695 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
696 if (!OpC) return false;
697
698 // If there are no bits set that aren't demanded, nothing to do.
699 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
700 if ((~Demanded & OpC->getValue()) == 0)
701 return false;
702
703 // This instruction is producing bits that are not demanded. Shrink the RHS.
704 Demanded &= OpC->getValue();
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000705 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706 return true;
707}
708
709// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
710// set of known zero and one bits, compute the maximum and minimum values that
711// could have the specified known zero and known one bits, returning them in
712// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000713static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714 const APInt& KnownOne,
715 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000716 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
717 KnownZero.getBitWidth() == Min.getBitWidth() &&
718 KnownZero.getBitWidth() == Max.getBitWidth() &&
719 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720 APInt UnknownBits = ~(KnownZero|KnownOne);
721
722 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
723 // bit if it is unknown.
724 Min = KnownOne;
725 Max = KnownOne|UnknownBits;
726
Dan Gohman7934d592009-04-25 17:12:48 +0000727 if (UnknownBits.isNegative()) { // Sign bit is unknown
728 Min.set(Min.getBitWidth()-1);
729 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000730 }
731}
732
733// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
734// a set of known zero and one bits, compute the maximum and minimum values that
735// could have the specified known zero and known one bits, returning them in
736// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000737static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000738 const APInt &KnownOne,
739 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000740 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
741 KnownZero.getBitWidth() == Min.getBitWidth() &&
742 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000743 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
744 APInt UnknownBits = ~(KnownZero|KnownOne);
745
746 // The minimum value is when the unknown bits are all zeros.
747 Min = KnownOne;
748 // The maximum value is when the unknown bits are all ones.
749 Max = KnownOne|UnknownBits;
750}
751
Chris Lattner676c78e2009-01-31 08:15:18 +0000752/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
753/// SimplifyDemandedBits knows about. See if the instruction has any
754/// properties that allow us to simplify its operands.
755bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000756 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000757 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
758 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
759
760 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
761 KnownZero, KnownOne, 0);
762 if (V == 0) return false;
763 if (V == &Inst) return true;
764 ReplaceInstUsesWith(Inst, V);
765 return true;
766}
767
768/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
769/// specified instruction operand if possible, updating it in place. It returns
770/// true if it made any change and false otherwise.
771bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
772 APInt &KnownZero, APInt &KnownOne,
773 unsigned Depth) {
774 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
775 KnownZero, KnownOne, Depth);
776 if (NewVal == 0) return false;
777 U.set(NewVal);
778 return true;
779}
780
781
782/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
783/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000784/// that only the bits set in DemandedMask of the result of V are ever used
785/// downstream. Consequently, depending on the mask and V, it may be possible
786/// to replace V with a constant or one of its operands. In such cases, this
787/// function does the replacement and returns true. In all other cases, it
788/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000789/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000790/// to be zero in the expression. These are provided to potentially allow the
791/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
792/// the expression. KnownOne and KnownZero always follow the invariant that
793/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
794/// the bits in KnownOne and KnownZero may only be accurate for those bits set
795/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
796/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000797///
798/// This returns null if it did not change anything and it permits no
799/// simplification. This returns V itself if it did some simplification of V's
800/// operands based on the information about what bits are demanded. This returns
801/// some other non-null value if it found out that V is equal to another value
802/// in the context where the specified bits are demanded, but not for all users.
803Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
804 APInt &KnownZero, APInt &KnownOne,
805 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000806 assert(V != 0 && "Null pointer of Value???");
807 assert(Depth <= 6 && "Limit Search Depth");
808 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000809 const Type *VTy = V->getType();
810 assert((TD || !isa<PointerType>(VTy)) &&
811 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000812 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
813 (!VTy->isIntOrIntVector() ||
814 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000815 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000816 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000817 "Value *V, DemandedMask, KnownZero and KnownOne "
818 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
820 // We know all of the bits for a constant!
821 KnownOne = CI->getValue() & DemandedMask;
822 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000823 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000824 }
Dan Gohman7934d592009-04-25 17:12:48 +0000825 if (isa<ConstantPointerNull>(V)) {
826 // We know all of the bits for a constant!
827 KnownOne.clear();
828 KnownZero = DemandedMask;
829 return 0;
830 }
831
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000832 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000833 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000834 if (DemandedMask == 0) { // Not demanding any bits from V.
835 if (isa<UndefValue>(V))
836 return 0;
Owen Andersonb99ecca2009-07-30 23:03:37 +0000837 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000838 }
839
Chris Lattner08817332009-01-31 08:24:16 +0000840 if (Depth == 6) // Limit search depth.
841 return 0;
842
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000843 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
844 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
845
Dan Gohman7934d592009-04-25 17:12:48 +0000846 Instruction *I = dyn_cast<Instruction>(V);
847 if (!I) {
848 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
849 return 0; // Only analyze instructions.
850 }
851
Chris Lattner08817332009-01-31 08:24:16 +0000852 // If there are multiple uses of this value and we aren't at the root, then
853 // we can't do any simplifications of the operands, because DemandedMask
854 // only reflects the bits demanded by *one* of the users.
855 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000856 // Despite the fact that we can't simplify this instruction in all User's
857 // context, we can at least compute the knownzero/knownone bits, and we can
858 // do simplifications that apply to *just* the one user if we know that
859 // this instruction has a simpler value in that context.
860 if (I->getOpcode() == Instruction::And) {
861 // If either the LHS or the RHS are Zero, the result is zero.
862 ComputeMaskedBits(I->getOperand(1), DemandedMask,
863 RHSKnownZero, RHSKnownOne, Depth+1);
864 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
865 LHSKnownZero, LHSKnownOne, Depth+1);
866
867 // If all of the demanded bits are known 1 on one side, return the other.
868 // These bits cannot contribute to the result of the 'and' in this
869 // context.
870 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
871 (DemandedMask & ~LHSKnownZero))
872 return I->getOperand(0);
873 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
874 (DemandedMask & ~RHSKnownZero))
875 return I->getOperand(1);
876
877 // If all of the demanded bits in the inputs are known zeros, return zero.
878 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000879 return Constant::getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000880
881 } else if (I->getOpcode() == Instruction::Or) {
882 // We can simplify (X|Y) -> X or Y in the user's context if we know that
883 // only bits from X or Y are demanded.
884
885 // If either the LHS or the RHS are One, the result is One.
886 ComputeMaskedBits(I->getOperand(1), DemandedMask,
887 RHSKnownZero, RHSKnownOne, Depth+1);
888 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
889 LHSKnownZero, LHSKnownOne, Depth+1);
890
891 // If all of the demanded bits are known zero on one side, return the
892 // other. These bits cannot contribute to the result of the 'or' in this
893 // context.
894 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
895 (DemandedMask & ~LHSKnownOne))
896 return I->getOperand(0);
897 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
898 (DemandedMask & ~RHSKnownOne))
899 return I->getOperand(1);
900
901 // If all of the potentially set bits on one side are known to be set on
902 // the other side, just use the 'other' side.
903 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
904 (DemandedMask & (~RHSKnownZero)))
905 return I->getOperand(0);
906 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
907 (DemandedMask & (~LHSKnownZero)))
908 return I->getOperand(1);
909 }
910
Chris Lattner08817332009-01-31 08:24:16 +0000911 // Compute the KnownZero/KnownOne bits to simplify things downstream.
912 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
913 return 0;
914 }
915
916 // If this is the root being simplified, allow it to have multiple uses,
917 // just set the DemandedMask to all bits so that we can try to simplify the
918 // operands. This allows visitTruncInst (for example) to simplify the
919 // operand of a trunc without duplicating all the logic below.
920 if (Depth == 0 && !V->hasOneUse())
921 DemandedMask = APInt::getAllOnesValue(BitWidth);
922
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000923 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000924 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000925 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000926 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927 case Instruction::And:
928 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000929 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
930 RHSKnownZero, RHSKnownOne, Depth+1) ||
931 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000932 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000933 return I;
934 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
935 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000936
937 // If all of the demanded bits are known 1 on one side, return the other.
938 // These bits cannot contribute to the result of the 'and'.
939 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
940 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000941 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
943 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000944 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945
946 // If all of the demanded bits in the inputs are known zeros, return zero.
947 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000948 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949
950 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000951 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000952 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000953
954 // Output known-1 bits are only known if set in both the LHS & RHS.
955 RHSKnownOne &= LHSKnownOne;
956 // Output known-0 are known to be clear if zero in either the LHS | RHS.
957 RHSKnownZero |= LHSKnownZero;
958 break;
959 case Instruction::Or:
960 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +0000961 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
962 RHSKnownZero, RHSKnownOne, Depth+1) ||
963 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000964 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000965 return I;
966 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
967 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000968
969 // If all of the demanded bits are known zero on one side, return the other.
970 // These bits cannot contribute to the result of the 'or'.
971 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
972 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000973 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
975 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000976 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000977
978 // If all of the potentially set bits on one side are known to be set on
979 // the other side, just use the 'other' side.
980 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
981 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000982 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000983 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
984 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000985 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986
987 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000988 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +0000989 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000990
991 // Output known-0 bits are only known if clear in both the LHS & RHS.
992 RHSKnownZero &= LHSKnownZero;
993 // Output known-1 are known to be set if set in either the LHS | RHS.
994 RHSKnownOne |= LHSKnownOne;
995 break;
996 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +0000997 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
998 RHSKnownZero, RHSKnownOne, Depth+1) ||
999 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001000 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001001 return I;
1002 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1003 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001004
1005 // If all of the demanded bits are known zero on one side, return the other.
1006 // These bits cannot contribute to the result of the 'xor'.
1007 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001008 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001010 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001011
1012 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1013 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1014 (RHSKnownOne & LHSKnownOne);
1015 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1016 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1017 (RHSKnownOne & LHSKnownZero);
1018
1019 // If all of the demanded bits are known to be zero on one side or the
1020 // other, turn this into an *inclusive* or.
1021 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneradba7ea2009-08-31 04:36:22 +00001022 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1023 Instruction *Or =
1024 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1025 I->getName());
1026 return InsertNewInstBefore(Or, *I);
1027 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028
1029 // If all of the demanded bits on one side are known, and all of the set
1030 // bits on that side are also known to be set on the other side, turn this
1031 // into an AND, as we know the bits will be cleared.
1032 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1033 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1034 // all known
1035 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohmancf2c9982009-08-03 22:07:33 +00001036 Constant *AndC = Constant::getIntegerValue(VTy,
1037 ~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001038 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001039 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001040 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041 }
1042 }
1043
1044 // If the RHS is a constant, see if we can simplify it.
1045 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001046 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001047 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048
1049 RHSKnownZero = KnownZeroOut;
1050 RHSKnownOne = KnownOneOut;
1051 break;
1052 }
1053 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001054 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1055 RHSKnownZero, RHSKnownOne, Depth+1) ||
1056 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001058 return I;
1059 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1060 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001061
1062 // If the operands are constants, see if we can simplify them.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001063 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1064 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001065 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066
1067 // Only known if known in both the LHS and RHS.
1068 RHSKnownOne &= LHSKnownOne;
1069 RHSKnownZero &= LHSKnownZero;
1070 break;
1071 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001072 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073 DemandedMask.zext(truncBf);
1074 RHSKnownZero.zext(truncBf);
1075 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001076 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001077 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001078 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079 DemandedMask.trunc(BitWidth);
1080 RHSKnownZero.trunc(BitWidth);
1081 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001082 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001083 break;
1084 }
1085 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001086 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001087 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001088
1089 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1090 if (const VectorType *SrcVTy =
1091 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1092 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1093 // Don't touch a bitcast between vectors of different element counts.
1094 return false;
1095 } else
1096 // Don't touch a scalar-to-vector bitcast.
1097 return false;
1098 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1099 // Don't touch a vector-to-scalar bitcast.
1100 return false;
1101
Chris Lattner676c78e2009-01-31 08:15:18 +00001102 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001104 return I;
1105 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001106 break;
1107 case Instruction::ZExt: {
1108 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001109 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001110
1111 DemandedMask.trunc(SrcBitWidth);
1112 RHSKnownZero.trunc(SrcBitWidth);
1113 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001114 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001115 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001116 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001117 DemandedMask.zext(BitWidth);
1118 RHSKnownZero.zext(BitWidth);
1119 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001120 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121 // The top bits are known to be zero.
1122 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1123 break;
1124 }
1125 case Instruction::SExt: {
1126 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001127 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128
1129 APInt InputDemandedBits = DemandedMask &
1130 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1131
1132 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1133 // If any of the sign extended bits are demanded, we know that the sign
1134 // bit is demanded.
1135 if ((NewBits & DemandedMask) != 0)
1136 InputDemandedBits.set(SrcBitWidth-1);
1137
1138 InputDemandedBits.trunc(SrcBitWidth);
1139 RHSKnownZero.trunc(SrcBitWidth);
1140 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001141 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001143 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001144 InputDemandedBits.zext(BitWidth);
1145 RHSKnownZero.zext(BitWidth);
1146 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001147 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148
1149 // If the sign bit of the input is known set or clear, then we know the
1150 // top bits of the result.
1151
1152 // If the input sign bit is known zero, or if the NewBits are not demanded
1153 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001154 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001155 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001156 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1157 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1159 RHSKnownOne |= NewBits;
1160 }
1161 break;
1162 }
1163 case Instruction::Add: {
1164 // Figure out what the input bits are. If the top bits of the and result
1165 // are not demanded, then the add doesn't demand them from its input
1166 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001167 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001168
1169 // If there is a constant on the RHS, there are a variety of xformations
1170 // we can do.
1171 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1172 // If null, this should be simplified elsewhere. Some of the xforms here
1173 // won't work if the RHS is zero.
1174 if (RHS->isZero())
1175 break;
1176
1177 // If the top bit of the output is demanded, demand everything from the
1178 // input. Otherwise, we demand all the input bits except NLZ top bits.
1179 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1180
1181 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001182 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001183 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001184 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001185
1186 // If the RHS of the add has bits set that can't affect the input, reduce
1187 // the constant.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001188 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001189 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001190
1191 // Avoid excess work.
1192 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1193 break;
1194
1195 // Turn it into OR if input bits are zero.
1196 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1197 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001198 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001199 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001200 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201 }
1202
1203 // We can say something about the output known-zero and known-one bits,
1204 // depending on potential carries from the input constant and the
1205 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1206 // bits set and the RHS constant is 0x01001, then we know we have a known
1207 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1208
1209 // To compute this, we first compute the potential carry bits. These are
1210 // the bits which may be modified. I'm not aware of a better way to do
1211 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001212 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001213 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1214
1215 // Now that we know which bits have carries, compute the known-1/0 sets.
1216
1217 // Bits are known one if they are known zero in one operand and one in the
1218 // other, and there is no input carry.
1219 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1220 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1221
1222 // Bits are known zero if they are known zero in both operands and there
1223 // is no input carry.
1224 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1225 } else {
1226 // If the high-bits of this ADD are not demanded, then it does not demand
1227 // the high bits of its LHS or RHS.
1228 if (DemandedMask[BitWidth-1] == 0) {
1229 // Right fill the mask of bits for this ADD to demand the most
1230 // significant bit and all those below it.
1231 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001232 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1233 LHSKnownZero, LHSKnownOne, Depth+1) ||
1234 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001235 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001236 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001237 }
1238 }
1239 break;
1240 }
1241 case Instruction::Sub:
1242 // If the high-bits of this SUB are not demanded, then it does not demand
1243 // the high bits of its LHS or RHS.
1244 if (DemandedMask[BitWidth-1] == 0) {
1245 // Right fill the mask of bits for this SUB to demand the most
1246 // significant bit and all those below it.
1247 uint32_t NLZ = DemandedMask.countLeadingZeros();
1248 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001249 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1250 LHSKnownZero, LHSKnownOne, Depth+1) ||
1251 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001252 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001253 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001255 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1256 // the known zeros and ones.
1257 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258 break;
1259 case Instruction::Shl:
1260 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1261 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1262 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001263 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001265 return I;
1266 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 RHSKnownZero <<= ShiftAmt;
1268 RHSKnownOne <<= ShiftAmt;
1269 // low bits known zero.
1270 if (ShiftAmt)
1271 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1272 }
1273 break;
1274 case Instruction::LShr:
1275 // For a logical shift right
1276 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1277 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1278
1279 // Unsigned shift right.
1280 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001281 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001282 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001283 return I;
1284 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1286 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1287 if (ShiftAmt) {
1288 // Compute the new bits that are at the top now.
1289 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1290 RHSKnownZero |= HighBits; // high bits known zero.
1291 }
1292 }
1293 break;
1294 case Instruction::AShr:
1295 // If this is an arithmetic shift right and only the low-bit is set, we can
1296 // always convert this into a logical shr, even if the shift amount is
1297 // variable. The low bit of the shift cannot be an input sign bit unless
1298 // the shift amount is >= the size of the datatype, which is undefined.
1299 if (DemandedMask == 1) {
1300 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001301 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001302 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001303 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001304 }
1305
1306 // If the sign bit is the only bit demanded by this ashr, then there is no
1307 // need to do it, the shift doesn't change the high bit.
1308 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001309 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001310
1311 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1312 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1313
1314 // Signed shift right.
1315 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1316 // If any of the "high bits" are demanded, we should set the sign bit as
1317 // demanded.
1318 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1319 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001320 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001322 return I;
1323 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 // Compute the new bits that are at the top now.
1325 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1326 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1327 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1328
1329 // Handle the sign bits.
1330 APInt SignBit(APInt::getSignBit(BitWidth));
1331 // Adjust to where it is now in the mask.
1332 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1333
1334 // If the input sign bit is known to be zero, or if none of the top bits
1335 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001336 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001337 (HighBits & ~DemandedMask) == HighBits) {
1338 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001339 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001341 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1343 RHSKnownOne |= HighBits;
1344 }
1345 }
1346 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001347 case Instruction::SRem:
1348 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001349 APInt RA = Rem->getValue().abs();
1350 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001351 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001352 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001353
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001354 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001355 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001356 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001357 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001358 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001359
1360 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1361 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001362
1363 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001364
Chris Lattner676c78e2009-01-31 08:15:18 +00001365 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001366 }
1367 }
1368 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001369 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001370 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1371 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001372 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1373 KnownZero2, KnownOne2, Depth+1) ||
1374 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001375 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001376 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001377
Chris Lattneree5417c2009-01-21 18:09:24 +00001378 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001379 Leaders = std::max(Leaders,
1380 KnownZero2.countLeadingOnes());
1381 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001382 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383 }
Chris Lattner989ba312008-06-18 04:33:20 +00001384 case Instruction::Call:
1385 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1386 switch (II->getIntrinsicID()) {
1387 default: break;
1388 case Intrinsic::bswap: {
1389 // If the only bits demanded come from one byte of the bswap result,
1390 // just shift the input byte into position to eliminate the bswap.
1391 unsigned NLZ = DemandedMask.countLeadingZeros();
1392 unsigned NTZ = DemandedMask.countTrailingZeros();
1393
1394 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1395 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1396 // have 14 leading zeros, round to 8.
1397 NLZ &= ~7;
1398 NTZ &= ~7;
1399 // If we need exactly one byte, we can do this transformation.
1400 if (BitWidth-NLZ-NTZ == 8) {
1401 unsigned ResultBit = NTZ;
1402 unsigned InputBit = BitWidth-NTZ-8;
1403
1404 // Replace this with either a left or right shift to get the byte into
1405 // the right place.
1406 Instruction *NewVal;
1407 if (InputBit > ResultBit)
1408 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001409 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001410 else
1411 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001412 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001413 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001414 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001415 }
1416
1417 // TODO: Could compute known zero/one bits based on the input.
1418 break;
1419 }
1420 }
1421 }
Chris Lattner4946e222008-06-18 18:11:55 +00001422 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001423 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001424 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001425
1426 // If the client is only demanding bits that we know, return the known
1427 // constant.
Dan Gohmancf2c9982009-08-03 22:07:33 +00001428 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1429 return Constant::getIntegerValue(VTy, RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001430 return false;
1431}
1432
1433
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001434/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001435/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001436/// actually used by the caller. This method analyzes which elements of the
1437/// operand are undef and returns that information in UndefElts.
1438///
1439/// If the information about demanded elements can be used to simplify the
1440/// operation, the operation is simplified, then the resultant value is
1441/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001442Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1443 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001444 unsigned Depth) {
1445 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001446 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001447 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001448
1449 if (isa<UndefValue>(V)) {
1450 // If the entire vector is undefined, just return this info.
1451 UndefElts = EltMask;
1452 return 0;
1453 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1454 UndefElts = EltMask;
Owen Andersonb99ecca2009-07-30 23:03:37 +00001455 return UndefValue::get(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001456 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001457
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001458 UndefElts = 0;
1459 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1460 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb99ecca2009-07-30 23:03:37 +00001461 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001462
1463 std::vector<Constant*> Elts;
1464 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001465 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001466 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001467 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001468 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1469 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001470 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001471 } else { // Otherwise, defined.
1472 Elts.push_back(CP->getOperand(i));
1473 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001474
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001475 // If we changed the constant, return it.
Owen Anderson2f422e02009-07-28 21:19:26 +00001476 Constant *NewCP = ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001477 return NewCP != CP ? NewCP : 0;
1478 } else if (isa<ConstantAggregateZero>(V)) {
1479 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1480 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001481
1482 // Check if this is identity. If so, return 0 since we are not simplifying
1483 // anything.
1484 if (DemandedElts == ((1ULL << VWidth) -1))
1485 return 0;
1486
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001487 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonaac28372009-07-31 20:28:14 +00001488 Constant *Zero = Constant::getNullValue(EltTy);
Owen Andersonb99ecca2009-07-30 23:03:37 +00001489 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001490 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001491 for (unsigned i = 0; i != VWidth; ++i) {
1492 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1493 Elts.push_back(Elt);
1494 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001495 UndefElts = DemandedElts ^ EltMask;
Owen Anderson2f422e02009-07-28 21:19:26 +00001496 return ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001497 }
1498
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001499 // Limit search depth.
1500 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001501 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001502
1503 // If multiple users are using the root value, procede with
1504 // simplification conservatively assuming that all elements
1505 // are needed.
1506 if (!V->hasOneUse()) {
1507 // Quit if we find multiple users of a non-root value though.
1508 // They'll be handled when it's their turn to be visited by
1509 // the main instcombine process.
1510 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001511 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001512 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001513
1514 // Conservatively assume that all elements are needed.
1515 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001516 }
1517
1518 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001519 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001520
1521 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001522 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001523 Value *TmpV;
1524 switch (I->getOpcode()) {
1525 default: break;
1526
1527 case Instruction::InsertElement: {
1528 // If this is a variable index, we don't know which element it overwrites.
1529 // demand exactly the same input as we produce.
1530 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1531 if (Idx == 0) {
1532 // Note that we can't propagate undef elt info, because we don't know
1533 // which elt is getting updated.
1534 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1535 UndefElts2, Depth+1);
1536 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1537 break;
1538 }
1539
1540 // If this is inserting an element that isn't demanded, remove this
1541 // insertelement.
1542 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner059cfc72009-08-30 06:20:05 +00001543 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1544 Worklist.Add(I);
1545 return I->getOperand(0);
1546 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001547
1548 // Otherwise, the element inserted overwrites whatever was there, so the
1549 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001550 APInt DemandedElts2 = DemandedElts;
1551 DemandedElts2.clear(IdxNo);
1552 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001553 UndefElts, Depth+1);
1554 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1555
1556 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001557 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001558 break;
1559 }
1560 case Instruction::ShuffleVector: {
1561 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001562 uint64_t LHSVWidth =
1563 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001564 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001565 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001566 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001567 unsigned MaskVal = Shuffle->getMaskValue(i);
1568 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001569 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001570 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001571 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001572 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001573 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001574 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001575 }
1576 }
1577 }
1578
Nate Begemanb4d176f2009-02-11 22:36:25 +00001579 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001580 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001581 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001582 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1583
Nate Begemanb4d176f2009-02-11 22:36:25 +00001584 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001585 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1586 UndefElts3, Depth+1);
1587 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1588
1589 bool NewUndefElts = false;
1590 for (unsigned i = 0; i < VWidth; i++) {
1591 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001592 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001593 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001594 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001595 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001596 NewUndefElts = true;
1597 UndefElts.set(i);
1598 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001599 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001600 if (UndefElts3[MaskVal - LHSVWidth]) {
1601 NewUndefElts = true;
1602 UndefElts.set(i);
1603 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001604 }
1605 }
1606
1607 if (NewUndefElts) {
1608 // Add additional discovered undefs.
1609 std::vector<Constant*> Elts;
1610 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001611 if (UndefElts[i])
Owen Anderson35b47072009-08-13 21:58:54 +00001612 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001613 else
Owen Anderson35b47072009-08-13 21:58:54 +00001614 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001615 Shuffle->getMaskValue(i)));
1616 }
Owen Anderson2f422e02009-07-28 21:19:26 +00001617 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001618 MadeChange = true;
1619 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001620 break;
1621 }
1622 case Instruction::BitCast: {
1623 // Vector->vector casts only.
1624 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1625 if (!VTy) break;
1626 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001627 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001628 unsigned Ratio;
1629
1630 if (VWidth == InVWidth) {
1631 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1632 // elements as are demanded of us.
1633 Ratio = 1;
1634 InputDemandedElts = DemandedElts;
1635 } else if (VWidth > InVWidth) {
1636 // Untested so far.
1637 break;
1638
1639 // If there are more elements in the result than there are in the source,
1640 // then an input element is live if any of the corresponding output
1641 // elements are live.
1642 Ratio = VWidth/InVWidth;
1643 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001644 if (DemandedElts[OutIdx])
1645 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001646 }
1647 } else {
1648 // Untested so far.
1649 break;
1650
1651 // If there are more elements in the source than there are in the result,
1652 // then an input element is live if the corresponding output element is
1653 // live.
1654 Ratio = InVWidth/VWidth;
1655 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001656 if (DemandedElts[InIdx/Ratio])
1657 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001658 }
1659
1660 // div/rem demand all inputs, because they don't want divide by zero.
1661 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1662 UndefElts2, Depth+1);
1663 if (TmpV) {
1664 I->setOperand(0, TmpV);
1665 MadeChange = true;
1666 }
1667
1668 UndefElts = UndefElts2;
1669 if (VWidth > InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001670 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001671 // If there are more elements in the result than there are in the source,
1672 // then an output element is undef if the corresponding input element is
1673 // undef.
1674 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001675 if (UndefElts2[OutIdx/Ratio])
1676 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001677 } else if (VWidth < InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001678 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001679 // If there are more elements in the source than there are in the result,
1680 // then a result element is undef if all of the corresponding input
1681 // elements are undef.
1682 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1683 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001684 if (!UndefElts2[InIdx]) // Not undef?
1685 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001686 }
1687 break;
1688 }
1689 case Instruction::And:
1690 case Instruction::Or:
1691 case Instruction::Xor:
1692 case Instruction::Add:
1693 case Instruction::Sub:
1694 case Instruction::Mul:
1695 // div/rem demand all inputs, because they don't want divide by zero.
1696 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1697 UndefElts, Depth+1);
1698 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1699 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1700 UndefElts2, Depth+1);
1701 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1702
1703 // Output elements are undefined if both are undefined. Consider things
1704 // like undef&0. The result is known zero, not undef.
1705 UndefElts &= UndefElts2;
1706 break;
1707
1708 case Instruction::Call: {
1709 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1710 if (!II) break;
1711 switch (II->getIntrinsicID()) {
1712 default: break;
1713
1714 // Binary vector operations that work column-wise. A dest element is a
1715 // function of the corresponding input elements from the two inputs.
1716 case Intrinsic::x86_sse_sub_ss:
1717 case Intrinsic::x86_sse_mul_ss:
1718 case Intrinsic::x86_sse_min_ss:
1719 case Intrinsic::x86_sse_max_ss:
1720 case Intrinsic::x86_sse2_sub_sd:
1721 case Intrinsic::x86_sse2_mul_sd:
1722 case Intrinsic::x86_sse2_min_sd:
1723 case Intrinsic::x86_sse2_max_sd:
1724 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1725 UndefElts, Depth+1);
1726 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1727 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1728 UndefElts2, Depth+1);
1729 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1730
1731 // If only the low elt is demanded and this is a scalarizable intrinsic,
1732 // scalarize it now.
1733 if (DemandedElts == 1) {
1734 switch (II->getIntrinsicID()) {
1735 default: break;
1736 case Intrinsic::x86_sse_sub_ss:
1737 case Intrinsic::x86_sse_mul_ss:
1738 case Intrinsic::x86_sse2_sub_sd:
1739 case Intrinsic::x86_sse2_mul_sd:
1740 // TODO: Lower MIN/MAX/ABS/etc
1741 Value *LHS = II->getOperand(1);
1742 Value *RHS = II->getOperand(2);
1743 // Extract the element as scalars.
Eric Christopher1ba36872009-07-25 02:28:41 +00001744 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001745 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christopher1ba36872009-07-25 02:28:41 +00001746 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001747 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001748
1749 switch (II->getIntrinsicID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001750 default: llvm_unreachable("Case stmts out of sync!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001751 case Intrinsic::x86_sse_sub_ss:
1752 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001753 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001754 II->getName()), *II);
1755 break;
1756 case Intrinsic::x86_sse_mul_ss:
1757 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001758 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001759 II->getName()), *II);
1760 break;
1761 }
1762
1763 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001764 InsertElementInst::Create(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001765 UndefValue::get(II->getType()), TmpV,
Owen Anderson35b47072009-08-13 21:58:54 +00001766 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001767 InsertNewInstBefore(New, *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001768 return New;
1769 }
1770 }
1771
1772 // Output elements are undefined if both are undefined. Consider things
1773 // like undef&0. The result is known zero, not undef.
1774 UndefElts &= UndefElts2;
1775 break;
1776 }
1777 break;
1778 }
1779 }
1780 return MadeChange ? I : 0;
1781}
1782
Dan Gohman5d56fd42008-05-19 22:14:15 +00001783
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001784/// AssociativeOpt - Perform an optimization on an associative operator. This
1785/// function is designed to check a chain of associative operators for a
1786/// potential to apply a certain optimization. Since the optimization may be
1787/// applicable if the expression was reassociated, this checks the chain, then
1788/// reassociates the expression as necessary to expose the optimization
1789/// opportunity. This makes use of a special Functor, which must define
1790/// 'shouldApply' and 'apply' methods.
1791///
1792template<typename Functor>
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001793static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001794 unsigned Opcode = Root.getOpcode();
1795 Value *LHS = Root.getOperand(0);
1796
1797 // Quick check, see if the immediate LHS matches...
1798 if (F.shouldApply(LHS))
1799 return F.apply(Root);
1800
1801 // Otherwise, if the LHS is not of the same opcode as the root, return.
1802 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1803 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1804 // Should we apply this transform to the RHS?
1805 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1806
1807 // If not to the RHS, check to see if we should apply to the LHS...
1808 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1809 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1810 ShouldApply = true;
1811 }
1812
1813 // If the functor wants to apply the optimization to the RHS of LHSI,
1814 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1815 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001816 // Now all of the instructions are in the current basic block, go ahead
1817 // and perform the reassociation.
1818 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1819
1820 // First move the selected RHS to the LHS of the root...
1821 Root.setOperand(0, LHSI->getOperand(1));
1822
1823 // Make what used to be the LHS of the root be the user of the root...
1824 Value *ExtraOperand = TmpLHSI->getOperand(1);
1825 if (&Root == TmpLHSI) {
Owen Andersonaac28372009-07-31 20:28:14 +00001826 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001827 return 0;
1828 }
1829 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1830 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001831 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001832 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001833 ARI = Root;
1834
1835 // Now propagate the ExtraOperand down the chain of instructions until we
1836 // get to LHSI.
1837 while (TmpLHSI != LHSI) {
1838 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1839 // Move the instruction to immediately before the chain we are
1840 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001841 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001842 ARI = NextLHSI;
1843
1844 Value *NextOp = NextLHSI->getOperand(1);
1845 NextLHSI->setOperand(1, ExtraOperand);
1846 TmpLHSI = NextLHSI;
1847 ExtraOperand = NextOp;
1848 }
1849
1850 // Now that the instructions are reassociated, have the functor perform
1851 // the transformation...
1852 return F.apply(Root);
1853 }
1854
1855 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1856 }
1857 return 0;
1858}
1859
Dan Gohman089efff2008-05-13 00:00:25 +00001860namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001861
Nick Lewycky27f6c132008-05-23 04:34:58 +00001862// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001863struct AddRHS {
1864 Value *RHS;
Dan Gohmancdff2122009-08-12 16:23:25 +00001865 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001866 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1867 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001868 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001869 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001870 }
1871};
1872
1873// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1874// iff C1&C2 == 0
1875struct AddMaskingAnd {
1876 Constant *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00001877 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001878 bool shouldApply(Value *LHS) const {
1879 ConstantInt *C1;
Dan Gohmancdff2122009-08-12 16:23:25 +00001880 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Anderson02b48c32009-07-29 18:55:55 +00001881 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001882 }
1883 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001884 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001885 }
1886};
1887
Dan Gohman089efff2008-05-13 00:00:25 +00001888}
1889
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001890static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1891 InstCombiner *IC) {
Chris Lattner78628292009-08-30 19:47:22 +00001892 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattnerd6164c22009-08-30 20:01:10 +00001893 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001894
1895 // Figure out if the constant is the left or the right argument.
1896 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1897 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1898
1899 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1900 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +00001901 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1902 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001903 }
1904
1905 Value *Op0 = SO, *Op1 = ConstOperand;
1906 if (!ConstIsRHS)
1907 std::swap(Op0, Op1);
Chris Lattnerc7694852009-08-30 07:44:24 +00001908
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001909 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattnerc7694852009-08-30 07:44:24 +00001910 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1911 SO->getName()+".op");
1912 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1913 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1914 SO->getName()+".cmp");
1915 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1916 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1917 SO->getName()+".cmp");
1918 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001919}
1920
1921// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1922// constant as the other operand, try to fold the binary operator into the
1923// select arguments. This also works for Cast instructions, which obviously do
1924// not have a second operand.
1925static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1926 InstCombiner *IC) {
1927 // Don't modify shared select instructions
1928 if (!SI->hasOneUse()) return 0;
1929 Value *TV = SI->getOperand(1);
1930 Value *FV = SI->getOperand(2);
1931
1932 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1933 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson35b47072009-08-13 21:58:54 +00001934 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001935
1936 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1937 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1938
Gabor Greifd6da1d02008-04-06 20:25:17 +00001939 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1940 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001941 }
1942 return 0;
1943}
1944
1945
Chris Lattnerf7843b72009-09-27 19:57:57 +00001946/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1947/// has a PHI node as operand #0, see if we can fold the instruction into the
1948/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +00001949///
1950/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1951/// that would normally be unprofitable because they strongly encourage jump
1952/// threading.
1953Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1954 bool AllowAggressive) {
1955 AllowAggressive = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001956 PHINode *PN = cast<PHINode>(I.getOperand(0));
1957 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner9b61abd2009-09-27 20:46:36 +00001958 if (NumPHIValues == 0 ||
1959 // We normally only transform phis with a single use, unless we're trying
1960 // hard to make jump threading happen.
1961 (!PN->hasOneUse() && !AllowAggressive))
1962 return 0;
1963
1964
Chris Lattnerf7843b72009-09-27 19:57:57 +00001965 // Check to see if all of the operands of the PHI are simple constants
1966 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00001967 // remember the BB it is in. If there is more than one or if *it* is a PHI,
1968 // bail out. We don't do arbitrary constant expressions here because moving
1969 // their computation can be expensive without a cost model.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001970 BasicBlock *NonConstBB = 0;
1971 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattnerf7843b72009-09-27 19:57:57 +00001972 if (!isa<Constant>(PN->getIncomingValue(i)) ||
1973 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001974 if (NonConstBB) return 0; // More than one non-const value.
1975 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1976 NonConstBB = PN->getIncomingBlock(i);
1977
1978 // If the incoming non-constant value is in I's block, we have an infinite
1979 // loop.
1980 if (NonConstBB == I.getParent())
1981 return 0;
1982 }
1983
1984 // If there is exactly one non-constant value, we can insert a copy of the
1985 // operation in that block. However, if this is a critical edge, we would be
1986 // inserting the computation one some other paths (e.g. inside a loop). Only
1987 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9b61abd2009-09-27 20:46:36 +00001988 if (NonConstBB != 0 && !AllowAggressive) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001989 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1990 if (!BI || !BI->isUnconditional()) return 0;
1991 }
1992
1993 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001994 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001995 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1996 InsertNewInstBefore(NewPN, *PN);
1997 NewPN->takeName(PN);
1998
1999 // Next, add all of the operands to the PHI.
Chris Lattnerf7843b72009-09-27 19:57:57 +00002000 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2001 // We only currently try to fold the condition of a select when it is a phi,
2002 // not the true/false values.
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002003 Value *TrueV = SI->getTrueValue();
2004 Value *FalseV = SI->getFalseValue();
Chris Lattnerf7843b72009-09-27 19:57:57 +00002005 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002006 BasicBlock *ThisBB = PN->getIncomingBlock(i);
2007 Value *TrueVInPred = TrueV->DoPHITranslation(I.getParent(), ThisBB);
2008 Value *FalseVInPred = FalseV->DoPHITranslation(I.getParent(), ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002009 Value *InV = 0;
2010 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002011 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerf7843b72009-09-27 19:57:57 +00002012 } else {
2013 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002014 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2015 FalseVInPred,
Chris Lattnerf7843b72009-09-27 19:57:57 +00002016 "phitmp", NonConstBB->getTerminator());
2017 Worklist.Add(cast<Instruction>(InV));
2018 }
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002019 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002020 }
2021 } else if (I.getNumOperands() == 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002022 Constant *C = cast<Constant>(I.getOperand(1));
2023 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002024 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002025 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2026 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +00002027 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002028 else
Owen Anderson02b48c32009-07-29 18:55:55 +00002029 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002030 } else {
2031 assert(PN->getIncomingBlock(i) == NonConstBB);
2032 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002033 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002034 PN->getIncomingValue(i), C, "phitmp",
2035 NonConstBB->getTerminator());
2036 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +00002037 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002038 CI->getPredicate(),
2039 PN->getIncomingValue(i), C, "phitmp",
2040 NonConstBB->getTerminator());
2041 else
Edwin Törökbd448e32009-07-14 16:55:14 +00002042 llvm_unreachable("Unknown binop!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002043
Chris Lattner3183fb62009-08-30 06:13:40 +00002044 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002045 }
2046 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2047 }
2048 } else {
2049 CastInst *CI = cast<CastInst>(&I);
2050 const Type *RetTy = CI->getType();
2051 for (unsigned i = 0; i != NumPHIValues; ++i) {
2052 Value *InV;
2053 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002054 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002055 } else {
2056 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002057 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002058 I.getType(), "phitmp",
2059 NonConstBB->getTerminator());
Chris Lattner3183fb62009-08-30 06:13:40 +00002060 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002061 }
2062 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2063 }
2064 }
2065 return ReplaceInstUsesWith(I, NewPN);
2066}
2067
Chris Lattner55476162008-01-29 06:52:45 +00002068
Chris Lattner3554f972008-05-20 05:46:13 +00002069/// WillNotOverflowSignedAdd - Return true if we can prove that:
2070/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2071/// This basically requires proving that the add in the original type would not
2072/// overflow to change the sign bit or have a carry out.
2073bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2074 // There are different heuristics we can use for this. Here are some simple
2075 // ones.
2076
2077 // Add has the property that adding any two 2's complement numbers can only
2078 // have one carry bit which can change a sign. As such, if LHS and RHS each
2079 // have at least two sign bits, we know that the addition of the two values will
2080 // sign extend fine.
2081 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2082 return true;
2083
2084
2085 // If one of the operands only has one non-zero bit, and if the other operand
2086 // has a known-zero bit in a more significant place than it (not including the
2087 // sign bit) the ripple may go up to and fill the zero, but won't change the
2088 // sign. For example, (X & ~4) + 1.
2089
2090 // TODO: Implement.
2091
2092 return false;
2093}
2094
Chris Lattner55476162008-01-29 06:52:45 +00002095
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002096Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2097 bool Changed = SimplifyCommutative(I);
2098 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2099
2100 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2101 // X + undef -> undef
2102 if (isa<UndefValue>(RHS))
2103 return ReplaceInstUsesWith(I, RHS);
2104
2105 // X + 0 --> X
Dan Gohman7ce405e2009-06-04 22:49:04 +00002106 if (RHSC->isNullValue())
2107 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002108
2109 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2110 // X + (signbit) --> X ^ signbit
2111 const APInt& Val = CI->getValue();
2112 uint32_t BitWidth = Val.getBitWidth();
2113 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002114 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002115
2116 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2117 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002118 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002119 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002120
Eli Friedmana21526d2009-07-13 22:27:52 +00002121 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +00002122 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson35b47072009-08-13 21:58:54 +00002123 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002124 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002125 }
2126
2127 if (isa<PHINode>(LHS))
2128 if (Instruction *NV = FoldOpIntoPhi(I))
2129 return NV;
2130
2131 ConstantInt *XorRHS = 0;
2132 Value *XorLHS = 0;
2133 if (isa<ConstantInt>(RHSC) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002134 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002135 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002136 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2137
2138 uint32_t Size = TySizeBits / 2;
2139 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2140 APInt CFF80Val(-C0080Val);
2141 do {
2142 if (TySizeBits > Size) {
2143 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2144 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2145 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2146 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2147 // This is a sign extend if the top bits are known zero.
2148 if (!MaskedValueIsZero(XorLHS,
2149 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2150 Size = 0; // Not a sign ext, but can't be any others either.
2151 break;
2152 }
2153 }
2154 Size >>= 1;
2155 C0080Val = APIntOps::lshr(C0080Val, Size);
2156 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2157 } while (Size >= 1);
2158
2159 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002160 // with funny bit widths then this switch statement should be removed. It
2161 // is just here to get the size of the "middle" type back up to something
2162 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002163 const Type *MiddleType = 0;
2164 switch (Size) {
2165 default: break;
Owen Anderson35b47072009-08-13 21:58:54 +00002166 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2167 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2168 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002169 }
2170 if (MiddleType) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002171 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002172 return new SExtInst(NewTrunc, I.getType(), I.getName());
2173 }
2174 }
2175 }
2176
Owen Anderson35b47072009-08-13 21:58:54 +00002177 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002178 return BinaryOperator::CreateXor(LHS, RHS);
2179
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002180 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002181 if (I.getType()->isInteger()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00002182 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Anderson24be4c12009-07-03 00:17:18 +00002183 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002184
2185 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2186 if (RHSI->getOpcode() == Instruction::Sub)
2187 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2188 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2189 }
2190 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2191 if (LHSI->getOpcode() == Instruction::Sub)
2192 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2193 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2194 }
2195 }
2196
2197 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002198 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002199 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002200 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002201 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002202 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohmancdff2122009-08-12 16:23:25 +00002203 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002204 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002205 }
2206
Gabor Greifa645dd32008-05-16 19:29:10 +00002207 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002208 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002209
2210 // A + -B --> A - B
2211 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002212 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002213 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002214
2215
2216 ConstantInt *C2;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002217 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002218 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002219 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002220
2221 // X*C1 + X*C2 --> X * (C1+C2)
2222 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002223 if (X == dyn_castFoldableMul(RHS, C1))
Owen Anderson02b48c32009-07-29 18:55:55 +00002224 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002225 }
2226
2227 // X + X*C --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002228 if (dyn_castFoldableMul(RHS, C2) == LHS)
2229 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002230
2231 // X + ~X --> -1 since ~X = -X-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002232 if (dyn_castNotVal(LHS) == RHS ||
2233 dyn_castNotVal(RHS) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +00002234 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235
2236
2237 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00002238 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2239 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002240 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002241
2242 // A+B --> A|B iff A and B have no bits set in common.
2243 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2244 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2245 APInt LHSKnownOne(IT->getBitWidth(), 0);
2246 APInt LHSKnownZero(IT->getBitWidth(), 0);
2247 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2248 if (LHSKnownZero != 0) {
2249 APInt RHSKnownOne(IT->getBitWidth(), 0);
2250 APInt RHSKnownZero(IT->getBitWidth(), 0);
2251 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2252
2253 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002254 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002255 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002256 }
2257 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002258
Nick Lewycky83598a72008-02-03 07:42:09 +00002259 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002260 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002261 Value *W, *X, *Y, *Z;
Dan Gohmancdff2122009-08-12 16:23:25 +00002262 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2263 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002264 if (W != Y) {
2265 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002266 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002267 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002268 std::swap(W, X);
2269 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002270 std::swap(Y, Z);
2271 std::swap(W, X);
2272 }
2273 }
2274
2275 if (W == Y) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002276 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002277 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002278 }
2279 }
2280 }
2281
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002282 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2283 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002284 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002285 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002286
2287 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002288 if (LHS->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002289 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002290 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002291 if (Anded == CRHS) {
2292 // See if all bits from the first bit set in the Add RHS up are included
2293 // in the mask. First, get the rightmost bit.
2294 const APInt& AddRHSV = CRHS->getValue();
2295
2296 // Form a mask of all bits from the lowest bit added through the top.
2297 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2298
2299 // See if the and mask includes all of these bits.
2300 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2301
2302 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2303 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattnerc7694852009-08-30 07:44:24 +00002304 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002305 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002306 }
2307 }
2308 }
2309
2310 // Try to fold constant add into select arguments.
2311 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2312 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2313 return R;
2314 }
2315
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002316 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002317 {
2318 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002319 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002320 if (!SI) {
2321 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002322 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002323 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002324 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002325 Value *TV = SI->getTrueValue();
2326 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002327 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002328
2329 // Can we fold the add into the argument of the select?
2330 // We check both true and false select arguments for a matching subtract.
Dan Gohmancdff2122009-08-12 16:23:25 +00002331 if (match(FV, m_Zero()) &&
2332 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002333 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002334 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohmancdff2122009-08-12 16:23:25 +00002335 if (match(TV, m_Zero()) &&
2336 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002337 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002338 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002339 }
2340 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002341
Chris Lattner3554f972008-05-20 05:46:13 +00002342 // Check for (add (sext x), y), see if we can merge this into an
2343 // integer add followed by a sext.
2344 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2345 // (add (sext x), cst) --> (sext (add x, cst'))
2346 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2347 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002348 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002349 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002350 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002351 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2352 // Insert the new, smaller add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002353 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2354 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002355 return new SExtInst(NewAdd, I.getType());
2356 }
2357 }
2358
2359 // (add (sext x), (sext y)) --> (sext (add int x, y))
2360 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2361 // Only do this if x/y have the same type, if at last one of them has a
2362 // single use (so we don't increase the number of sexts), and if the
2363 // integer add will not overflow.
2364 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2365 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2366 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2367 RHSConv->getOperand(0))) {
2368 // Insert the new integer add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002369 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2370 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002371 return new SExtInst(NewAdd, I.getType());
2372 }
2373 }
2374 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002375
2376 return Changed ? &I : 0;
2377}
2378
2379Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2380 bool Changed = SimplifyCommutative(I);
2381 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2382
2383 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2384 // X + 0 --> X
2385 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +00002386 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002387 (I.getType())->getValueAPF()))
2388 return ReplaceInstUsesWith(I, LHS);
2389 }
2390
2391 if (isa<PHINode>(LHS))
2392 if (Instruction *NV = FoldOpIntoPhi(I))
2393 return NV;
2394 }
2395
2396 // -A + B --> B - A
2397 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002398 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002399 return BinaryOperator::CreateFSub(RHS, LHSV);
2400
2401 // A + -B --> A - B
2402 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002403 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002404 return BinaryOperator::CreateFSub(LHS, V);
2405
2406 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2407 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2408 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2409 return ReplaceInstUsesWith(I, LHS);
2410
Chris Lattner3554f972008-05-20 05:46:13 +00002411 // Check for (add double (sitofp x), y), see if we can merge this into an
2412 // integer add followed by a promotion.
2413 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2414 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2415 // ... if the constant fits in the integer value. This is useful for things
2416 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2417 // requires a constant pool load, and generally allows the add to be better
2418 // instcombined.
2419 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2420 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002421 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002422 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002423 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002424 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2425 // Insert the new integer add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002426 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2427 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002428 return new SIToFPInst(NewAdd, I.getType());
2429 }
2430 }
2431
2432 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2433 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2434 // Only do this if x/y have the same type, if at last one of them has a
2435 // single use (so we don't increase the number of int->fp conversions),
2436 // and if the integer add will not overflow.
2437 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2438 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2439 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2440 RHSConv->getOperand(0))) {
2441 // Insert the new integer add.
Chris Lattnerc7694852009-08-30 07:44:24 +00002442 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2443 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002444 return new SIToFPInst(NewAdd, I.getType());
2445 }
2446 }
2447 }
2448
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002449 return Changed ? &I : 0;
2450}
2451
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002452Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2453 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2454
Dan Gohman7ce405e2009-06-04 22:49:04 +00002455 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002456 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002457
2458 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002459 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002460 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002461
2462 if (isa<UndefValue>(Op0))
2463 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2464 if (isa<UndefValue>(Op1))
2465 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2466
2467 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2468 // Replace (-1 - A) with (~A)...
2469 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00002470 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002471
2472 // C - ~X == X + (1+C)
2473 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002474 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002475 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002476
2477 // -(X >>u 31) -> (X >>s 31)
2478 // -(X >>s 31) -> (X >>u 31)
2479 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002480 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002481 if (SI->getOpcode() == Instruction::LShr) {
2482 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2483 // Check to see if we are shifting out everything but the sign bit.
2484 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2485 SI->getType()->getPrimitiveSizeInBits()-1) {
2486 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002487 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002488 SI->getOperand(0), CU, SI->getName());
2489 }
2490 }
2491 }
2492 else if (SI->getOpcode() == Instruction::AShr) {
2493 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2494 // Check to see if we are shifting out everything but the sign bit.
2495 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2496 SI->getType()->getPrimitiveSizeInBits()-1) {
2497 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002498 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002499 SI->getOperand(0), CU, SI->getName());
2500 }
2501 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002502 }
2503 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002504 }
2505
2506 // Try to fold constant sub into select arguments.
2507 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2508 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2509 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002510
2511 // C - zext(bool) -> bool ? C - 1 : C
2512 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson35b47072009-08-13 21:58:54 +00002513 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002514 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002515 }
2516
Owen Anderson35b47072009-08-13 21:58:54 +00002517 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002518 return BinaryOperator::CreateXor(Op0, Op1);
2519
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002520 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002521 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002522 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002523 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002524 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002525 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002526 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002527 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002528 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2529 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2530 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002531 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002532 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002533 }
2534 }
2535
2536 if (Op1I->hasOneUse()) {
2537 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2538 // is not used by anyone else...
2539 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002540 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002541 // Swap the two operands of the subexpr...
2542 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2543 Op1I->setOperand(0, IIOp1);
2544 Op1I->setOperand(1, IIOp0);
2545
2546 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002547 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002548 }
2549
2550 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2551 //
2552 if (Op1I->getOpcode() == Instruction::And &&
2553 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2554 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2555
Chris Lattnerc7694852009-08-30 07:44:24 +00002556 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greifa645dd32008-05-16 19:29:10 +00002557 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002558 }
2559
2560 // 0 - (X sdiv C) -> (X sdiv -C)
2561 if (Op1I->getOpcode() == Instruction::SDiv)
2562 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2563 if (CSI->isZero())
2564 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002565 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002566 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002567
2568 // X - X*C --> X * (1-C)
2569 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002570 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002571 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00002572 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002573 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002574 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002575 }
2576 }
2577 }
2578
Dan Gohman7ce405e2009-06-04 22:49:04 +00002579 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2580 if (Op0I->getOpcode() == Instruction::Add) {
2581 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2582 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2583 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2584 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2585 } else if (Op0I->getOpcode() == Instruction::Sub) {
2586 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002587 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002588 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002589 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002590 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002591
2592 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002593 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002594 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002595 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002596
2597 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002598 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00002599 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002600 }
2601 return 0;
2602}
2603
Dan Gohman7ce405e2009-06-04 22:49:04 +00002604Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2605 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2606
2607 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002608 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002609 return BinaryOperator::CreateFAdd(Op0, V);
2610
2611 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2612 if (Op1I->getOpcode() == Instruction::FAdd) {
2613 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002614 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002615 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002616 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002617 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002618 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002619 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002620 }
2621
2622 return 0;
2623}
2624
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002625/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2626/// comparison only checks the sign bit. If it only checks the sign bit, set
2627/// TrueIfSigned if the result of the comparison is true when the input value is
2628/// signed.
2629static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2630 bool &TrueIfSigned) {
2631 switch (pred) {
2632 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2633 TrueIfSigned = true;
2634 return RHS->isZero();
2635 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2636 TrueIfSigned = true;
2637 return RHS->isAllOnesValue();
2638 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2639 TrueIfSigned = false;
2640 return RHS->isAllOnesValue();
2641 case ICmpInst::ICMP_UGT:
2642 // True if LHS u> RHS and RHS == high-bit-mask - 1
2643 TrueIfSigned = true;
2644 return RHS->getValue() ==
2645 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2646 case ICmpInst::ICMP_UGE:
2647 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2648 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002649 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002650 default:
2651 return false;
2652 }
2653}
2654
2655Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2656 bool Changed = SimplifyCommutative(I);
2657 Value *Op0 = I.getOperand(0);
2658
Eli Friedmane426ded2009-07-18 09:12:15 +00002659 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002660 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002661
2662 // Simplify mul instructions with a constant RHS...
2663 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2664 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2665
2666 // ((X << C1)*C2) == (X * (C2 << C1))
2667 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2668 if (SI->getOpcode() == Instruction::Shl)
2669 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002670 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002671 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002672
2673 if (CI->isZero())
2674 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2675 if (CI->equalsInt(1)) // X * 1 == X
2676 return ReplaceInstUsesWith(I, Op0);
2677 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002678 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002679
2680 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2681 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002682 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002683 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002684 }
Chris Lattner6297fc72008-08-11 22:06:05 +00002685 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedman6e058402009-07-14 02:01:53 +00002686 if (Op1->isNullValue())
2687 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky94418732008-11-27 20:21:08 +00002688
2689 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2690 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002691 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00002692
2693 // As above, vector X*splat(1.0) -> X in all defined cases.
2694 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002695 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2696 if (CI->equalsInt(1))
2697 return ReplaceInstUsesWith(I, Op0);
2698 }
2699 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002700 }
2701
2702 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2703 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002704 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002705 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnerc7694852009-08-30 07:44:24 +00002706 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2707 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
Gabor Greifa645dd32008-05-16 19:29:10 +00002708 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002709
2710 }
2711
2712 // Try to fold constant mul into select arguments.
2713 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2714 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2715 return R;
2716
2717 if (isa<PHINode>(Op0))
2718 if (Instruction *NV = FoldOpIntoPhi(I))
2719 return NV;
2720 }
2721
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002722 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2723 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002724 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002725
Nick Lewycky1c246402008-11-21 07:33:58 +00002726 // (X / Y) * Y = X - (X % Y)
2727 // (X / Y) * -Y = (X % Y) - X
2728 {
2729 Value *Op1 = I.getOperand(1);
2730 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2731 if (!BO ||
2732 (BO->getOpcode() != Instruction::UDiv &&
2733 BO->getOpcode() != Instruction::SDiv)) {
2734 Op1 = Op0;
2735 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2736 }
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002737 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00002738 if (BO && BO->hasOneUse() &&
2739 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2740 (BO->getOpcode() == Instruction::UDiv ||
2741 BO->getOpcode() == Instruction::SDiv)) {
2742 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2743
Dan Gohman07878902009-08-12 16:33:09 +00002744 // If the division is exact, X % Y is zero.
2745 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2746 if (SDiv->isExact()) {
2747 if (Op1BO == Op1)
2748 return ReplaceInstUsesWith(I, Op0BO);
2749 else
2750 return BinaryOperator::CreateNeg(Op0BO);
2751 }
2752
Chris Lattnerc7694852009-08-30 07:44:24 +00002753 Value *Rem;
Nick Lewycky1c246402008-11-21 07:33:58 +00002754 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattnerc7694852009-08-30 07:44:24 +00002755 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00002756 else
Chris Lattnerc7694852009-08-30 07:44:24 +00002757 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00002758 Rem->takeName(BO);
2759
2760 if (Op1BO == Op1)
2761 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattnerc7694852009-08-30 07:44:24 +00002762 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00002763 }
2764 }
2765
Owen Anderson35b47072009-08-13 21:58:54 +00002766 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002767 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2768
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002769 // If one of the operands of the multiply is a cast from a boolean value, then
2770 // we know the bool is either zero or one, so this is a 'masking' multiply.
2771 // See if we can simplify things based on how the boolean was originally
2772 // formed.
2773 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002774 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson35b47072009-08-13 21:58:54 +00002775 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002776 BoolCast = CI;
2777 if (!BoolCast)
2778 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson35b47072009-08-13 21:58:54 +00002779 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002780 BoolCast = CI;
2781 if (BoolCast) {
2782 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2783 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2784 const Type *SCOpTy = SCIOp0->getType();
2785 bool TIS = false;
2786
2787 // If the icmp is true iff the sign bit of X is set, then convert this
2788 // multiply into a shift/and combination.
2789 if (isa<ConstantInt>(SCIOp1) &&
2790 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2791 TIS) {
2792 // Shift the X value right to turn it into "all signbits".
Owen Andersoneacb44d2009-07-24 23:12:02 +00002793 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002794 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnerc7694852009-08-30 07:44:24 +00002795 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2796 BoolCast->getOperand(0)->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002797
2798 // If the multiply type is not the same as the source type, sign extend
2799 // or truncate to the multiply type.
Chris Lattnerd6164c22009-08-30 20:01:10 +00002800 if (I.getType() != V->getType())
2801 V = Builder->CreateIntCast(V, I.getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002802
2803 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002804 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002805 }
2806 }
2807 }
2808
2809 return Changed ? &I : 0;
2810}
2811
Dan Gohman7ce405e2009-06-04 22:49:04 +00002812Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2813 bool Changed = SimplifyCommutative(I);
2814 Value *Op0 = I.getOperand(0);
2815
2816 // Simplify mul instructions with a constant RHS...
2817 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2818 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2819 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2820 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2821 if (Op1F->isExactlyValue(1.0))
2822 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2823 } else if (isa<VectorType>(Op1->getType())) {
2824 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2825 // As above, vector X*splat(1.0) -> X in all defined cases.
2826 if (Constant *Splat = Op1V->getSplatValue()) {
2827 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2828 if (F->isExactlyValue(1.0))
2829 return ReplaceInstUsesWith(I, Op0);
2830 }
2831 }
2832 }
2833
2834 // Try to fold constant mul into select arguments.
2835 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2836 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2837 return R;
2838
2839 if (isa<PHINode>(Op0))
2840 if (Instruction *NV = FoldOpIntoPhi(I))
2841 return NV;
2842 }
2843
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002844 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2845 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002846 return BinaryOperator::CreateFMul(Op0v, Op1v);
2847
2848 return Changed ? &I : 0;
2849}
2850
Chris Lattner76972db2008-07-14 00:15:52 +00002851/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2852/// instruction.
2853bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2854 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2855
2856 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2857 int NonNullOperand = -1;
2858 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2859 if (ST->isNullValue())
2860 NonNullOperand = 2;
2861 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2862 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2863 if (ST->isNullValue())
2864 NonNullOperand = 1;
2865
2866 if (NonNullOperand == -1)
2867 return false;
2868
2869 Value *SelectCond = SI->getOperand(0);
2870
2871 // Change the div/rem to use 'Y' instead of the select.
2872 I.setOperand(1, SI->getOperand(NonNullOperand));
2873
2874 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2875 // problem. However, the select, or the condition of the select may have
2876 // multiple uses. Based on our knowledge that the operand must be non-zero,
2877 // propagate the known value for the select into other uses of it, and
2878 // propagate a known value of the condition into its other users.
2879
2880 // If the select and condition only have a single use, don't bother with this,
2881 // early exit.
2882 if (SI->use_empty() && SelectCond->hasOneUse())
2883 return true;
2884
2885 // Scan the current block backward, looking for other uses of SI.
2886 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2887
2888 while (BBI != BBFront) {
2889 --BBI;
2890 // If we found a call to a function, we can't assume it will return, so
2891 // information from below it cannot be propagated above it.
2892 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2893 break;
2894
2895 // Replace uses of the select or its condition with the known values.
2896 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2897 I != E; ++I) {
2898 if (*I == SI) {
2899 *I = SI->getOperand(NonNullOperand);
Chris Lattner3183fb62009-08-30 06:13:40 +00002900 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00002901 } else if (*I == SelectCond) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00002902 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2903 ConstantInt::getFalse(*Context);
Chris Lattner3183fb62009-08-30 06:13:40 +00002904 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00002905 }
2906 }
2907
2908 // If we past the instruction, quit looking for it.
2909 if (&*BBI == SI)
2910 SI = 0;
2911 if (&*BBI == SelectCond)
2912 SelectCond = 0;
2913
2914 // If we ran out of things to eliminate, break out of the loop.
2915 if (SelectCond == 0 && SI == 0)
2916 break;
2917
2918 }
2919 return true;
2920}
2921
2922
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002923/// This function implements the transforms on div instructions that work
2924/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2925/// used by the visitors to those instructions.
2926/// @brief Transforms common to all three div instructions
2927Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2928 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2929
Chris Lattner653ef3c2008-02-19 06:12:18 +00002930 // undef / X -> 0 for integer.
2931 // undef / X -> undef for FP (the undef could be a snan).
2932 if (isa<UndefValue>(Op0)) {
2933 if (Op0->getType()->isFPOrFPVector())
2934 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00002935 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002936 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002937
2938 // X / undef -> undef
2939 if (isa<UndefValue>(Op1))
2940 return ReplaceInstUsesWith(I, Op1);
2941
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002942 return 0;
2943}
2944
2945/// This function implements the transforms common to both integer division
2946/// instructions (udiv and sdiv). It is called by the visitors to those integer
2947/// division instructions.
2948/// @brief Common integer divide transforms
2949Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2950 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2951
Chris Lattnercefb36c2008-05-16 02:59:42 +00002952 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002953 if (Op0 == Op1) {
2954 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00002955 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002956 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00002957 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00002958 }
2959
Owen Andersoneacb44d2009-07-24 23:12:02 +00002960 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002961 return ReplaceInstUsesWith(I, CI);
2962 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002963
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002964 if (Instruction *Common = commonDivTransforms(I))
2965 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002966
2967 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2968 // This does not apply for fdiv.
2969 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2970 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002971
2972 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2973 // div X, 1 == X
2974 if (RHS->equalsInt(1))
2975 return ReplaceInstUsesWith(I, Op0);
2976
2977 // (X / C1) / C2 -> X / (C1*C2)
2978 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2979 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2980 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002981 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002982 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00002983 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00002984 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002985 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002986 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002987 }
2988
2989 if (!RHS->isZero()) { // avoid X udiv 0
2990 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2991 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2992 return R;
2993 if (isa<PHINode>(Op0))
2994 if (Instruction *NV = FoldOpIntoPhi(I))
2995 return NV;
2996 }
2997 }
2998
2999 // 0 / X == 0, we don't need to preserve faults!
3000 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3001 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00003002 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003003
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003004 // It can't be division by zero, hence it must be division by one.
Owen Anderson35b47072009-08-13 21:58:54 +00003005 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003006 return ReplaceInstUsesWith(I, Op0);
3007
Nick Lewycky94418732008-11-27 20:21:08 +00003008 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3009 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3010 // div X, 1 == X
3011 if (X->isOne())
3012 return ReplaceInstUsesWith(I, Op0);
3013 }
3014
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003015 return 0;
3016}
3017
3018Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3019 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3020
3021 // Handle the integer div common cases
3022 if (Instruction *Common = commonIDivTransforms(I))
3023 return Common;
3024
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003025 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00003026 // X udiv C^2 -> X >> C
3027 // Check to see if this is an unsigned division with an exact power of 2,
3028 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003029 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003030 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003031 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003032
3033 // X udiv C, where C >= signbit
3034 if (C->getValue().isNegative()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003035 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersonaac28372009-07-31 20:28:14 +00003036 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003037 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003038 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003039 }
3040
3041 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3042 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3043 if (RHSI->getOpcode() == Instruction::Shl &&
3044 isa<ConstantInt>(RHSI->getOperand(0))) {
3045 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3046 if (C1.isPowerOf2()) {
3047 Value *N = RHSI->getOperand(1);
3048 const Type *NTy = N->getType();
Chris Lattnerc7694852009-08-30 07:44:24 +00003049 if (uint32_t C2 = C1.logBase2())
3050 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003051 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003052 }
3053 }
3054 }
3055
3056 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3057 // where C1&C2 are powers of two.
3058 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3059 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3060 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3061 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3062 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3063 // Compute the shift amounts
3064 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3065 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003066 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003067 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003068
3069 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003070 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003071 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003072
3073 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003074 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003075 }
3076 }
3077 return 0;
3078}
3079
3080Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3081 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3082
3083 // Handle the integer div common cases
3084 if (Instruction *Common = commonIDivTransforms(I))
3085 return Common;
3086
3087 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3088 // sdiv X, -1 == -X
3089 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00003090 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00003091
Dan Gohman07878902009-08-12 16:33:09 +00003092 // sdiv X, C --> ashr X, log2(C)
Dan Gohman31b6b132009-08-11 20:47:47 +00003093 if (cast<SDivOperator>(&I)->isExact() &&
3094 RHS->getValue().isNonNegative() &&
3095 RHS->getValue().isPowerOf2()) {
3096 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3097 RHS->getValue().exactLogBase2());
3098 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3099 }
Dan Gohman5ce93b32009-08-12 16:37:02 +00003100
3101 // -X/C --> X/-C provided the negation doesn't overflow.
3102 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3103 if (isa<Constant>(Sub->getOperand(0)) &&
3104 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohmanb5ed4492009-08-20 17:11:38 +00003105 Sub->hasNoSignedWrap())
Dan Gohman5ce93b32009-08-12 16:37:02 +00003106 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3107 ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003108 }
3109
3110 // If the sign bits of both operands are zero (i.e. we can prove they are
3111 // unsigned inputs), turn this into a udiv.
3112 if (I.getType()->isInteger()) {
3113 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003114 if (MaskedValueIsZero(Op0, Mask)) {
3115 if (MaskedValueIsZero(Op1, Mask)) {
3116 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3117 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3118 }
3119 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00003120 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00003121 ShiftedInt->getValue().isPowerOf2()) {
3122 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3123 // Safe because the only negative value (1 << Y) can take on is
3124 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3125 // the sign bit set.
3126 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3127 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003128 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003129 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003130
3131 return 0;
3132}
3133
3134Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3135 return commonDivTransforms(I);
3136}
3137
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003138/// This function implements the transforms on rem instructions that work
3139/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3140/// is used by the visitors to those instructions.
3141/// @brief Transforms common to all three rem instructions
3142Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3143 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3144
Chris Lattner653ef3c2008-02-19 06:12:18 +00003145 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3146 if (I.getType()->isFPOrFPVector())
3147 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00003148 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003149 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003150 if (isa<UndefValue>(Op1))
3151 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3152
3153 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003154 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3155 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003156
3157 return 0;
3158}
3159
3160/// This function implements the transforms common to both integer remainder
3161/// instructions (urem and srem). It is called by the visitors to those integer
3162/// remainder instructions.
3163/// @brief Common integer remainder transforms
3164Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3165 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3166
3167 if (Instruction *common = commonRemTransforms(I))
3168 return common;
3169
Dale Johannesena51f7372009-01-21 00:35:19 +00003170 // 0 % X == 0 for integer, we don't need to preserve faults!
3171 if (Constant *LHS = dyn_cast<Constant>(Op0))
3172 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00003173 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003174
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003175 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3176 // X % 0 == undef, we don't need to preserve faults!
3177 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003178 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003179
3180 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003181 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003182
3183 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3184 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3185 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3186 return R;
3187 } else if (isa<PHINode>(Op0I)) {
3188 if (Instruction *NV = FoldOpIntoPhi(I))
3189 return NV;
3190 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003191
3192 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003193 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003194 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003195 }
3196 }
3197
3198 return 0;
3199}
3200
3201Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3202 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3203
3204 if (Instruction *common = commonIRemTransforms(I))
3205 return common;
3206
3207 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3208 // X urem C^2 -> X and C
3209 // Check to see if this is an unsigned remainder with an exact power of 2,
3210 // if so, convert to a bitwise and.
3211 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3212 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003213 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003214 }
3215
3216 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3217 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3218 if (RHSI->getOpcode() == Instruction::Shl &&
3219 isa<ConstantInt>(RHSI->getOperand(0))) {
3220 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00003221 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00003222 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003223 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003224 }
3225 }
3226 }
3227
3228 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3229 // where C1&C2 are powers of two.
3230 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3231 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3232 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3233 // STO == 0 and SFO == 0 handled above.
3234 if ((STO->getValue().isPowerOf2()) &&
3235 (SFO->getValue().isPowerOf2())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003236 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3237 SI->getName()+".t");
3238 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3239 SI->getName()+".f");
Gabor Greifd6da1d02008-04-06 20:25:17 +00003240 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003241 }
3242 }
3243 }
3244
3245 return 0;
3246}
3247
3248Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3249 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3250
Dan Gohmandb3dd962007-11-05 23:16:33 +00003251 // Handle the integer rem common cases
Chris Lattner4796b622009-08-30 06:22:51 +00003252 if (Instruction *Common = commonIRemTransforms(I))
3253 return Common;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003254
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003255 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003256 if (!isa<Constant>(RHSNeg) ||
3257 (isa<ConstantInt>(RHSNeg) &&
3258 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003259 // X % -Y -> X % Y
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003260 Worklist.AddValue(I.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003261 I.setOperand(1, RHSNeg);
3262 return &I;
3263 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003264
Dan Gohmandb3dd962007-11-05 23:16:33 +00003265 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003266 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003267 if (I.getType()->isInteger()) {
3268 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3269 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3270 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003271 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003272 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003273 }
3274
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003275 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003276 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3277 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003278
Nick Lewyckyfd746832008-12-20 16:48:00 +00003279 bool hasNegative = false;
3280 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3281 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3282 if (RHS->getValue().isNegative())
3283 hasNegative = true;
3284
3285 if (hasNegative) {
3286 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003287 for (unsigned i = 0; i != VWidth; ++i) {
3288 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3289 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00003290 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003291 else
3292 Elts[i] = RHS;
3293 }
3294 }
3295
Owen Anderson2f422e02009-07-28 21:19:26 +00003296 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003297 if (NewRHSV != RHSV) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003298 Worklist.AddValue(I.getOperand(1));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003299 I.setOperand(1, NewRHSV);
3300 return &I;
3301 }
3302 }
3303 }
3304
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003305 return 0;
3306}
3307
3308Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3309 return commonRemTransforms(I);
3310}
3311
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003312// isOneBitSet - Return true if there is exactly one bit set in the specified
3313// constant.
3314static bool isOneBitSet(const ConstantInt *CI) {
3315 return CI->getValue().isPowerOf2();
3316}
3317
3318// isHighOnes - Return true if the constant is of the form 1+0+.
3319// This is the same as lowones(~X).
3320static bool isHighOnes(const ConstantInt *CI) {
3321 return (~CI->getValue() + 1).isPowerOf2();
3322}
3323
3324/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3325/// are carefully arranged to allow folding of expressions such as:
3326///
3327/// (A < B) | (A > B) --> (A != B)
3328///
3329/// Note that this is only valid if the first and second predicates have the
3330/// same sign. Is illegal to do: (A u< B) | (A s> B)
3331///
3332/// Three bits are used to represent the condition, as follows:
3333/// 0 A > B
3334/// 1 A == B
3335/// 2 A < B
3336///
3337/// <=> Value Definition
3338/// 000 0 Always false
3339/// 001 1 A > B
3340/// 010 2 A == B
3341/// 011 3 A >= B
3342/// 100 4 A < B
3343/// 101 5 A != B
3344/// 110 6 A <= B
3345/// 111 7 Always true
3346///
3347static unsigned getICmpCode(const ICmpInst *ICI) {
3348 switch (ICI->getPredicate()) {
3349 // False -> 0
3350 case ICmpInst::ICMP_UGT: return 1; // 001
3351 case ICmpInst::ICMP_SGT: return 1; // 001
3352 case ICmpInst::ICMP_EQ: return 2; // 010
3353 case ICmpInst::ICMP_UGE: return 3; // 011
3354 case ICmpInst::ICMP_SGE: return 3; // 011
3355 case ICmpInst::ICMP_ULT: return 4; // 100
3356 case ICmpInst::ICMP_SLT: return 4; // 100
3357 case ICmpInst::ICMP_NE: return 5; // 101
3358 case ICmpInst::ICMP_ULE: return 6; // 110
3359 case ICmpInst::ICMP_SLE: return 6; // 110
3360 // True -> 7
3361 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003362 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003363 return 0;
3364 }
3365}
3366
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003367/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3368/// predicate into a three bit mask. It also returns whether it is an ordered
3369/// predicate by reference.
3370static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3371 isOrdered = false;
3372 switch (CC) {
3373 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3374 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003375 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3376 case FCmpInst::FCMP_UGT: return 1; // 001
3377 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3378 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003379 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3380 case FCmpInst::FCMP_UGE: return 3; // 011
3381 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3382 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003383 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3384 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003385 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3386 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003387 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003388 default:
3389 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003390 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003391 return 0;
3392 }
3393}
3394
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003395/// getICmpValue - This is the complement of getICmpCode, which turns an
3396/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003397/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003398/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003399static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003400 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003401 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003402 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson4f720fa2009-07-31 17:39:07 +00003403 case 0: return ConstantInt::getFalse(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003404 case 1:
3405 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003406 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003407 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003408 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3409 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003410 case 3:
3411 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003412 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003413 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003414 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003415 case 4:
3416 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003417 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003418 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003419 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3420 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003421 case 6:
3422 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003423 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003424 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003425 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003426 case 7: return ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003427 }
3428}
3429
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003430/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3431/// opcode and two operands into either a FCmp instruction. isordered is passed
3432/// in to determine which kind of predicate to use in the new fcmp instruction.
3433static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003434 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003435 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003436 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003437 case 0:
3438 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003439 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003440 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003441 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003442 case 1:
3443 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003444 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003445 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003446 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003447 case 2:
3448 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003449 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003450 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003451 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003452 case 3:
3453 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003454 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003455 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003456 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003457 case 4:
3458 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003459 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003460 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003461 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003462 case 5:
3463 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003464 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003465 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003466 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003467 case 6:
3468 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003469 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003470 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003471 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003472 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003473 }
3474}
3475
Chris Lattner2972b822008-11-16 04:55:20 +00003476/// PredicatesFoldable - Return true if both predicates match sign or if at
3477/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003478static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3479 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattner2972b822008-11-16 04:55:20 +00003480 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3481 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003482}
3483
3484namespace {
3485// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3486struct FoldICmpLogical {
3487 InstCombiner &IC;
3488 Value *LHS, *RHS;
3489 ICmpInst::Predicate pred;
3490 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3491 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3492 pred(ICI->getPredicate()) {}
3493 bool shouldApply(Value *V) const {
3494 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3495 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003496 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3497 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003498 return false;
3499 }
3500 Instruction *apply(Instruction &Log) const {
3501 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3502 if (ICI->getOperand(0) != LHS) {
3503 assert(ICI->getOperand(1) == LHS);
3504 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3505 }
3506
3507 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3508 unsigned LHSCode = getICmpCode(ICI);
3509 unsigned RHSCode = getICmpCode(RHSICI);
3510 unsigned Code;
3511 switch (Log.getOpcode()) {
3512 case Instruction::And: Code = LHSCode & RHSCode; break;
3513 case Instruction::Or: Code = LHSCode | RHSCode; break;
3514 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003515 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003516 }
3517
3518 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3519 ICmpInst::isSignedPredicate(ICI->getPredicate());
3520
Owen Anderson24be4c12009-07-03 00:17:18 +00003521 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003522 if (Instruction *I = dyn_cast<Instruction>(RV))
3523 return I;
3524 // Otherwise, it's a constant boolean value...
3525 return IC.ReplaceInstUsesWith(Log, RV);
3526 }
3527};
3528} // end anonymous namespace
3529
3530// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3531// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3532// guaranteed to be a binary operator.
3533Instruction *InstCombiner::OptAndOp(Instruction *Op,
3534 ConstantInt *OpRHS,
3535 ConstantInt *AndRHS,
3536 BinaryOperator &TheAnd) {
3537 Value *X = Op->getOperand(0);
3538 Constant *Together = 0;
3539 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00003540 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003541
3542 switch (Op->getOpcode()) {
3543 case Instruction::Xor:
3544 if (Op->hasOneUse()) {
3545 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattnerc7694852009-08-30 07:44:24 +00003546 Value *And = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003547 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003548 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003549 }
3550 break;
3551 case Instruction::Or:
3552 if (Together == AndRHS) // (X | C) & C --> C
3553 return ReplaceInstUsesWith(TheAnd, AndRHS);
3554
3555 if (Op->hasOneUse() && Together != OpRHS) {
3556 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattnerc7694852009-08-30 07:44:24 +00003557 Value *Or = Builder->CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003558 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003559 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003560 }
3561 break;
3562 case Instruction::Add:
3563 if (Op->hasOneUse()) {
3564 // Adding a one to a single bit bit-field should be turned into an XOR
3565 // of the bit. First thing to check is to see if this AND is with a
3566 // single bit constant.
3567 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3568
3569 // If there is only one bit set...
3570 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3571 // Ok, at this point, we know that we are masking the result of the
3572 // ADD down to exactly one bit. If the constant we are adding has
3573 // no bits set below this bit, then we can eliminate the ADD.
3574 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3575
3576 // Check to see if any bits below the one bit set in AndRHSV are set.
3577 if ((AddRHS & (AndRHSV-1)) == 0) {
3578 // If not, the only thing that can effect the output of the AND is
3579 // the bit specified by AndRHSV. If that bit is set, the effect of
3580 // the XOR is to toggle the bit. If it is clear, then the ADD has
3581 // no effect.
3582 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3583 TheAnd.setOperand(0, X);
3584 return &TheAnd;
3585 } else {
3586 // Pull the XOR out of the AND.
Chris Lattnerc7694852009-08-30 07:44:24 +00003587 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003588 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003589 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003590 }
3591 }
3592 }
3593 }
3594 break;
3595
3596 case Instruction::Shl: {
3597 // We know that the AND will not produce any of the bits shifted in, so if
3598 // the anded constant includes them, clear them now!
3599 //
3600 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3601 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3602 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003603 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003604
3605 if (CI->getValue() == ShlMask) {
3606 // Masking out bits that the shift already masks
3607 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3608 } else if (CI != AndRHS) { // Reducing bits set in and.
3609 TheAnd.setOperand(1, CI);
3610 return &TheAnd;
3611 }
3612 break;
3613 }
3614 case Instruction::LShr:
3615 {
3616 // We know that the AND will not produce any of the bits shifted in, so if
3617 // the anded constant includes them, clear them now! This only applies to
3618 // unsigned shifts, because a signed shr may bring in set bits!
3619 //
3620 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3621 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3622 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003623 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003624
3625 if (CI->getValue() == ShrMask) {
3626 // Masking out bits that the shift already masks.
3627 return ReplaceInstUsesWith(TheAnd, Op);
3628 } else if (CI != AndRHS) {
3629 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3630 return &TheAnd;
3631 }
3632 break;
3633 }
3634 case Instruction::AShr:
3635 // Signed shr.
3636 // See if this is shifting in some sign extension, then masking it out
3637 // with an and.
3638 if (Op->hasOneUse()) {
3639 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3640 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3641 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003642 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003643 if (C == AndRHS) { // Masking out bits shifted in.
3644 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3645 // Make the argument unsigned.
3646 Value *ShVal = Op->getOperand(0);
Chris Lattnerc7694852009-08-30 07:44:24 +00003647 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003648 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003649 }
3650 }
3651 break;
3652 }
3653 return 0;
3654}
3655
3656
3657/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3658/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3659/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3660/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3661/// insert new instructions.
3662Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3663 bool isSigned, bool Inside,
3664 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003665 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003666 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3667 "Lo is not <= Hi in range emission code!");
3668
3669 if (Inside) {
3670 if (Lo == Hi) // Trivially false.
Dan Gohmane6803b82009-08-25 23:17:54 +00003671 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003672
3673 // V >= Min && V < Hi --> V < Hi
3674 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3675 ICmpInst::Predicate pred = (isSigned ?
3676 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003677 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003678 }
3679
3680 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00003681 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattnerc7694852009-08-30 07:44:24 +00003682 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003683 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003684 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003685 }
3686
3687 if (Lo == Hi) // Trivially true.
Dan Gohmane6803b82009-08-25 23:17:54 +00003688 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003689
3690 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003691 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003692 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3693 ICmpInst::Predicate pred = (isSigned ?
3694 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003695 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003696 }
3697
3698 // Emit V-Lo >u Hi-1-Lo
3699 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00003700 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattnerc7694852009-08-30 07:44:24 +00003701 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003702 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003703 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003704}
3705
3706// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3707// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3708// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3709// not, since all 1s are not contiguous.
3710static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3711 const APInt& V = Val->getValue();
3712 uint32_t BitWidth = Val->getType()->getBitWidth();
3713 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3714
3715 // look for the first zero bit after the run of ones
3716 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3717 // look for the first non-zero bit
3718 ME = V.getActiveBits();
3719 return true;
3720}
3721
3722/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3723/// where isSub determines whether the operator is a sub. If we can fold one of
3724/// the following xforms:
3725///
3726/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3727/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3728/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3729///
3730/// return (A +/- B).
3731///
3732Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3733 ConstantInt *Mask, bool isSub,
3734 Instruction &I) {
3735 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3736 if (!LHSI || LHSI->getNumOperands() != 2 ||
3737 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3738
3739 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3740
3741 switch (LHSI->getOpcode()) {
3742 default: return 0;
3743 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00003744 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003745 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3746 if ((Mask->getValue().countLeadingZeros() +
3747 Mask->getValue().countPopulation()) ==
3748 Mask->getValue().getBitWidth())
3749 break;
3750
3751 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3752 // part, we don't need any explicit masks to take them out of A. If that
3753 // is all N is, ignore it.
3754 uint32_t MB = 0, ME = 0;
3755 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3756 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3757 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3758 if (MaskedValueIsZero(RHS, Mask))
3759 break;
3760 }
3761 }
3762 return 0;
3763 case Instruction::Or:
3764 case Instruction::Xor:
3765 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3766 if ((Mask->getValue().countLeadingZeros() +
3767 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00003768 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003769 break;
3770 return 0;
3771 }
3772
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003773 if (isSub)
Chris Lattnerc7694852009-08-30 07:44:24 +00003774 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3775 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003776}
3777
Chris Lattner0631ea72008-11-16 05:06:21 +00003778/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3779Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3780 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00003781 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00003782 ConstantInt *LHSCst, *RHSCst;
3783 ICmpInst::Predicate LHSCC, RHSCC;
3784
Chris Lattnerf3803482008-11-16 05:10:52 +00003785 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00003786 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00003787 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00003788 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00003789 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00003790 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003791
3792 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3793 // where C is a power of 2
3794 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3795 LHSCst->getValue().isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003796 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohmane6803b82009-08-25 23:17:54 +00003797 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerf3803482008-11-16 05:10:52 +00003798 }
3799
3800 // From here on, we only handle:
3801 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3802 if (Val != Val2) return 0;
3803
Chris Lattner0631ea72008-11-16 05:06:21 +00003804 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3805 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3806 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3807 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3808 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3809 return 0;
3810
3811 // We can't fold (ugt x, C) & (sgt x, C2).
3812 if (!PredicatesFoldable(LHSCC, RHSCC))
3813 return 0;
3814
3815 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003816 bool ShouldSwap;
Chris Lattner0631ea72008-11-16 05:06:21 +00003817 if (ICmpInst::isSignedPredicate(LHSCC) ||
3818 (ICmpInst::isEquality(LHSCC) &&
3819 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003820 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003821 else
Chris Lattner665298f2008-11-16 05:14:43 +00003822 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3823
3824 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003825 std::swap(LHS, RHS);
3826 std::swap(LHSCst, RHSCst);
3827 std::swap(LHSCC, RHSCC);
3828 }
3829
3830 // At this point, we know we have have two icmp instructions
3831 // comparing a value against two constants and and'ing the result
3832 // together. Because of the above check, we know that we only have
3833 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3834 // (from the FoldICmpLogical check above), that the two constants
3835 // are not equal and that the larger constant is on the RHS
3836 assert(LHSCst != RHSCst && "Compares not folded above?");
3837
3838 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003839 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003840 case ICmpInst::ICMP_EQ:
3841 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003842 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003843 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3844 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3845 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003846 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003847 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3848 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3849 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3850 return ReplaceInstUsesWith(I, LHS);
3851 }
3852 case ICmpInst::ICMP_NE:
3853 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003854 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003855 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003856 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00003857 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003858 break; // (X != 13 & X u< 15) -> no change
3859 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003860 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00003861 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003862 break; // (X != 13 & X s< 15) -> no change
3863 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3864 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3865 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3866 return ReplaceInstUsesWith(I, RHS);
3867 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003868 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00003869 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00003870 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmane6803b82009-08-25 23:17:54 +00003871 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003872 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00003873 }
3874 break; // (X != 13 & X != 15) -> no change
3875 }
3876 break;
3877 case ICmpInst::ICMP_ULT:
3878 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003879 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003880 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3881 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003882 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003883 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3884 break;
3885 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3886 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3887 return ReplaceInstUsesWith(I, LHS);
3888 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3889 break;
3890 }
3891 break;
3892 case ICmpInst::ICMP_SLT:
3893 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003894 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003895 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3896 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003897 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003898 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3899 break;
3900 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3901 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3902 return ReplaceInstUsesWith(I, LHS);
3903 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3904 break;
3905 }
3906 break;
3907 case ICmpInst::ICMP_UGT:
3908 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003909 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003910 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3911 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3912 return ReplaceInstUsesWith(I, RHS);
3913 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3914 break;
3915 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003916 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00003917 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003918 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003919 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003920 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003921 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003922 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3923 break;
3924 }
3925 break;
3926 case ICmpInst::ICMP_SGT:
3927 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003928 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003929 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3930 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3931 return ReplaceInstUsesWith(I, RHS);
3932 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3933 break;
3934 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003935 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00003936 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003937 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003938 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003939 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003940 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003941 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3942 break;
3943 }
3944 break;
3945 }
Chris Lattner0631ea72008-11-16 05:06:21 +00003946
3947 return 0;
3948}
3949
Chris Lattner93a359a2009-07-23 05:14:02 +00003950Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3951 FCmpInst *RHS) {
3952
3953 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3954 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3955 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3956 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3957 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3958 // If either of the constants are nans, then the whole thing returns
3959 // false.
3960 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00003961 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00003962 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner93a359a2009-07-23 05:14:02 +00003963 LHS->getOperand(0), RHS->getOperand(0));
3964 }
Chris Lattnercf373552009-07-23 05:32:17 +00003965
3966 // Handle vector zeros. This occurs because the canonical form of
3967 // "fcmp ord x,x" is "fcmp ord x, 0".
3968 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3969 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00003970 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnercf373552009-07-23 05:32:17 +00003971 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00003972 return 0;
3973 }
3974
3975 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3976 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3977 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3978
3979
3980 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3981 // Swap RHS operands to match LHS.
3982 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3983 std::swap(Op1LHS, Op1RHS);
3984 }
3985
3986 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3987 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3988 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00003989 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +00003990
3991 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00003992 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00003993 if (Op0CC == FCmpInst::FCMP_TRUE)
3994 return ReplaceInstUsesWith(I, RHS);
3995 if (Op1CC == FCmpInst::FCMP_TRUE)
3996 return ReplaceInstUsesWith(I, LHS);
3997
3998 bool Op0Ordered;
3999 bool Op1Ordered;
4000 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4001 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4002 if (Op1Pred == 0) {
4003 std::swap(LHS, RHS);
4004 std::swap(Op0Pred, Op1Pred);
4005 std::swap(Op0Ordered, Op1Ordered);
4006 }
4007 if (Op0Pred == 0) {
4008 // uno && ueq -> uno && (uno || eq) -> ueq
4009 // ord && olt -> ord && (ord && lt) -> olt
4010 if (Op0Ordered == Op1Ordered)
4011 return ReplaceInstUsesWith(I, RHS);
4012
4013 // uno && oeq -> uno && (ord && eq) -> false
4014 // uno && ord -> false
4015 if (!Op0Ordered)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004016 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004017 // ord && ueq -> ord && (uno || eq) -> oeq
4018 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4019 Op0LHS, Op0RHS, Context));
4020 }
4021 }
4022
4023 return 0;
4024}
4025
Chris Lattner0631ea72008-11-16 05:06:21 +00004026
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004027Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4028 bool Changed = SimplifyCommutative(I);
4029 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4030
4031 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00004032 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004033
4034 // and X, X = X
4035 if (Op0 == Op1)
4036 return ReplaceInstUsesWith(I, Op1);
4037
4038 // See if we can simplify any instructions used by the instruction whose sole
4039 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004040 if (SimplifyDemandedInstructionBits(I))
4041 return &I;
4042 if (isa<VectorType>(I.getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004043 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4044 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4045 return ReplaceInstUsesWith(I, I.getOperand(0));
4046 } else if (isa<ConstantAggregateZero>(Op1)) {
4047 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4048 }
4049 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00004050
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004051 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4052 const APInt& AndRHSMask = AndRHS->getValue();
4053 APInt NotAndRHS(~AndRHSMask);
4054
4055 // Optimize a variety of ((val OP C1) & C2) combinations...
4056 if (isa<BinaryOperator>(Op0)) {
4057 Instruction *Op0I = cast<Instruction>(Op0);
4058 Value *Op0LHS = Op0I->getOperand(0);
4059 Value *Op0RHS = Op0I->getOperand(1);
4060 switch (Op0I->getOpcode()) {
4061 case Instruction::Xor:
4062 case Instruction::Or:
4063 // If the mask is only needed on one incoming arm, push it up.
4064 if (Op0I->hasOneUse()) {
4065 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4066 // Not masking anything out for the LHS, move to RHS.
Chris Lattnerc7694852009-08-30 07:44:24 +00004067 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4068 Op0RHS->getName()+".masked");
Gabor Greifa645dd32008-05-16 19:29:10 +00004069 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004070 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4071 }
4072 if (!isa<Constant>(Op0RHS) &&
4073 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4074 // Not masking anything out for the RHS, move to LHS.
Chris Lattnerc7694852009-08-30 07:44:24 +00004075 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4076 Op0LHS->getName()+".masked");
Gabor Greifa645dd32008-05-16 19:29:10 +00004077 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004078 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4079 }
4080 }
4081
4082 break;
4083 case Instruction::Add:
4084 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4085 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4086 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4087 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004088 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004089 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004090 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004091 break;
4092
4093 case Instruction::Sub:
4094 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4095 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4096 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4097 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004098 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004099
Nick Lewyckya349ba42008-07-10 05:51:40 +00004100 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4101 // has 1's for all bits that the subtraction with A might affect.
4102 if (Op0I->hasOneUse()) {
4103 uint32_t BitWidth = AndRHSMask.getBitWidth();
4104 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4105 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4106
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004107 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004108 if (!(A && A->isZero()) && // avoid infinite recursion.
4109 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004110 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004111 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4112 }
4113 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004114 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004115
4116 case Instruction::Shl:
4117 case Instruction::LShr:
4118 // (1 << x) & 1 --> zext(x == 0)
4119 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004120 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004121 Value *NewICmp =
4122 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004123 return new ZExtInst(NewICmp, I.getType());
4124 }
4125 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004126 }
4127
4128 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4129 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4130 return Res;
4131 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4132 // If this is an integer truncation or change from signed-to-unsigned, and
4133 // if the source is an and/or with immediate, transform it. This
4134 // frequently occurs for bitfield accesses.
4135 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4136 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4137 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004138 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004139 if (CastOp->getOpcode() == Instruction::And) {
4140 // Change: and (cast (and X, C1) to T), C2
4141 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4142 // This will fold the two constants together, which may allow
4143 // other simplifications.
Chris Lattnerc7694852009-08-30 07:44:24 +00004144 Value *NewCast = Builder->CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004145 CastOp->getOperand(0), I.getType(),
4146 CastOp->getName()+".shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004147 // trunc_or_bitcast(C1)&C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004148 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004149 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004150 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004151 } else if (CastOp->getOpcode() == Instruction::Or) {
4152 // Change: and (cast (or X, C1) to T), C2
4153 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004154 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004155 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00004156 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004157 return ReplaceInstUsesWith(I, AndRHS);
4158 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004159 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004160 }
4161 }
4162
4163 // Try to fold constant and into select arguments.
4164 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4165 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4166 return R;
4167 if (isa<PHINode>(Op0))
4168 if (Instruction *NV = FoldOpIntoPhi(I))
4169 return NV;
4170 }
4171
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004172 Value *Op0NotVal = dyn_castNotVal(Op0);
4173 Value *Op1NotVal = dyn_castNotVal(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004174
4175 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersonaac28372009-07-31 20:28:14 +00004176 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004177
4178 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4179 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004180 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4181 I.getName()+".demorgan");
Dan Gohmancdff2122009-08-12 16:23:25 +00004182 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004183 }
4184
4185 {
4186 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004187 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004188 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4189 return ReplaceInstUsesWith(I, Op1);
4190
4191 // (A|B) & ~(A&B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004192 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004193 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004194 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004195 }
4196 }
4197
Dan Gohmancdff2122009-08-12 16:23:25 +00004198 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004199 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4200 return ReplaceInstUsesWith(I, Op0);
4201
4202 // ~(A&B) & (A|B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004203 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004204 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004205 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004206 }
4207 }
4208
4209 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004210 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004211 if (A == Op1) { // (A^B)&A -> A&(A^B)
4212 I.swapOperands(); // Simplify below
4213 std::swap(Op0, Op1);
4214 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4215 cast<BinaryOperator>(Op0)->swapOperands();
4216 I.swapOperands(); // Simplify below
4217 std::swap(Op0, Op1);
4218 }
4219 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004220
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004221 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004222 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004223 if (B == Op0) { // B&(A^B) -> B&(B^A)
4224 cast<BinaryOperator>(Op1)->swapOperands();
4225 std::swap(A, B);
4226 }
Chris Lattnerc7694852009-08-30 07:44:24 +00004227 if (A == Op0) // A&(A^B) -> A & ~B
4228 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004229 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004230
4231 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00004232 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4233 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004234 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004235 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4236 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004237 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004238 }
4239
4240 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4241 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004242 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004243 return R;
4244
Chris Lattner0631ea72008-11-16 05:06:21 +00004245 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4246 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4247 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004248 }
4249
4250 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4251 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4252 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4253 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4254 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004255 if (SrcTy == Op1C->getOperand(0)->getType() &&
4256 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004257 // Only do this if the casts both really cause code to be generated.
4258 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4259 I.getType(), TD) &&
4260 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4261 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004262 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4263 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004264 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004265 }
4266 }
4267
4268 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4269 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4270 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4271 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4272 SI0->getOperand(1) == SI1->getOperand(1) &&
4273 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004274 Value *NewOp =
4275 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4276 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004277 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004278 SI1->getOperand(1));
4279 }
4280 }
4281
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004282 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004283 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004284 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4285 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4286 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004287 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004288
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004289 return Changed ? &I : 0;
4290}
4291
Chris Lattner567f5112008-10-05 02:13:19 +00004292/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4293/// capable of providing pieces of a bswap. The subexpression provides pieces
4294/// of a bswap if it is proven that each of the non-zero bytes in the output of
4295/// the expression came from the corresponding "byte swapped" byte in some other
4296/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4297/// we know that the expression deposits the low byte of %X into the high byte
4298/// of the bswap result and that all other bytes are zero. This expression is
4299/// accepted, the high byte of ByteValues is set to X to indicate a correct
4300/// match.
4301///
4302/// This function returns true if the match was unsuccessful and false if so.
4303/// On entry to the function the "OverallLeftShift" is a signed integer value
4304/// indicating the number of bytes that the subexpression is later shifted. For
4305/// example, if the expression is later right shifted by 16 bits, the
4306/// OverallLeftShift value would be -2 on entry. This is used to specify which
4307/// byte of ByteValues is actually being set.
4308///
4309/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4310/// byte is masked to zero by a user. For example, in (X & 255), X will be
4311/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4312/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4313/// always in the local (OverallLeftShift) coordinate space.
4314///
4315static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4316 SmallVector<Value*, 8> &ByteValues) {
4317 if (Instruction *I = dyn_cast<Instruction>(V)) {
4318 // If this is an or instruction, it may be an inner node of the bswap.
4319 if (I->getOpcode() == Instruction::Or) {
4320 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4321 ByteValues) ||
4322 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4323 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004324 }
Chris Lattner567f5112008-10-05 02:13:19 +00004325
4326 // If this is a logical shift by a constant multiple of 8, recurse with
4327 // OverallLeftShift and ByteMask adjusted.
4328 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4329 unsigned ShAmt =
4330 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4331 // Ensure the shift amount is defined and of a byte value.
4332 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4333 return true;
4334
4335 unsigned ByteShift = ShAmt >> 3;
4336 if (I->getOpcode() == Instruction::Shl) {
4337 // X << 2 -> collect(X, +2)
4338 OverallLeftShift += ByteShift;
4339 ByteMask >>= ByteShift;
4340 } else {
4341 // X >>u 2 -> collect(X, -2)
4342 OverallLeftShift -= ByteShift;
4343 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004344 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004345 }
4346
4347 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4348 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4349
4350 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4351 ByteValues);
4352 }
4353
4354 // If this is a logical 'and' with a mask that clears bytes, clear the
4355 // corresponding bytes in ByteMask.
4356 if (I->getOpcode() == Instruction::And &&
4357 isa<ConstantInt>(I->getOperand(1))) {
4358 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4359 unsigned NumBytes = ByteValues.size();
4360 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4361 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4362
4363 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4364 // If this byte is masked out by a later operation, we don't care what
4365 // the and mask is.
4366 if ((ByteMask & (1 << i)) == 0)
4367 continue;
4368
4369 // If the AndMask is all zeros for this byte, clear the bit.
4370 APInt MaskB = AndMask & Byte;
4371 if (MaskB == 0) {
4372 ByteMask &= ~(1U << i);
4373 continue;
4374 }
4375
4376 // If the AndMask is not all ones for this byte, it's not a bytezap.
4377 if (MaskB != Byte)
4378 return true;
4379
4380 // Otherwise, this byte is kept.
4381 }
4382
4383 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4384 ByteValues);
4385 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004386 }
4387
Chris Lattner567f5112008-10-05 02:13:19 +00004388 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4389 // the input value to the bswap. Some observations: 1) if more than one byte
4390 // is demanded from this input, then it could not be successfully assembled
4391 // into a byteswap. At least one of the two bytes would not be aligned with
4392 // their ultimate destination.
4393 if (!isPowerOf2_32(ByteMask)) return true;
4394 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004395
Chris Lattner567f5112008-10-05 02:13:19 +00004396 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4397 // is demanded, it needs to go into byte 0 of the result. This means that the
4398 // byte needs to be shifted until it lands in the right byte bucket. The
4399 // shift amount depends on the position: if the byte is coming from the high
4400 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4401 // low part, it must be shifted left.
4402 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4403 if (InputByteNo < ByteValues.size()/2) {
4404 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4405 return true;
4406 } else {
4407 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4408 return true;
4409 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004410
4411 // If the destination byte value is already defined, the values are or'd
4412 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004413 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004414 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004415 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004416 return false;
4417}
4418
4419/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4420/// If so, insert the new bswap intrinsic and return it.
4421Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4422 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004423 if (!ITy || ITy->getBitWidth() % 16 ||
4424 // ByteMask only allows up to 32-byte values.
4425 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004426 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4427
4428 /// ByteValues - For each byte of the result, we keep track of which value
4429 /// defines each byte.
4430 SmallVector<Value*, 8> ByteValues;
4431 ByteValues.resize(ITy->getBitWidth()/8);
4432
4433 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004434 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4435 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004436 return 0;
4437
4438 // Check to see if all of the bytes come from the same value.
4439 Value *V = ByteValues[0];
4440 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4441
4442 // Check to make sure that all of the bytes come from the same value.
4443 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4444 if (ByteValues[i] != V)
4445 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004446 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004447 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004448 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004449 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004450}
4451
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004452/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4453/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4454/// we can simplify this expression to "cond ? C : D or B".
4455static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004456 Value *C, Value *D,
4457 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004458 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004459 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004460 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004461 return 0;
4462
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004463 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00004464 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004465 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00004466 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004467 return SelectInst::Create(Cond, C, B);
4468 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00004469 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004470 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00004471 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004472 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004473 return 0;
4474}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004475
Chris Lattner0c678e52008-11-16 05:20:07 +00004476/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4477Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4478 ICmpInst *LHS, ICmpInst *RHS) {
4479 Value *Val, *Val2;
4480 ConstantInt *LHSCst, *RHSCst;
4481 ICmpInst::Predicate LHSCC, RHSCC;
4482
4483 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004484 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004485 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004486 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004487 m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00004488 return 0;
4489
4490 // From here on, we only handle:
4491 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4492 if (Val != Val2) return 0;
4493
4494 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4495 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4496 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4497 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4498 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4499 return 0;
4500
4501 // We can't fold (ugt x, C) | (sgt x, C2).
4502 if (!PredicatesFoldable(LHSCC, RHSCC))
4503 return 0;
4504
4505 // Ensure that the larger constant is on the RHS.
4506 bool ShouldSwap;
4507 if (ICmpInst::isSignedPredicate(LHSCC) ||
4508 (ICmpInst::isEquality(LHSCC) &&
4509 ICmpInst::isSignedPredicate(RHSCC)))
4510 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4511 else
4512 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4513
4514 if (ShouldSwap) {
4515 std::swap(LHS, RHS);
4516 std::swap(LHSCst, RHSCst);
4517 std::swap(LHSCC, RHSCC);
4518 }
4519
4520 // At this point, we know we have have two icmp instructions
4521 // comparing a value against two constants and or'ing the result
4522 // together. Because of the above check, we know that we only have
4523 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4524 // FoldICmpLogical check above), that the two constants are not
4525 // equal.
4526 assert(LHSCst != RHSCst && "Compares not folded above?");
4527
4528 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004529 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004530 case ICmpInst::ICMP_EQ:
4531 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004532 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004533 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004534 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004535 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00004536 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004537 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004538 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohmane6803b82009-08-25 23:17:54 +00004539 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004540 }
4541 break; // (X == 13 | X == 15) -> no change
4542 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4543 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4544 break;
4545 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4546 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4547 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4548 return ReplaceInstUsesWith(I, RHS);
4549 }
4550 break;
4551 case ICmpInst::ICMP_NE:
4552 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004553 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004554 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4555 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4556 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4557 return ReplaceInstUsesWith(I, LHS);
4558 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4559 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4560 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004561 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004562 }
4563 break;
4564 case ICmpInst::ICMP_ULT:
4565 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004566 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004567 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4568 break;
4569 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4570 // If RHSCst is [us]MAXINT, it is always false. Not handling
4571 // this can cause overflow.
4572 if (RHSCst->isMaxValue(false))
4573 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004574 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004575 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004576 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4577 break;
4578 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4579 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4580 return ReplaceInstUsesWith(I, RHS);
4581 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4582 break;
4583 }
4584 break;
4585 case ICmpInst::ICMP_SLT:
4586 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004587 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004588 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4589 break;
4590 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4591 // If RHSCst is [us]MAXINT, it is always false. Not handling
4592 // this can cause overflow.
4593 if (RHSCst->isMaxValue(true))
4594 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004595 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004596 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004597 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4598 break;
4599 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4600 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4601 return ReplaceInstUsesWith(I, RHS);
4602 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4603 break;
4604 }
4605 break;
4606 case ICmpInst::ICMP_UGT:
4607 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004608 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004609 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4610 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4611 return ReplaceInstUsesWith(I, LHS);
4612 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4613 break;
4614 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4615 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004616 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004617 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4618 break;
4619 }
4620 break;
4621 case ICmpInst::ICMP_SGT:
4622 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004623 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004624 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4625 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4626 return ReplaceInstUsesWith(I, LHS);
4627 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4628 break;
4629 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4630 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004631 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004632 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4633 break;
4634 }
4635 break;
4636 }
4637 return 0;
4638}
4639
Chris Lattner57e66fa2009-07-23 05:46:22 +00004640Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4641 FCmpInst *RHS) {
4642 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4643 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4644 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4645 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4646 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4647 // If either of the constants are nans, then the whole thing returns
4648 // true.
4649 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004650 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004651
4652 // Otherwise, no need to compare the two constants, compare the
4653 // rest.
Dan Gohmane6803b82009-08-25 23:17:54 +00004654 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004655 LHS->getOperand(0), RHS->getOperand(0));
4656 }
4657
4658 // Handle vector zeros. This occurs because the canonical form of
4659 // "fcmp uno x,x" is "fcmp uno x, 0".
4660 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4661 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004662 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004663 LHS->getOperand(0), RHS->getOperand(0));
4664
4665 return 0;
4666 }
4667
4668 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4669 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4670 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4671
4672 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4673 // Swap RHS operands to match LHS.
4674 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4675 std::swap(Op1LHS, Op1RHS);
4676 }
4677 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4678 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4679 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004680 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004681 Op0LHS, Op0RHS);
4682 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004683 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004684 if (Op0CC == FCmpInst::FCMP_FALSE)
4685 return ReplaceInstUsesWith(I, RHS);
4686 if (Op1CC == FCmpInst::FCMP_FALSE)
4687 return ReplaceInstUsesWith(I, LHS);
4688 bool Op0Ordered;
4689 bool Op1Ordered;
4690 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4691 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4692 if (Op0Ordered == Op1Ordered) {
4693 // If both are ordered or unordered, return a new fcmp with
4694 // or'ed predicates.
4695 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4696 Op0LHS, Op0RHS, Context);
4697 if (Instruction *I = dyn_cast<Instruction>(RV))
4698 return I;
4699 // Otherwise, it's a constant boolean value...
4700 return ReplaceInstUsesWith(I, RV);
4701 }
4702 }
4703 return 0;
4704}
4705
Bill Wendlingdae376a2008-12-01 08:23:25 +00004706/// FoldOrWithConstants - This helper function folds:
4707///
Bill Wendling236a1192008-12-02 05:09:00 +00004708/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004709///
4710/// into:
4711///
Bill Wendling236a1192008-12-02 05:09:00 +00004712/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004713///
Bill Wendling236a1192008-12-02 05:09:00 +00004714/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004715Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004716 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004717 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4718 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004719
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004720 Value *V1 = 0;
4721 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004722 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004723
Bill Wendling86ee3162008-12-02 06:18:11 +00004724 APInt Xor = CI1->getValue() ^ CI2->getValue();
4725 if (!Xor.isAllOnesValue()) return 0;
4726
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004727 if (V1 == A || V1 == B) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004728 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004729 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004730 }
4731
4732 return 0;
4733}
4734
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004735Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4736 bool Changed = SimplifyCommutative(I);
4737 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4738
4739 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersonaac28372009-07-31 20:28:14 +00004740 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004741
4742 // or X, X = X
4743 if (Op0 == Op1)
4744 return ReplaceInstUsesWith(I, Op0);
4745
4746 // See if we can simplify any instructions used by the instruction whose sole
4747 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004748 if (SimplifyDemandedInstructionBits(I))
4749 return &I;
4750 if (isa<VectorType>(I.getType())) {
4751 if (isa<ConstantAggregateZero>(Op1)) {
4752 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4753 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4754 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4755 return ReplaceInstUsesWith(I, I.getOperand(1));
4756 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004757 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004758
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004759 // or X, -1 == -1
4760 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4761 ConstantInt *C1 = 0; Value *X = 0;
4762 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004763 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004764 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004765 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004766 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004767 return BinaryOperator::CreateAnd(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004768 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004769 }
4770
4771 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004772 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004773 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004774 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004775 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004776 return BinaryOperator::CreateXor(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004777 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004778 }
4779
4780 // Try to fold constant and into select arguments.
4781 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4782 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4783 return R;
4784 if (isa<PHINode>(Op0))
4785 if (Instruction *NV = FoldOpIntoPhi(I))
4786 return NV;
4787 }
4788
4789 Value *A = 0, *B = 0;
4790 ConstantInt *C1 = 0, *C2 = 0;
4791
Dan Gohmancdff2122009-08-12 16:23:25 +00004792 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004793 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4794 return ReplaceInstUsesWith(I, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004795 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004796 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4797 return ReplaceInstUsesWith(I, Op0);
4798
4799 // (A | B) | C and A | (B | C) -> bswap if possible.
4800 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00004801 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4802 match(Op1, m_Or(m_Value(), m_Value())) ||
4803 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4804 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004805 if (Instruction *BSwap = MatchBSwap(I))
4806 return BSwap;
4807 }
4808
4809 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004810 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004811 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004812 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004813 Value *NOr = Builder->CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004814 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004815 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004816 }
4817
4818 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004819 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004820 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004821 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004822 Value *NOr = Builder->CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004823 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004824 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004825 }
4826
4827 // (A & C)|(B & D)
4828 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004829 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4830 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004831 Value *V1 = 0, *V2 = 0, *V3 = 0;
4832 C1 = dyn_cast<ConstantInt>(C);
4833 C2 = dyn_cast<ConstantInt>(D);
4834 if (C1 && C2) { // (A & C1)|(B & C2)
4835 // If we have: ((V + N) & C1) | (V & C2)
4836 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4837 // replace with V+N.
4838 if (C1->getValue() == ~C2->getValue()) {
4839 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohmancdff2122009-08-12 16:23:25 +00004840 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004841 // Add commutes, try both ways.
4842 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4843 return ReplaceInstUsesWith(I, A);
4844 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4845 return ReplaceInstUsesWith(I, A);
4846 }
4847 // Or commutes, try both ways.
4848 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004849 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004850 // Add commutes, try both ways.
4851 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4852 return ReplaceInstUsesWith(I, B);
4853 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4854 return ReplaceInstUsesWith(I, B);
4855 }
4856 }
4857 V1 = 0; V2 = 0; V3 = 0;
4858 }
4859
4860 // Check to see if we have any common things being and'ed. If so, find the
4861 // terms for V1 & (V2|V3).
4862 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4863 if (A == B) // (A & C)|(A & D) == A & (C|D)
4864 V1 = A, V2 = C, V3 = D;
4865 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4866 V1 = A, V2 = B, V3 = C;
4867 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4868 V1 = C, V2 = A, V3 = D;
4869 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4870 V1 = C, V2 = A, V3 = B;
4871
4872 if (V1) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004873 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00004874 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004875 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004876 }
Dan Gohman279952c2008-10-28 22:38:57 +00004877
Dan Gohman35b76162008-10-30 20:40:10 +00004878 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00004879 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004880 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004881 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004882 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004883 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004884 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004885 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004886 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004887
Bill Wendling22ca8352008-11-30 13:52:49 +00004888 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004889 if ((match(C, m_Not(m_Specific(D))) &&
4890 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004891 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004892 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004893 if ((match(A, m_Not(m_Specific(D))) &&
4894 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004895 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004896 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004897 if ((match(C, m_Not(m_Specific(B))) &&
4898 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004899 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004900 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004901 if ((match(A, m_Not(m_Specific(B))) &&
4902 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004903 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004904 }
4905
4906 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4907 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4908 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4909 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4910 SI0->getOperand(1) == SI1->getOperand(1) &&
4911 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004912 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4913 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004914 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004915 SI1->getOperand(1));
4916 }
4917 }
4918
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004919 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004920 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4921 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004922 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004923 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004924 }
4925 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004926 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4927 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004928 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004929 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004930 }
4931
Dan Gohmancdff2122009-08-12 16:23:25 +00004932 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004933 if (A == Op1) // ~A | A == -1
Owen Andersonaac28372009-07-31 20:28:14 +00004934 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004935 } else {
4936 A = 0;
4937 }
4938 // Note, A is still live here!
Dan Gohmancdff2122009-08-12 16:23:25 +00004939 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004940 if (Op0 == B)
Owen Andersonaac28372009-07-31 20:28:14 +00004941 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004942
4943 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4944 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004945 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohmancdff2122009-08-12 16:23:25 +00004946 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004947 }
4948 }
4949
4950 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4951 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004952 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004953 return R;
4954
Chris Lattner0c678e52008-11-16 05:20:07 +00004955 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4956 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4957 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004958 }
4959
4960 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004961 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004962 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4963 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004964 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4965 !isa<ICmpInst>(Op1C->getOperand(0))) {
4966 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004967 if (SrcTy == Op1C->getOperand(0)->getType() &&
4968 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00004969 // Only do this if the casts both really cause code to be
4970 // generated.
4971 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4972 I.getType(), TD) &&
4973 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4974 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004975 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4976 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004977 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004978 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004979 }
4980 }
Chris Lattner91882432007-10-24 05:38:08 +00004981 }
4982
4983
4984 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4985 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00004986 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4987 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4988 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004989 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004990
4991 return Changed ? &I : 0;
4992}
4993
Dan Gohman089efff2008-05-13 00:00:25 +00004994namespace {
4995
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004996// XorSelf - Implements: X ^ X --> 0
4997struct XorSelf {
4998 Value *RHS;
4999 XorSelf(Value *rhs) : RHS(rhs) {}
5000 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5001 Instruction *apply(BinaryOperator &Xor) const {
5002 return &Xor;
5003 }
5004};
5005
Dan Gohman089efff2008-05-13 00:00:25 +00005006}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005007
5008Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5009 bool Changed = SimplifyCommutative(I);
5010 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5011
Evan Chenge5cd8032008-03-25 20:07:13 +00005012 if (isa<UndefValue>(Op1)) {
5013 if (isa<UndefValue>(Op0))
5014 // Handle undef ^ undef -> 0 special case. This is a common
5015 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00005016 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005017 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005018 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005019
5020 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005021 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005022 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00005023 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005024 }
5025
5026 // See if we can simplify any instructions used by the instruction whose sole
5027 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005028 if (SimplifyDemandedInstructionBits(I))
5029 return &I;
5030 if (isa<VectorType>(I.getType()))
5031 if (isa<ConstantAggregateZero>(Op1))
5032 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005033
5034 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005035 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005036 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5037 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5038 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5039 if (Op0I->getOpcode() == Instruction::And ||
5040 Op0I->getOpcode() == Instruction::Or) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005041 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5042 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005043 Value *NotY =
5044 Builder->CreateNot(Op0I->getOperand(1),
5045 Op0I->getOperand(1)->getName()+".not");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005046 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005047 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattnerc7694852009-08-30 07:44:24 +00005048 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005049 }
5050 }
5051 }
5052 }
5053
5054
5055 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00005056 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005057 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005058 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005059 return new ICmpInst(ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005060 ICI->getOperand(0), ICI->getOperand(1));
5061
Nick Lewycky1405e922007-08-06 20:04:16 +00005062 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005063 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005064 FCI->getOperand(0), FCI->getOperand(1));
5065 }
5066
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005067 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5068 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5069 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5070 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5071 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattnerc7694852009-08-30 07:44:24 +00005072 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5073 (RHS == ConstantExpr::getCast(Opcode,
5074 ConstantInt::getTrue(*Context),
5075 Op0C->getDestTy()))) {
5076 CI->setPredicate(CI->getInversePredicate());
5077 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005078 }
5079 }
5080 }
5081 }
5082
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005083 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5084 // ~(c-X) == X-c-1 == X+(-c-1)
5085 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5086 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005087 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5088 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005089 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005090 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005091 }
5092
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005093 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005094 if (Op0I->getOpcode() == Instruction::Add) {
5095 // ~(X-c) --> (-c-1)-X
5096 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005097 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005098 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00005099 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005100 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00005101 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005102 } else if (RHS->getValue().isSignBit()) {
5103 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005104 Constant *C = ConstantInt::get(*Context,
5105 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005106 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005107
5108 }
5109 } else if (Op0I->getOpcode() == Instruction::Or) {
5110 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5111 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005112 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005113 // Anything in both C1 and C2 is known to be zero, remove it from
5114 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00005115 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5116 NewRHS = ConstantExpr::getAnd(NewRHS,
5117 ConstantExpr::getNot(CommonBits));
Chris Lattner3183fb62009-08-30 06:13:40 +00005118 Worklist.Add(Op0I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005119 I.setOperand(0, Op0I->getOperand(0));
5120 I.setOperand(1, NewRHS);
5121 return &I;
5122 }
5123 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005124 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005125 }
5126
5127 // Try to fold constant and into select arguments.
5128 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5129 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5130 return R;
5131 if (isa<PHINode>(Op0))
5132 if (Instruction *NV = FoldOpIntoPhi(I))
5133 return NV;
5134 }
5135
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005136 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005137 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00005138 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005139
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005140 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005141 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00005142 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005143
5144
5145 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5146 if (Op1I) {
5147 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005148 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005149 if (A == Op0) { // B^(B|A) == (A|B)^B
5150 Op1I->swapOperands();
5151 I.swapOperands();
5152 std::swap(Op0, Op1);
5153 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5154 I.swapOperands(); // Simplified below.
5155 std::swap(Op0, Op1);
5156 }
Dan Gohmancdff2122009-08-12 16:23:25 +00005157 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005158 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005159 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005160 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005161 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005162 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005163 if (A == Op0) { // A^(A&B) -> A^(B&A)
5164 Op1I->swapOperands();
5165 std::swap(A, B);
5166 }
5167 if (B == Op0) { // A^(B&A) -> (B&A)^A
5168 I.swapOperands(); // Simplified below.
5169 std::swap(Op0, Op1);
5170 }
5171 }
5172 }
5173
5174 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5175 if (Op0I) {
5176 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005177 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005178 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005179 if (A == Op1) // (B|A)^B == (A|B)^B
5180 std::swap(A, B);
Chris Lattnerc7694852009-08-30 07:44:24 +00005181 if (B == Op1) // (A|B)^B == A & ~B
5182 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohmancdff2122009-08-12 16:23:25 +00005183 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005184 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005185 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005186 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005187 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005188 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005189 if (A == Op1) // (A&B)^A -> (B&A)^A
5190 std::swap(A, B);
5191 if (B == Op1 && // (B&A)^A == ~B & A
5192 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerc7694852009-08-30 07:44:24 +00005193 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005194 }
5195 }
5196 }
5197
5198 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5199 if (Op0I && Op1I && Op0I->isShift() &&
5200 Op0I->getOpcode() == Op1I->getOpcode() &&
5201 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5202 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005203 Value *NewOp =
5204 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5205 Op0I->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005206 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005207 Op1I->getOperand(1));
5208 }
5209
5210 if (Op0I && Op1I) {
5211 Value *A, *B, *C, *D;
5212 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005213 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5214 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005215 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005216 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005217 }
5218 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005219 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5220 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005221 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005222 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005223 }
5224
5225 // (A & B)^(C & D)
5226 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005227 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5228 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005229 // (X & Y)^(X & Y) -> (Y^Z) & X
5230 Value *X = 0, *Y = 0, *Z = 0;
5231 if (A == C)
5232 X = A, Y = B, Z = D;
5233 else if (A == D)
5234 X = A, Y = B, Z = C;
5235 else if (B == C)
5236 X = B, Y = A, Z = D;
5237 else if (B == D)
5238 X = B, Y = A, Z = C;
5239
5240 if (X) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005241 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005242 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005243 }
5244 }
5245 }
5246
5247 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5248 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005249 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005250 return R;
5251
5252 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005253 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005254 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5255 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5256 const Type *SrcTy = Op0C->getOperand(0)->getType();
5257 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5258 // Only do this if the casts both really cause code to be generated.
5259 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5260 I.getType(), TD) &&
5261 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5262 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005263 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5264 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005265 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005266 }
5267 }
Chris Lattner91882432007-10-24 05:38:08 +00005268 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005269
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005270 return Changed ? &I : 0;
5271}
5272
Owen Anderson24be4c12009-07-03 00:17:18 +00005273static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005274 LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005275 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005276}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005277
Dan Gohman8fd520a2009-06-15 22:12:54 +00005278static bool HasAddOverflow(ConstantInt *Result,
5279 ConstantInt *In1, ConstantInt *In2,
5280 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005281 if (IsSigned)
5282 if (In2->getValue().isNegative())
5283 return Result->getValue().sgt(In1->getValue());
5284 else
5285 return Result->getValue().slt(In1->getValue());
5286 else
5287 return Result->getValue().ult(In1->getValue());
5288}
5289
Dan Gohman8fd520a2009-06-15 22:12:54 +00005290/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005291/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005292static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005293 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005294 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005295 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005296
Dan Gohman8fd520a2009-06-15 22:12:54 +00005297 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5298 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005299 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005300 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5301 ExtractElement(In1, Idx, Context),
5302 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005303 IsSigned))
5304 return true;
5305 }
5306 return false;
5307 }
5308
5309 return HasAddOverflow(cast<ConstantInt>(Result),
5310 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5311 IsSigned);
5312}
5313
5314static bool HasSubOverflow(ConstantInt *Result,
5315 ConstantInt *In1, ConstantInt *In2,
5316 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005317 if (IsSigned)
5318 if (In2->getValue().isNegative())
5319 return Result->getValue().slt(In1->getValue());
5320 else
5321 return Result->getValue().sgt(In1->getValue());
5322 else
5323 return Result->getValue().ugt(In1->getValue());
5324}
5325
Dan Gohman8fd520a2009-06-15 22:12:54 +00005326/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5327/// overflowed for this type.
5328static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005329 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005330 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005331 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005332
5333 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5334 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005335 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005336 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5337 ExtractElement(In1, Idx, Context),
5338 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005339 IsSigned))
5340 return true;
5341 }
5342 return false;
5343 }
5344
5345 return HasSubOverflow(cast<ConstantInt>(Result),
5346 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5347 IsSigned);
5348}
5349
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005350/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5351/// code necessary to compute the offset from the base pointer (without adding
5352/// in the base pointer). Return the result as a signed integer of intptr size.
5353static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005354 TargetData &TD = *IC.getTargetData();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005355 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson35b47072009-08-13 21:58:54 +00005356 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersonaac28372009-07-31 20:28:14 +00005357 Value *Result = Constant::getNullValue(IntPtrTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005358
5359 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005360 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005361 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5362
Gabor Greif17396002008-06-12 21:37:33 +00005363 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5364 ++i, ++GTI) {
5365 Value *Op = *i;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005366 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005367 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5368 if (OpC->isZero()) continue;
5369
5370 // Handle a struct index, which adds its field offset to the pointer.
5371 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5372 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5373
Chris Lattnerc7694852009-08-30 07:44:24 +00005374 Result = IC.Builder->CreateAdd(Result,
5375 ConstantInt::get(IntPtrTy, Size),
5376 GEP->getName()+".offs");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005377 continue;
5378 }
5379
Owen Andersoneacb44d2009-07-24 23:12:02 +00005380 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Anderson24be4c12009-07-03 00:17:18 +00005381 Constant *OC =
Owen Anderson02b48c32009-07-29 18:55:55 +00005382 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5383 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattnerc7694852009-08-30 07:44:24 +00005384 // Emit an add instruction.
5385 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005386 continue;
5387 }
5388 // Convert to correct type.
Chris Lattnerc7694852009-08-30 07:44:24 +00005389 if (Op->getType() != IntPtrTy)
5390 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005391 if (Size != 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005392 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattnerc7694852009-08-30 07:44:24 +00005393 // We'll let instcombine(mul) convert this to a shl if possible.
5394 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005395 }
5396
5397 // Emit an add instruction.
Chris Lattnerc7694852009-08-30 07:44:24 +00005398 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005399 }
5400 return Result;
5401}
5402
Chris Lattnereba75862008-04-22 02:53:33 +00005403
Dan Gohmanff9b4732009-07-17 22:16:21 +00005404/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5405/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5406/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5407/// be complex, and scales are involved. The above expression would also be
5408/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5409/// This later form is less amenable to optimization though, and we are allowed
5410/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattnereba75862008-04-22 02:53:33 +00005411///
5412/// If we can't emit an optimized form for this expression, this returns null.
5413///
5414static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5415 InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005416 TargetData &TD = *IC.getTargetData();
Chris Lattnereba75862008-04-22 02:53:33 +00005417 gep_type_iterator GTI = gep_type_begin(GEP);
5418
5419 // Check to see if this gep only has a single variable index. If so, and if
5420 // any constant indices are a multiple of its scale, then we can compute this
5421 // in terms of the scale of the variable index. For example, if the GEP
5422 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5423 // because the expression will cross zero at the same point.
5424 unsigned i, e = GEP->getNumOperands();
5425 int64_t Offset = 0;
5426 for (i = 1; i != e; ++i, ++GTI) {
5427 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5428 // Compute the aggregate offset of constant indices.
5429 if (CI->isZero()) continue;
5430
5431 // Handle a struct index, which adds its field offset to the pointer.
5432 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5433 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5434 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005435 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005436 Offset += Size*CI->getSExtValue();
5437 }
5438 } else {
5439 // Found our variable index.
5440 break;
5441 }
5442 }
5443
5444 // If there are no variable indices, we must have a constant offset, just
5445 // evaluate it the general way.
5446 if (i == e) return 0;
5447
5448 Value *VariableIdx = GEP->getOperand(i);
5449 // Determine the scale factor of the variable element. For example, this is
5450 // 4 if the variable index is into an array of i32.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005451 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005452
5453 // Verify that there are no other variable indices. If so, emit the hard way.
5454 for (++i, ++GTI; i != e; ++i, ++GTI) {
5455 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5456 if (!CI) return 0;
5457
5458 // Compute the aggregate offset of constant indices.
5459 if (CI->isZero()) continue;
5460
5461 // Handle a struct index, which adds its field offset to the pointer.
5462 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5463 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5464 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005465 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005466 Offset += Size*CI->getSExtValue();
5467 }
5468 }
5469
5470 // Okay, we know we have a single variable index, which must be a
5471 // pointer/array/vector index. If there is no offset, life is simple, return
5472 // the index.
5473 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5474 if (Offset == 0) {
5475 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5476 // we don't need to bother extending: the extension won't affect where the
5477 // computation crosses zero.
5478 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson35b47072009-08-13 21:58:54 +00005479 VariableIdx = new TruncInst(VariableIdx,
5480 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005481 VariableIdx->getName(), &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005482 return VariableIdx;
5483 }
5484
5485 // Otherwise, there is an index. The computation we will do will be modulo
5486 // the pointer size, so get it.
5487 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5488
5489 Offset &= PtrSizeMask;
5490 VariableScale &= PtrSizeMask;
5491
5492 // To do this transformation, any constant index must be a multiple of the
5493 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5494 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5495 // multiple of the variable scale.
5496 int64_t NewOffs = Offset / (int64_t)VariableScale;
5497 if (Offset != NewOffs*(int64_t)VariableScale)
5498 return 0;
5499
5500 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson35b47072009-08-13 21:58:54 +00005501 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattnereba75862008-04-22 02:53:33 +00005502 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005503 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005504 true /*SExt*/,
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005505 VariableIdx->getName(), &I);
Owen Andersoneacb44d2009-07-24 23:12:02 +00005506 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005507 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005508}
5509
5510
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005511/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5512/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohman17f46f72009-07-28 01:40:03 +00005513Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005514 ICmpInst::Predicate Cond,
5515 Instruction &I) {
Chris Lattnereba75862008-04-22 02:53:33 +00005516 // Look through bitcasts.
5517 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5518 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005519
5520 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohman17f46f72009-07-28 01:40:03 +00005521 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005522 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005523 // This transformation (ignoring the base and scales) is valid because we
Dan Gohman17f46f72009-07-28 01:40:03 +00005524 // know pointers can't overflow since the gep is inbounds. See if we can
5525 // output an optimized form.
Chris Lattnereba75862008-04-22 02:53:33 +00005526 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5527
5528 // If not, synthesize the offset the hard way.
5529 if (Offset == 0)
5530 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005531 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonaac28372009-07-31 20:28:14 +00005532 Constant::getNullValue(Offset->getType()));
Dan Gohman17f46f72009-07-28 01:40:03 +00005533 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005534 // If the base pointers are different, but the indices are the same, just
5535 // compare the base pointer.
5536 if (PtrBase != GEPRHS->getOperand(0)) {
5537 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5538 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5539 GEPRHS->getOperand(0)->getType();
5540 if (IndicesTheSame)
5541 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5542 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5543 IndicesTheSame = false;
5544 break;
5545 }
5546
5547 // If all indices are the same, just compare the base pointers.
5548 if (IndicesTheSame)
Dan Gohmane6803b82009-08-25 23:17:54 +00005549 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005550 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5551
5552 // Otherwise, the base pointers are different and the indices are
5553 // different, bail out.
5554 return 0;
5555 }
5556
5557 // If one of the GEPs has all zero indices, recurse.
5558 bool AllZeros = true;
5559 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5560 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5561 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5562 AllZeros = false;
5563 break;
5564 }
5565 if (AllZeros)
5566 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5567 ICmpInst::getSwappedPredicate(Cond), I);
5568
5569 // If the other GEP has all zero indices, recurse.
5570 AllZeros = true;
5571 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5572 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5573 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5574 AllZeros = false;
5575 break;
5576 }
5577 if (AllZeros)
5578 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5579
5580 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5581 // If the GEPs only differ by one index, compare it.
5582 unsigned NumDifferences = 0; // Keep track of # differences.
5583 unsigned DiffOperand = 0; // The operand that differs.
5584 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5585 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5586 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5587 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5588 // Irreconcilable differences.
5589 NumDifferences = 2;
5590 break;
5591 } else {
5592 if (NumDifferences++) break;
5593 DiffOperand = i;
5594 }
5595 }
5596
5597 if (NumDifferences == 0) // SAME GEP?
5598 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson35b47072009-08-13 21:58:54 +00005599 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005600 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005601
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005602 else if (NumDifferences == 1) {
5603 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5604 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5605 // Make sure we do a signed comparison here.
Dan Gohmane6803b82009-08-25 23:17:54 +00005606 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005607 }
5608 }
5609
5610 // Only lower this if the icmp is the only user of the GEP or if we expect
5611 // the result to fold to a constant!
Dan Gohmana80e2712009-07-21 23:21:54 +00005612 if (TD &&
5613 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005614 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5615 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5616 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5617 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005618 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005619 }
5620 }
5621 return 0;
5622}
5623
Chris Lattnere6b62d92008-05-19 20:18:56 +00005624/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5625///
5626Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5627 Instruction *LHSI,
5628 Constant *RHSC) {
5629 if (!isa<ConstantFP>(RHSC)) return 0;
5630 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5631
5632 // Get the width of the mantissa. We don't want to hack on conversions that
5633 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005634 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005635 if (MantissaWidth == -1) return 0; // Unknown.
5636
5637 // Check to see that the input is converted from an integer type that is small
5638 // enough that preserves all bits. TODO: check here for "known" sign bits.
5639 // 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 +00005640 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005641
5642 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005643 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5644 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005645 ++InputSize;
5646
5647 // If the conversion would lose info, don't hack on this.
5648 if ((int)InputSize > MantissaWidth)
5649 return 0;
5650
5651 // Otherwise, we can potentially simplify the comparison. We know that it
5652 // will always come through as an integer value and we know the constant is
5653 // not a NAN (it would have been previously simplified).
5654 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5655
5656 ICmpInst::Predicate Pred;
5657 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005658 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnere6b62d92008-05-19 20:18:56 +00005659 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005660 case FCmpInst::FCMP_OEQ:
5661 Pred = ICmpInst::ICMP_EQ;
5662 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005663 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005664 case FCmpInst::FCMP_OGT:
5665 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5666 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005667 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005668 case FCmpInst::FCMP_OGE:
5669 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5670 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005671 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005672 case FCmpInst::FCMP_OLT:
5673 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5674 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005675 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005676 case FCmpInst::FCMP_OLE:
5677 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5678 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005679 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005680 case FCmpInst::FCMP_ONE:
5681 Pred = ICmpInst::ICMP_NE;
5682 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005683 case FCmpInst::FCMP_ORD:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005684 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005685 case FCmpInst::FCMP_UNO:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005686 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005687 }
5688
5689 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5690
5691 // Now we know that the APFloat is a normal number, zero or inf.
5692
Chris Lattnerf13ff492008-05-20 03:50:52 +00005693 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005694 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005695 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005696
Bill Wendling20636df2008-11-09 04:26:50 +00005697 if (!LHSUnsigned) {
5698 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5699 // and large values.
5700 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5701 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5702 APFloat::rmNearestTiesToEven);
5703 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5704 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5705 Pred == ICmpInst::ICMP_SLE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005706 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5707 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005708 }
5709 } else {
5710 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5711 // +INF and large values.
5712 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5713 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5714 APFloat::rmNearestTiesToEven);
5715 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5716 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5717 Pred == ICmpInst::ICMP_ULE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005718 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5719 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005720 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005721 }
5722
Bill Wendling20636df2008-11-09 04:26:50 +00005723 if (!LHSUnsigned) {
5724 // See if the RHS value is < SignedMin.
5725 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5726 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5727 APFloat::rmNearestTiesToEven);
5728 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5729 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5730 Pred == ICmpInst::ICMP_SGE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005731 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5732 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005733 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005734 }
5735
Bill Wendling20636df2008-11-09 04:26:50 +00005736 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5737 // [0, UMAX], but it may still be fractional. See if it is fractional by
5738 // casting the FP value to the integer value and back, checking for equality.
5739 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005740 Constant *RHSInt = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005741 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5742 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005743 if (!RHS.isZero()) {
5744 bool Equal = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005745 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5746 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005747 if (!Equal) {
5748 // If we had a comparison against a fractional value, we have to adjust
5749 // the compare predicate and sometimes the value. RHSC is rounded towards
5750 // zero at this point.
5751 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005752 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng14118132009-05-22 23:10:53 +00005753 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005754 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005755 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00005756 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005757 case ICmpInst::ICMP_ULE:
5758 // (float)int <= 4.4 --> int <= 4
5759 // (float)int <= -4.4 --> false
5760 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005761 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005762 break;
5763 case ICmpInst::ICMP_SLE:
5764 // (float)int <= 4.4 --> int <= 4
5765 // (float)int <= -4.4 --> int < -4
5766 if (RHS.isNegative())
5767 Pred = ICmpInst::ICMP_SLT;
5768 break;
5769 case ICmpInst::ICMP_ULT:
5770 // (float)int < -4.4 --> false
5771 // (float)int < 4.4 --> int <= 4
5772 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005773 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005774 Pred = ICmpInst::ICMP_ULE;
5775 break;
5776 case ICmpInst::ICMP_SLT:
5777 // (float)int < -4.4 --> int < -4
5778 // (float)int < 4.4 --> int <= 4
5779 if (!RHS.isNegative())
5780 Pred = ICmpInst::ICMP_SLE;
5781 break;
5782 case ICmpInst::ICMP_UGT:
5783 // (float)int > 4.4 --> int > 4
5784 // (float)int > -4.4 --> true
5785 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005786 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005787 break;
5788 case ICmpInst::ICMP_SGT:
5789 // (float)int > 4.4 --> int > 4
5790 // (float)int > -4.4 --> int >= -4
5791 if (RHS.isNegative())
5792 Pred = ICmpInst::ICMP_SGE;
5793 break;
5794 case ICmpInst::ICMP_UGE:
5795 // (float)int >= -4.4 --> true
5796 // (float)int >= 4.4 --> int > 4
5797 if (!RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005798 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005799 Pred = ICmpInst::ICMP_UGT;
5800 break;
5801 case ICmpInst::ICMP_SGE:
5802 // (float)int >= -4.4 --> int >= -4
5803 // (float)int >= 4.4 --> int > 4
5804 if (!RHS.isNegative())
5805 Pred = ICmpInst::ICMP_SGT;
5806 break;
5807 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005808 }
5809 }
5810
5811 // Lower this FP comparison into an appropriate integer version of the
5812 // comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00005813 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00005814}
5815
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005816Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5817 bool Changed = SimplifyCompare(I);
5818 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5819
5820 // Fold trivial predicates.
5821 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner41c09932009-09-02 05:12:37 +00005822 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005823 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner41c09932009-09-02 05:12:37 +00005824 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005825
5826 // Simplify 'fcmp pred X, X'
5827 if (Op0 == Op1) {
5828 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005829 default: llvm_unreachable("Unknown predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005830 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5831 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5832 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner41c09932009-09-02 05:12:37 +00005833 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005834 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5835 case FCmpInst::FCMP_OLT: // True if ordered and less than
5836 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner41c09932009-09-02 05:12:37 +00005837 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005838
5839 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5840 case FCmpInst::FCMP_ULT: // True if unordered or less than
5841 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5842 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5843 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5844 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersonaac28372009-07-31 20:28:14 +00005845 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005846 return &I;
5847
5848 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5849 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5850 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5851 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5852 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5853 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersonaac28372009-07-31 20:28:14 +00005854 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005855 return &I;
5856 }
5857 }
5858
5859 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner41c09932009-09-02 05:12:37 +00005860 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005861
5862 // Handle fcmp with constant RHS
5863 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005864 // If the constant is a nan, see if we can fold the comparison based on it.
5865 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5866 if (CFP->getValueAPF().isNaN()) {
5867 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson4f720fa2009-07-31 17:39:07 +00005868 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnerf13ff492008-05-20 03:50:52 +00005869 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5870 "Comparison must be either ordered or unordered!");
5871 // True if unordered.
Owen Anderson4f720fa2009-07-31 17:39:07 +00005872 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005873 }
5874 }
5875
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005876 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5877 switch (LHSI->getOpcode()) {
5878 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005879 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5880 // block. If in the same block, we're encouraging jump threading. If
5881 // not, we are just pessimizing the code by making an i1 phi.
5882 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00005883 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00005884 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005885 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005886 case Instruction::SIToFP:
5887 case Instruction::UIToFP:
5888 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5889 return NV;
5890 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005891 case Instruction::Select:
5892 // If either operand of the select is a constant, we can fold the
5893 // comparison into the select arms, which will cause one to be
5894 // constant folded and the select turned into a bitwise or.
5895 Value *Op1 = 0, *Op2 = 0;
5896 if (LHSI->hasOneUse()) {
5897 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5898 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005899 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005900 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00005901 Op2 = Builder->CreateFCmp(I.getPredicate(),
5902 LHSI->getOperand(2), RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005903 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5904 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005905 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005906 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00005907 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5908 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005909 }
5910 }
5911
5912 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005913 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005914 break;
5915 }
5916 }
5917
5918 return Changed ? &I : 0;
5919}
5920
5921Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5922 bool Changed = SimplifyCompare(I);
5923 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5924 const Type *Ty = Op0->getType();
5925
5926 // icmp X, X
5927 if (Op0 == Op1)
Chris Lattner41c09932009-09-02 05:12:37 +00005928 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005929 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005930
5931 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner41c09932009-09-02 05:12:37 +00005932 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lambf78cd322007-12-18 21:32:20 +00005933
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005934 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5935 // addresses never equal each other! We already know that Op0 != Op1.
Victor Hernandez48c3c542009-09-18 22:35:49 +00005936 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || isMalloc(Op0) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005937 isa<ConstantPointerNull>(Op0)) &&
Victor Hernandez48c3c542009-09-18 22:35:49 +00005938 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || isMalloc(Op1) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005939 isa<ConstantPointerNull>(Op1)))
Owen Anderson35b47072009-08-13 21:58:54 +00005940 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005941 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005942
5943 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson35b47072009-08-13 21:58:54 +00005944 if (Ty == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005945 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005946 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00005947 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattnerc7694852009-08-30 07:44:24 +00005948 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmancdff2122009-08-12 16:23:25 +00005949 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005950 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005951 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005952 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005953
5954 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00005955 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005956 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005957 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattnerc7694852009-08-30 07:44:24 +00005958 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00005959 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005960 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005961 case ICmpInst::ICMP_SGT:
5962 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005963 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005964 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00005965 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00005966 return BinaryOperator::CreateAnd(Not, Op0);
5967 }
5968 case ICmpInst::ICMP_UGE:
5969 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5970 // FALL THROUGH
5971 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattnerc7694852009-08-30 07:44:24 +00005972 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00005973 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005974 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005975 case ICmpInst::ICMP_SGE:
5976 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5977 // FALL THROUGH
5978 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00005979 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00005980 return BinaryOperator::CreateOr(Not, Op0);
5981 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005982 }
5983 }
5984
Dan Gohman7934d592009-04-25 17:12:48 +00005985 unsigned BitWidth = 0;
5986 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00005987 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5988 else if (Ty->isIntOrIntVector())
5989 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00005990
5991 bool isSignBit = false;
5992
Dan Gohman58c09632008-09-16 18:46:06 +00005993 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005994 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00005995 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00005996
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005997 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5998 if (I.isEquality() && CI->isNullValue() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005999 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006000 // (icmp cond A B) if cond is equality
Dan Gohmane6803b82009-08-25 23:17:54 +00006001 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00006002 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006003
Dan Gohman58c09632008-09-16 18:46:06 +00006004 // If we have an icmp le or icmp ge instruction, turn it into the
6005 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6006 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00006007 switch (I.getPredicate()) {
6008 default: break;
6009 case ICmpInst::ICMP_ULE:
6010 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006011 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006012 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006013 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006014 case ICmpInst::ICMP_SLE:
6015 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006016 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006017 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006018 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006019 case ICmpInst::ICMP_UGE:
6020 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006021 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006022 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006023 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006024 case ICmpInst::ICMP_SGE:
6025 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006026 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006027 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006028 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006029 }
6030
Chris Lattnera1308652008-07-11 05:40:05 +00006031 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006032 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006033 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006034 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6035 }
6036
6037 // See if we can fold the comparison based on range information we can get
6038 // by checking whether bits are known to be zero or one in the input.
6039 if (BitWidth != 0) {
6040 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6041 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6042
6043 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006044 isSignBit ? APInt::getSignBit(BitWidth)
6045 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006046 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006047 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006048 if (SimplifyDemandedBits(I.getOperandUse(1),
6049 APInt::getAllOnesValue(BitWidth),
6050 Op1KnownZero, Op1KnownOne, 0))
6051 return &I;
6052
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006053 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006054 // in. Compute the Min, Max and RHS values based on the known bits. For the
6055 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006056 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6057 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6058 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6059 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6060 Op0Min, Op0Max);
6061 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6062 Op1Min, Op1Max);
6063 } else {
6064 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6065 Op0Min, Op0Max);
6066 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6067 Op1Min, Op1Max);
6068 }
6069
Chris Lattnera1308652008-07-11 05:40:05 +00006070 // If Min and Max are known to be the same, then SimplifyDemandedBits
6071 // figured out that the LHS is a constant. Just constant fold this now so
6072 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006073 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006074 return new ICmpInst(I.getPredicate(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006075 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006076 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006077 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006078 ConstantInt::get(*Context, Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006079
Chris Lattnera1308652008-07-11 05:40:05 +00006080 // Based on the range information we know about the LHS, see if we can
6081 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006082 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006083 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner62d0f232008-07-11 05:08:55 +00006084 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006085 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006086 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006087 break;
6088 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006089 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006090 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006091 break;
6092 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006093 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006094 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006095 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006096 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006097 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006098 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006099 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6100 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006101 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006102 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006103
6104 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6105 if (CI->isMinValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006106 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006107 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006108 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006109 break;
6110 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006111 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006112 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006113 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006114 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006115
6116 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006117 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006118 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6119 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006120 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006121 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006122
6123 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6124 if (CI->isMaxValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006125 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006126 Constant::getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006127 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006128 break;
6129 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006130 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006131 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006132 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006133 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006134 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006135 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006136 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6137 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006138 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006139 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006140 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006141 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006142 case ICmpInst::ICMP_SGT:
6143 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006144 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006145 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006146 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006147
6148 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006149 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006150 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6151 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006152 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006153 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006154 }
6155 break;
6156 case ICmpInst::ICMP_SGE:
6157 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6158 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006159 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006160 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006161 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006162 break;
6163 case ICmpInst::ICMP_SLE:
6164 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6165 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006166 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006167 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006168 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006169 break;
6170 case ICmpInst::ICMP_UGE:
6171 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6172 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006173 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006174 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006175 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006176 break;
6177 case ICmpInst::ICMP_ULE:
6178 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6179 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006180 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006181 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006182 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006183 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006184 }
Dan Gohman7934d592009-04-25 17:12:48 +00006185
6186 // Turn a signed comparison into an unsigned one if both operands
6187 // are known to have the same sign.
6188 if (I.isSignedPredicate() &&
6189 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6190 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohmane6803b82009-08-25 23:17:54 +00006191 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006192 }
6193
6194 // Test if the ICmpInst instruction is used exclusively by a select as
6195 // part of a minimum or maximum operation. If so, refrain from doing
6196 // any other folding. This helps out other analyses which understand
6197 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6198 // and CodeGen. And in this case, at least one of the comparison
6199 // operands has at least one user besides the compare (the select),
6200 // which would often largely negate the benefit of folding anyway.
6201 if (I.hasOneUse())
6202 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6203 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6204 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6205 return 0;
6206
6207 // See if we are doing a comparison between a constant and an instruction that
6208 // can be folded into the comparison.
6209 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006210 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6211 // instruction, see if that instruction also has constants so that the
6212 // instruction can be folded into the icmp
6213 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6214 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6215 return Res;
6216 }
6217
6218 // Handle icmp with constant (but not simple integer constant) RHS
6219 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6220 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6221 switch (LHSI->getOpcode()) {
6222 case Instruction::GetElementPtr:
6223 if (RHSC->isNullValue()) {
6224 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6225 bool isAllZeros = true;
6226 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6227 if (!isa<Constant>(LHSI->getOperand(i)) ||
6228 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6229 isAllZeros = false;
6230 break;
6231 }
6232 if (isAllZeros)
Dan Gohmane6803b82009-08-25 23:17:54 +00006233 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersonaac28372009-07-31 20:28:14 +00006234 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006235 }
6236 break;
6237
6238 case Instruction::PHI:
Chris Lattner9b61abd2009-09-27 20:46:36 +00006239 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattnera2417ba2008-06-08 20:52:11 +00006240 // block. If in the same block, we're encouraging jump threading. If
6241 // not, we are just pessimizing the code by making an i1 phi.
6242 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00006243 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00006244 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006245 break;
6246 case Instruction::Select: {
6247 // If either operand of the select is a constant, we can fold the
6248 // comparison into the select arms, which will cause one to be
6249 // constant folded and the select turned into a bitwise or.
6250 Value *Op1 = 0, *Op2 = 0;
6251 if (LHSI->hasOneUse()) {
6252 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6253 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006254 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006255 // Insert a new ICmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006256 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6257 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006258 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6259 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006260 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006261 // Insert a new ICmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006262 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6263 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006264 }
6265 }
6266
6267 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006268 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006269 break;
6270 }
6271 case Instruction::Malloc:
6272 // If we have (malloc != null), and if the malloc has a single use, we
6273 // can assume it is successful and remove the malloc.
6274 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner3183fb62009-08-30 06:13:40 +00006275 Worklist.Add(LHSI);
Victor Hernandez48c3c542009-09-18 22:35:49 +00006276 return ReplaceInstUsesWith(I,
6277 ConstantInt::get(Type::getInt1Ty(*Context),
6278 !I.isTrueWhenEqual()));
6279 }
6280 break;
6281 case Instruction::Call:
6282 // If we have (malloc != null), and if the malloc has a single use, we
6283 // can assume it is successful and remove the malloc.
6284 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6285 isa<ConstantPointerNull>(RHSC)) {
6286 Worklist.Add(LHSI);
6287 return ReplaceInstUsesWith(I,
6288 ConstantInt::get(Type::getInt1Ty(*Context),
6289 !I.isTrueWhenEqual()));
6290 }
6291 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006292 }
6293 }
6294
6295 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohman17f46f72009-07-28 01:40:03 +00006296 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006297 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6298 return NI;
Dan Gohman17f46f72009-07-28 01:40:03 +00006299 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006300 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6301 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6302 return NI;
6303
6304 // Test to see if the operands of the icmp are casted versions of other
6305 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6306 // now.
6307 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6308 if (isa<PointerType>(Op0->getType()) &&
6309 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6310 // We keep moving the cast from the left operand over to the right
6311 // operand, where it can often be eliminated completely.
6312 Op0 = CI->getOperand(0);
6313
6314 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6315 // so eliminate it as well.
6316 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6317 Op1 = CI2->getOperand(0);
6318
6319 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006320 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006321 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00006322 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006323 } else {
6324 // Otherwise, cast the RHS right before the icmp
Chris Lattner78628292009-08-30 19:47:22 +00006325 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006326 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006327 }
Dan Gohmane6803b82009-08-25 23:17:54 +00006328 return new ICmpInst(I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006329 }
6330 }
6331
6332 if (isa<CastInst>(Op0)) {
6333 // Handle the special case of: icmp (cast bool to X), <cst>
6334 // This comes up when you have code like
6335 // int X = A < B;
6336 // if (X) ...
6337 // For generality, we handle any zero-extension of any operand comparison
6338 // with a constant or another cast from the same type.
6339 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6340 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6341 return R;
6342 }
6343
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006344 // See if it's the same type of instruction on the left and right.
6345 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6346 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006347 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006348 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006349 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006350 default: break;
6351 case Instruction::Add:
6352 case Instruction::Sub:
6353 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006354 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohmane6803b82009-08-25 23:17:54 +00006355 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006356 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006357 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6358 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6359 if (CI->getValue().isSignBit()) {
6360 ICmpInst::Predicate Pred = I.isSignedPredicate()
6361 ? I.getUnsignedPredicate()
6362 : I.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006363 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006364 Op1I->getOperand(0));
6365 }
6366
6367 if (CI->getValue().isMaxSignedValue()) {
6368 ICmpInst::Predicate Pred = I.isSignedPredicate()
6369 ? I.getUnsignedPredicate()
6370 : I.getSignedPredicate();
6371 Pred = I.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006372 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006373 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006374 }
6375 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006376 break;
6377 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006378 if (!I.isEquality())
6379 break;
6380
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006381 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6382 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6383 // Mask = -1 >> count-trailing-zeros(Cst).
6384 if (!CI->isZero() && !CI->isOne()) {
6385 const APInt &AP = CI->getValue();
Owen Andersoneacb44d2009-07-24 23:12:02 +00006386 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006387 APInt::getLowBitsSet(AP.getBitWidth(),
6388 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006389 AP.countTrailingZeros()));
Chris Lattnerc7694852009-08-30 07:44:24 +00006390 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6391 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohmane6803b82009-08-25 23:17:54 +00006392 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006393 }
6394 }
6395 break;
6396 }
6397 }
6398 }
6399 }
6400
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006401 // ~x < ~y --> y < x
6402 { Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00006403 if (match(Op0, m_Not(m_Value(A))) &&
6404 match(Op1, m_Not(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006405 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006406 }
6407
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006408 if (I.isEquality()) {
6409 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006410
6411 // -x == -y --> x == y
Dan Gohmancdff2122009-08-12 16:23:25 +00006412 if (match(Op0, m_Neg(m_Value(A))) &&
6413 match(Op1, m_Neg(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006414 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006415
Dan Gohmancdff2122009-08-12 16:23:25 +00006416 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006417 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6418 Value *OtherVal = A == Op1 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006419 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006420 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006421 }
6422
Dan Gohmancdff2122009-08-12 16:23:25 +00006423 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006424 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006425 ConstantInt *C1, *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00006426 if (match(B, m_ConstantInt(C1)) &&
6427 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006428 Constant *NC =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006429 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnerc7694852009-08-30 07:44:24 +00006430 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6431 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattner3b874082008-11-16 05:38:51 +00006432 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006433
6434 // A^B == A^D -> B == D
Dan Gohmane6803b82009-08-25 23:17:54 +00006435 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6436 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6437 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6438 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006439 }
6440 }
6441
Dan Gohmancdff2122009-08-12 16:23:25 +00006442 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006443 (A == Op0 || B == Op0)) {
6444 // A == (A^B) -> B == 0
6445 Value *OtherVal = A == Op0 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006446 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006447 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006448 }
Chris Lattner3b874082008-11-16 05:38:51 +00006449
6450 // (A-B) == A -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006451 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006452 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006453 Constant::getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006454
6455 // A == (A-B) -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006456 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006457 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006458 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006459
6460 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6461 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006462 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6463 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006464 Value *X = 0, *Y = 0, *Z = 0;
6465
6466 if (A == C) {
6467 X = B; Y = D; Z = A;
6468 } else if (A == D) {
6469 X = B; Y = C; Z = A;
6470 } else if (B == C) {
6471 X = A; Y = D; Z = B;
6472 } else if (B == D) {
6473 X = A; Y = C; Z = B;
6474 }
6475
6476 if (X) { // Build (X^Y) & Z
Chris Lattnerc7694852009-08-30 07:44:24 +00006477 Op1 = Builder->CreateXor(X, Y, "tmp");
6478 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006479 I.setOperand(0, Op1);
Owen Andersonaac28372009-07-31 20:28:14 +00006480 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006481 return &I;
6482 }
6483 }
6484 }
6485 return Changed ? &I : 0;
6486}
6487
6488
6489/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6490/// and CmpRHS are both known to be integer constants.
6491Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6492 ConstantInt *DivRHS) {
6493 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6494 const APInt &CmpRHSV = CmpRHS->getValue();
6495
6496 // FIXME: If the operand types don't match the type of the divide
6497 // then don't attempt this transform. The code below doesn't have the
6498 // logic to deal with a signed divide and an unsigned compare (and
6499 // vice versa). This is because (x /s C1) <s C2 produces different
6500 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6501 // (x /u C1) <u C2. Simply casting the operands and result won't
6502 // work. :( The if statement below tests that condition and bails
6503 // if it finds it.
6504 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6505 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6506 return 0;
6507 if (DivRHS->isZero())
6508 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006509 if (DivIsSigned && DivRHS->isAllOnesValue())
6510 return 0; // The overflow computation also screws up here
6511 if (DivRHS->isOne())
6512 return 0; // Not worth bothering, and eliminates some funny cases
6513 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006514
6515 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6516 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6517 // C2 (CI). By solving for X we can turn this into a range check
6518 // instead of computing a divide.
Owen Anderson02b48c32009-07-29 18:55:55 +00006519 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006520
6521 // Determine if the product overflows by seeing if the product is
6522 // not equal to the divide. Make sure we do the same kind of divide
6523 // as in the LHS instruction that we're folding.
Owen Anderson02b48c32009-07-29 18:55:55 +00006524 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6525 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006526
6527 // Get the ICmp opcode
6528 ICmpInst::Predicate Pred = ICI.getPredicate();
6529
6530 // Figure out the interval that is being checked. For example, a comparison
6531 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6532 // Compute this interval based on the constants involved and the signedness of
6533 // the compare/divide. This computes a half-open interval, keeping track of
6534 // whether either value in the interval overflows. After analysis each
6535 // overflow variable is set to 0 if it's corresponding bound variable is valid
6536 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6537 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006538 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006539
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006540 if (!DivIsSigned) { // udiv
6541 // e.g. X/5 op 3 --> [15, 20)
6542 LoBound = Prod;
6543 HiOverflow = LoOverflow = ProdOV;
6544 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006545 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006546 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006547 if (CmpRHSV == 0) { // (X / pos) op 0
6548 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006549 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006550 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006551 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006552 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6553 HiOverflow = LoOverflow = ProdOV;
6554 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006555 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006556 } else { // (X / pos) op neg
6557 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006558 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006559 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6560 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006561 ConstantInt* DivNeg =
Owen Anderson02b48c32009-07-29 18:55:55 +00006562 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Anderson24be4c12009-07-03 00:17:18 +00006563 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006564 true) ? -1 : 0;
6565 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006566 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006567 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006568 if (CmpRHSV == 0) { // (X / neg) op 0
6569 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006570 LoBound = AddOne(DivRHS);
Owen Anderson02b48c32009-07-29 18:55:55 +00006571 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006572 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6573 HiOverflow = 1; // [INTMIN+1, overflow)
6574 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6575 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006576 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006577 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006578 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006579 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6580 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006581 LoOverflow = AddWithOverflow(LoBound, HiBound,
6582 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006583 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006584 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6585 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006586 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006587 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006588 }
6589
6590 // Dividing by a negative swaps the condition. LT <-> GT
6591 Pred = ICmpInst::getSwappedPredicate(Pred);
6592 }
6593
6594 Value *X = DivI->getOperand(0);
6595 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006596 default: llvm_unreachable("Unhandled icmp opcode!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006597 case ICmpInst::ICMP_EQ:
6598 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006599 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006600 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006601 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006602 ICmpInst::ICMP_UGE, X, LoBound);
6603 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006604 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006605 ICmpInst::ICMP_ULT, X, HiBound);
6606 else
6607 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6608 case ICmpInst::ICMP_NE:
6609 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006610 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006611 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006612 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006613 ICmpInst::ICMP_ULT, X, LoBound);
6614 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006615 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006616 ICmpInst::ICMP_UGE, X, HiBound);
6617 else
6618 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6619 case ICmpInst::ICMP_ULT:
6620 case ICmpInst::ICMP_SLT:
6621 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006622 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006623 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006624 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006625 return new ICmpInst(Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006626 case ICmpInst::ICMP_UGT:
6627 case ICmpInst::ICMP_SGT:
6628 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006629 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006630 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006631 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006632 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohmane6803b82009-08-25 23:17:54 +00006633 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006634 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006635 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006636 }
6637}
6638
6639
6640/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6641///
6642Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6643 Instruction *LHSI,
6644 ConstantInt *RHS) {
6645 const APInt &RHSV = RHS->getValue();
6646
6647 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006648 case Instruction::Trunc:
6649 if (ICI.isEquality() && LHSI->hasOneUse()) {
6650 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6651 // of the high bits truncated out of x are known.
6652 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6653 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6654 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6655 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6656 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6657
6658 // If all the high bits are known, we can do this xform.
6659 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6660 // Pull in the high bits from known-ones set.
6661 APInt NewRHS(RHS->getValue());
6662 NewRHS.zext(SrcBits);
6663 NewRHS |= KnownOne;
Dan Gohmane6803b82009-08-25 23:17:54 +00006664 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006665 ConstantInt::get(*Context, NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00006666 }
6667 }
6668 break;
6669
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006670 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6671 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6672 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6673 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006674 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6675 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006676 Value *CompareVal = LHSI->getOperand(0);
6677
6678 // If the sign bit of the XorCST is not set, there is no change to
6679 // the operation, just stop using the Xor.
6680 if (!XorCST->getValue().isNegative()) {
6681 ICI.setOperand(0, CompareVal);
Chris Lattner3183fb62009-08-30 06:13:40 +00006682 Worklist.Add(LHSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006683 return &ICI;
6684 }
6685
6686 // Was the old condition true if the operand is positive?
6687 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6688
6689 // If so, the new one isn't.
6690 isTrueIfPositive ^= true;
6691
6692 if (isTrueIfPositive)
Dan Gohmane6803b82009-08-25 23:17:54 +00006693 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006694 SubOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006695 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006696 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006697 AddOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006698 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006699
6700 if (LHSI->hasOneUse()) {
6701 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6702 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6703 const APInt &SignBit = XorCST->getValue();
6704 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6705 ? ICI.getUnsignedPredicate()
6706 : ICI.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006707 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006708 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006709 }
6710
6711 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006712 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006713 const APInt &NotSignBit = XorCST->getValue();
6714 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6715 ? ICI.getUnsignedPredicate()
6716 : ICI.getSignedPredicate();
6717 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006718 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006719 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006720 }
6721 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006722 }
6723 break;
6724 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6725 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6726 LHSI->getOperand(0)->hasOneUse()) {
6727 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6728
6729 // If the LHS is an AND of a truncating cast, we can widen the
6730 // and/compare to be the input width without changing the value
6731 // produced, eliminating a cast.
6732 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6733 // We can do this transformation if either the AND constant does not
6734 // have its sign bit set or if it is an equality comparison.
6735 // Extending a relational comparison when we're checking the sign
6736 // bit would not work.
6737 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006738 (ICI.isEquality() ||
6739 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006740 uint32_t BitWidth =
6741 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6742 APInt NewCST = AndCST->getValue();
6743 NewCST.zext(BitWidth);
6744 APInt NewCI = RHSV;
6745 NewCI.zext(BitWidth);
Chris Lattnerc7694852009-08-30 07:44:24 +00006746 Value *NewAnd =
6747 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006748 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00006749 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006750 ConstantInt::get(*Context, NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006751 }
6752 }
6753
6754 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6755 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6756 // happens a LOT in code produced by the C front-end, for bitfield
6757 // access.
6758 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6759 if (Shift && !Shift->isShift())
6760 Shift = 0;
6761
6762 ConstantInt *ShAmt;
6763 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6764 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6765 const Type *AndTy = AndCST->getType(); // Type of the and.
6766
6767 // We can fold this as long as we can't shift unknown bits
6768 // into the mask. This can only happen with signed shift
6769 // rights, as they sign-extend.
6770 if (ShAmt) {
6771 bool CanFold = Shift->isLogicalShift();
6772 if (!CanFold) {
6773 // To test for the bad case of the signed shr, see if any
6774 // of the bits shifted in could be tested after the mask.
6775 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6776 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6777
6778 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6779 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6780 AndCST->getValue()) == 0)
6781 CanFold = true;
6782 }
6783
6784 if (CanFold) {
6785 Constant *NewCst;
6786 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006787 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006788 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006789 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006790
6791 // Check to see if we are shifting out any of the bits being
6792 // compared.
Owen Anderson02b48c32009-07-29 18:55:55 +00006793 if (ConstantExpr::get(Shift->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00006794 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006795 // If we shifted bits out, the fold is not going to work out.
6796 // As a special case, check to see if this means that the
6797 // result is always true or false now.
6798 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006799 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006800 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006801 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006802 } else {
6803 ICI.setOperand(1, NewCst);
6804 Constant *NewAndCST;
6805 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006806 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006807 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006808 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006809 LHSI->setOperand(1, NewAndCST);
6810 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +00006811 Worklist.Add(Shift); // Shift is dead.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006812 return &ICI;
6813 }
6814 }
6815 }
6816
6817 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6818 // preferable because it allows the C<<Y expression to be hoisted out
6819 // of a loop if Y is invariant and X is not.
6820 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00006821 ICI.isEquality() && !Shift->isArithmeticShift() &&
6822 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006823 // Compute C << Y.
6824 Value *NS;
6825 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerc7694852009-08-30 07:44:24 +00006826 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006827 } else {
6828 // Insert a logical shift.
Chris Lattnerc7694852009-08-30 07:44:24 +00006829 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006830 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006831
6832 // Compute X & (C << Y).
Chris Lattnerc7694852009-08-30 07:44:24 +00006833 Value *NewAnd =
6834 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006835
6836 ICI.setOperand(0, NewAnd);
6837 return &ICI;
6838 }
6839 }
6840 break;
6841
6842 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6843 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6844 if (!ShAmt) break;
6845
6846 uint32_t TypeBits = RHSV.getBitWidth();
6847
6848 // Check that the shift amount is in range. If not, don't perform
6849 // undefined shifts. When the shift is visited it will be
6850 // simplified.
6851 if (ShAmt->uge(TypeBits))
6852 break;
6853
6854 if (ICI.isEquality()) {
6855 // If we are comparing against bits always shifted out, the
6856 // comparison cannot succeed.
6857 Constant *Comp =
Owen Anderson02b48c32009-07-29 18:55:55 +00006858 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Anderson24be4c12009-07-03 00:17:18 +00006859 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006860 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6861 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00006862 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006863 return ReplaceInstUsesWith(ICI, Cst);
6864 }
6865
6866 if (LHSI->hasOneUse()) {
6867 // Otherwise strength reduce the shift into an and.
6868 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6869 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006870 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Anderson24be4c12009-07-03 00:17:18 +00006871 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006872
Chris Lattnerc7694852009-08-30 07:44:24 +00006873 Value *And =
6874 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006875 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006876 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006877 }
6878 }
6879
6880 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6881 bool TrueIfSigned = false;
6882 if (LHSI->hasOneUse() &&
6883 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6884 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneacb44d2009-07-24 23:12:02 +00006885 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006886 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattnerc7694852009-08-30 07:44:24 +00006887 Value *And =
6888 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006889 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00006890 And, Constant::getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006891 }
6892 break;
6893 }
6894
6895 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6896 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006897 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006898 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006899 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006900
Chris Lattner5ee84f82008-03-21 05:19:58 +00006901 // Check that the shift amount is in range. If not, don't perform
6902 // undefined shifts. When the shift is visited it will be
6903 // simplified.
6904 uint32_t TypeBits = RHSV.getBitWidth();
6905 if (ShAmt->uge(TypeBits))
6906 break;
6907
6908 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006909
Chris Lattner5ee84f82008-03-21 05:19:58 +00006910 // If we are comparing against bits always shifted out, the
6911 // comparison cannot succeed.
6912 APInt Comp = RHSV << ShAmtVal;
6913 if (LHSI->getOpcode() == Instruction::LShr)
6914 Comp = Comp.lshr(ShAmtVal);
6915 else
6916 Comp = Comp.ashr(ShAmtVal);
6917
6918 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6919 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00006920 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00006921 return ReplaceInstUsesWith(ICI, Cst);
6922 }
6923
6924 // Otherwise, check to see if the bits shifted out are known to be zero.
6925 // If so, we can compare against the unshifted value:
6926 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006927 if (LHSI->hasOneUse() &&
6928 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006929 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006930 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00006931 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006932 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006933
Evan Chengfb9292a2008-04-23 00:38:06 +00006934 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006935 // Otherwise strength reduce the shift into an and.
6936 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00006937 Constant *Mask = ConstantInt::get(*Context, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006938
Chris Lattnerc7694852009-08-30 07:44:24 +00006939 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6940 Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006941 return new ICmpInst(ICI.getPredicate(), And,
Owen Anderson02b48c32009-07-29 18:55:55 +00006942 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006943 }
6944 break;
6945 }
6946
6947 case Instruction::SDiv:
6948 case Instruction::UDiv:
6949 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6950 // Fold this div into the comparison, producing a range check.
6951 // Determine, based on the divide type, what the range is being
6952 // checked. If there is an overflow on the low or high side, remember
6953 // it, otherwise compute the range [low, hi) bounding the new value.
6954 // See: InsertRangeTest above for the kinds of replacements possible.
6955 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6956 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6957 DivRHS))
6958 return R;
6959 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006960
6961 case Instruction::Add:
6962 // Fold: icmp pred (add, X, C1), C2
6963
6964 if (!ICI.isEquality()) {
6965 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6966 if (!LHSC) break;
6967 const APInt &LHSV = LHSC->getValue();
6968
6969 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6970 .subtract(LHSV);
6971
6972 if (ICI.isSignedPredicate()) {
6973 if (CR.getLower().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006974 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006975 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006976 } else if (CR.getUpper().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006977 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006978 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006979 }
6980 } else {
6981 if (CR.getLower().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006982 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006983 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006984 } else if (CR.getUpper().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00006985 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006986 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006987 }
6988 }
6989 }
6990 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006991 }
6992
6993 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6994 if (ICI.isEquality()) {
6995 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6996
6997 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6998 // the second operand is a constant, simplify a bit.
6999 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7000 switch (BO->getOpcode()) {
7001 case Instruction::SRem:
7002 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7003 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7004 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7005 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007006 Value *NewRem =
7007 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7008 BO->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00007009 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersonaac28372009-07-31 20:28:14 +00007010 Constant::getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007011 }
7012 }
7013 break;
7014 case Instruction::Add:
7015 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7016 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7017 if (BO->hasOneUse())
Dan Gohmane6803b82009-08-25 23:17:54 +00007018 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007019 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007020 } else if (RHSV == 0) {
7021 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7022 // efficiently invertible, or if the add has just this one use.
7023 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7024
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007025 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohmane6803b82009-08-25 23:17:54 +00007026 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007027 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohmane6803b82009-08-25 23:17:54 +00007028 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007029 else if (BO->hasOneUse()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007030 Value *Neg = Builder->CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007031 Neg->takeName(BO);
Dan Gohmane6803b82009-08-25 23:17:54 +00007032 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007033 }
7034 }
7035 break;
7036 case Instruction::Xor:
7037 // For the xor case, we can xor two constants together, eliminating
7038 // the explicit xor.
7039 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00007040 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007041 ConstantExpr::getXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007042
7043 // FALLTHROUGH
7044 case Instruction::Sub:
7045 // Replace (([sub|xor] A, B) != 0) with (A != B)
7046 if (RHSV == 0)
Dan Gohmane6803b82009-08-25 23:17:54 +00007047 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007048 BO->getOperand(1));
7049 break;
7050
7051 case Instruction::Or:
7052 // If bits are being or'd in that are not present in the constant we
7053 // are comparing against, then the comparison could never succeed!
7054 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007055 Constant *NotCI = ConstantExpr::getNot(RHS);
7056 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00007057 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007058 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007059 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007060 }
7061 break;
7062
7063 case Instruction::And:
7064 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7065 // If bits are being compared against that are and'd out, then the
7066 // comparison can never succeed!
7067 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007068 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007069 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007070 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007071
7072 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7073 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohmane6803b82009-08-25 23:17:54 +00007074 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007075 ICmpInst::ICMP_NE, LHSI,
Owen Andersonaac28372009-07-31 20:28:14 +00007076 Constant::getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007077
7078 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007079 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007080 Value *X = BO->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +00007081 Constant *Zero = Constant::getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007082 ICmpInst::Predicate pred = isICMP_NE ?
7083 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohmane6803b82009-08-25 23:17:54 +00007084 return new ICmpInst(pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007085 }
7086
7087 // ((X & ~7) == 0) --> X < 8
7088 if (RHSV == 0 && isHighOnes(BOC)) {
7089 Value *X = BO->getOperand(0);
Owen Anderson02b48c32009-07-29 18:55:55 +00007090 Constant *NegX = ConstantExpr::getNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007091 ICmpInst::Predicate pred = isICMP_NE ?
7092 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohmane6803b82009-08-25 23:17:54 +00007093 return new ICmpInst(pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007094 }
7095 }
7096 default: break;
7097 }
7098 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7099 // Handle icmp {eq|ne} <intrinsic>, intcst.
7100 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner3183fb62009-08-30 06:13:40 +00007101 Worklist.Add(II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007102 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007103 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007104 return &ICI;
7105 }
7106 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007107 }
7108 return 0;
7109}
7110
7111/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7112/// We only handle extending casts so far.
7113///
7114Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7115 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7116 Value *LHSCIOp = LHSCI->getOperand(0);
7117 const Type *SrcTy = LHSCIOp->getType();
7118 const Type *DestTy = LHSCI->getType();
7119 Value *RHSCIOp;
7120
7121 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7122 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007123 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7124 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007125 cast<IntegerType>(DestTy)->getBitWidth()) {
7126 Value *RHSOp = 0;
7127 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007128 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007129 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7130 RHSOp = RHSC->getOperand(0);
7131 // If the pointer types don't match, insert a bitcast.
7132 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner78628292009-08-30 19:47:22 +00007133 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007134 }
7135
7136 if (RHSOp)
Dan Gohmane6803b82009-08-25 23:17:54 +00007137 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007138 }
7139
7140 // The code below only handles extension cast instructions, so far.
7141 // Enforce this.
7142 if (LHSCI->getOpcode() != Instruction::ZExt &&
7143 LHSCI->getOpcode() != Instruction::SExt)
7144 return 0;
7145
7146 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7147 bool isSignedCmp = ICI.isSignedPredicate();
7148
7149 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7150 // Not an extension from the same type?
7151 RHSCIOp = CI->getOperand(0);
7152 if (RHSCIOp->getType() != LHSCIOp->getType())
7153 return 0;
7154
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007155 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007156 // and the other is a zext), then we can't handle this.
7157 if (CI->getOpcode() != LHSCI->getOpcode())
7158 return 0;
7159
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007160 // Deal with equality cases early.
7161 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007162 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007163
7164 // A signed comparison of sign extended values simplifies into a
7165 // signed comparison.
7166 if (isSignedCmp && isSignedExt)
Dan Gohmane6803b82009-08-25 23:17:54 +00007167 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007168
7169 // The other three cases all fold into an unsigned comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00007170 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007171 }
7172
7173 // If we aren't dealing with a constant on the RHS, exit early
7174 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7175 if (!CI)
7176 return 0;
7177
7178 // Compute the constant that would happen if we truncated to SrcTy then
7179 // reextended to DestTy.
Owen Anderson02b48c32009-07-29 18:55:55 +00007180 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7181 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007182 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007183
7184 // If the re-extended constant didn't change...
7185 if (Res2 == CI) {
7186 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7187 // For example, we might have:
Dan Gohman9e1657f2009-06-14 23:30:43 +00007188 // %A = sext i16 %X to i32
7189 // %B = icmp ugt i32 %A, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007190 // It is incorrect to transform this into
Dan Gohman9e1657f2009-06-14 23:30:43 +00007191 // %B = icmp ugt i16 %X, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007192 // because %A may have negative value.
7193 //
Chris Lattner3d816532008-07-11 04:09:09 +00007194 // However, we allow this when the compare is EQ/NE, because they are
7195 // signless.
7196 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007197 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00007198 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007199 }
7200
7201 // The re-extended constant changed so the constant cannot be represented
7202 // in the shorter type. Consequently, we cannot emit a simple comparison.
7203
7204 // First, handle some easy cases. We know the result cannot be equal at this
7205 // point so handle the ICI.isEquality() cases
7206 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007207 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007208 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007209 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007210
7211 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7212 // should have been folded away previously and not enter in here.
7213 Value *Result;
7214 if (isSignedCmp) {
7215 // We're performing a signed comparison.
7216 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00007217 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007218 else
Owen Anderson4f720fa2009-07-31 17:39:07 +00007219 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007220 } else {
7221 // We're performing an unsigned comparison.
7222 if (isSignedExt) {
7223 // We're performing an unsigned comp with a sign extended value.
7224 // This is true if the input is >= 0. [aka >s -1]
Owen Andersonaac28372009-07-31 20:28:14 +00007225 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattnerc7694852009-08-30 07:44:24 +00007226 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007227 } else {
7228 // Unsigned extend & unsigned compare -> always true.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007229 Result = ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007230 }
7231 }
7232
7233 // Finally, return the value computed.
7234 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007235 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007236 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007237
7238 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7239 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7240 "ICmp should be folded!");
7241 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00007242 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohmancdff2122009-08-12 16:23:25 +00007243 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007244}
7245
7246Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7247 return commonShiftTransforms(I);
7248}
7249
7250Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7251 return commonShiftTransforms(I);
7252}
7253
7254Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007255 if (Instruction *R = commonShiftTransforms(I))
7256 return R;
7257
7258 Value *Op0 = I.getOperand(0);
7259
7260 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7261 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7262 if (CSI->isAllOnesValue())
7263 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007264
Dan Gohman2526aea2009-06-16 19:55:29 +00007265 // See if we can turn a signed shr into an unsigned shr.
7266 if (MaskedValueIsZero(Op0,
7267 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7268 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7269
7270 // Arithmetic shifting an all-sign-bit value is a no-op.
7271 unsigned NumSignBits = ComputeNumSignBits(Op0);
7272 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7273 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007274
Chris Lattnere3c504f2007-12-06 01:59:46 +00007275 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007276}
7277
7278Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7279 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7280 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7281
7282 // shl X, 0 == X and shr X, 0 == X
7283 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00007284 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7285 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007286 return ReplaceInstUsesWith(I, Op0);
7287
7288 if (isa<UndefValue>(Op0)) {
7289 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7290 return ReplaceInstUsesWith(I, Op0);
7291 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007292 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007293 }
7294 if (isa<UndefValue>(Op1)) {
7295 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7296 return ReplaceInstUsesWith(I, Op0);
7297 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007298 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007299 }
7300
Dan Gohman2bc21562009-05-21 02:28:33 +00007301 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007302 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007303 return &I;
7304
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007305 // Try to fold constant and into select arguments.
7306 if (isa<Constant>(Op0))
7307 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7308 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7309 return R;
7310
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007311 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7312 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7313 return Res;
7314 return 0;
7315}
7316
7317Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7318 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007319 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007320
7321 // See if we can simplify any instructions used by the instruction whose sole
7322 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007323 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007324
Dan Gohman9e1657f2009-06-14 23:30:43 +00007325 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7326 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007327 //
7328 if (Op1->uge(TypeBits)) {
7329 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007330 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007331 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007332 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007333 return &I;
7334 }
7335 }
7336
7337 // ((X*C1) << C2) == (X * (C1 << C2))
7338 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7339 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7340 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007341 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007342 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007343
7344 // Try to fold constant and into select arguments.
7345 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7346 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7347 return R;
7348 if (isa<PHINode>(Op0))
7349 if (Instruction *NV = FoldOpIntoPhi(I))
7350 return NV;
7351
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007352 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7353 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7354 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7355 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7356 // place. Don't try to do this transformation in this case. Also, we
7357 // require that the input operand is a shift-by-constant so that we have
7358 // confidence that the shifts will get folded together. We could do this
7359 // xform in more cases, but it is unlikely to be profitable.
7360 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7361 isa<ConstantInt>(TrOp->getOperand(1))) {
7362 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00007363 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00007364 // (shift2 (shift1 & 0x00FF), c2)
7365 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007366
7367 // For logical shifts, the truncation has the effect of making the high
7368 // part of the register be zeros. Emulate this by inserting an AND to
7369 // clear the top bits as needed. This 'and' will usually be zapped by
7370 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007371 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7372 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007373 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7374
7375 // The mask we constructed says what the trunc would do if occurring
7376 // between the shifts. We want to know the effect *after* the second
7377 // shift. We know that it is a logical shift by a constant, so adjust the
7378 // mask as appropriate.
7379 if (I.getOpcode() == Instruction::Shl)
7380 MaskV <<= Op1->getZExtValue();
7381 else {
7382 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7383 MaskV = MaskV.lshr(Op1->getZExtValue());
7384 }
7385
Chris Lattnerc7694852009-08-30 07:44:24 +00007386 // shift1 & 0x00FF
7387 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7388 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007389
7390 // Return the value truncated to the interesting size.
7391 return new TruncInst(And, I.getType());
7392 }
7393 }
7394
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007395 if (Op0->hasOneUse()) {
7396 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7397 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7398 Value *V1, *V2;
7399 ConstantInt *CC;
7400 switch (Op0BO->getOpcode()) {
7401 default: break;
7402 case Instruction::Add:
7403 case Instruction::And:
7404 case Instruction::Or:
7405 case Instruction::Xor: {
7406 // These operators commute.
7407 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7408 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007409 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerad7516a2009-08-30 18:50:58 +00007410 m_Specific(Op1)))) {
7411 Value *YS = // (Y << C)
7412 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7413 // (X + (Y << C))
7414 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7415 Op0BO->getOperand(1)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007416 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007417 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007418 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7419 }
7420
7421 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7422 Value *Op0BOOp1 = Op0BO->getOperand(1);
7423 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7424 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007425 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007426 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007427 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007428 Value *YS = // (Y << C)
7429 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7430 Op0BO->getName());
7431 // X & (CC << C)
7432 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7433 V1->getName()+".mask");
Gabor Greifa645dd32008-05-16 19:29:10 +00007434 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007435 }
7436 }
7437
7438 // FALL THROUGH.
7439 case Instruction::Sub: {
7440 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7441 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007442 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007443 m_Specific(Op1)))) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007444 Value *YS = // (Y << C)
7445 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7446 // (X + (Y << C))
7447 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7448 Op0BO->getOperand(0)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007449 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007450 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007451 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7452 }
7453
7454 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7455 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7456 match(Op0BO->getOperand(0),
7457 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007458 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007459 cast<BinaryOperator>(Op0BO->getOperand(0))
7460 ->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007461 Value *YS = // (Y << C)
7462 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7463 // X & (CC << C)
7464 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7465 V1->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007466
Gabor Greifa645dd32008-05-16 19:29:10 +00007467 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007468 }
7469
7470 break;
7471 }
7472 }
7473
7474
7475 // If the operand is an bitwise operator with a constant RHS, and the
7476 // shift is the only use, we can pull it out of the shift.
7477 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7478 bool isValid = true; // Valid only for And, Or, Xor
7479 bool highBitSet = false; // Transform if high bit of constant set?
7480
7481 switch (Op0BO->getOpcode()) {
7482 default: isValid = false; break; // Do not perform transform!
7483 case Instruction::Add:
7484 isValid = isLeftShift;
7485 break;
7486 case Instruction::Or:
7487 case Instruction::Xor:
7488 highBitSet = false;
7489 break;
7490 case Instruction::And:
7491 highBitSet = true;
7492 break;
7493 }
7494
7495 // If this is a signed shift right, and the high bit is modified
7496 // by the logical operation, do not perform the transformation.
7497 // The highBitSet boolean indicates the value of the high bit of
7498 // the constant which would cause it to be modified for this
7499 // operation.
7500 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007501 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007502 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007503
7504 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007505 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007506
Chris Lattnerad7516a2009-08-30 18:50:58 +00007507 Value *NewShift =
7508 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007509 NewShift->takeName(Op0BO);
7510
Gabor Greifa645dd32008-05-16 19:29:10 +00007511 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007512 NewRHS);
7513 }
7514 }
7515 }
7516 }
7517
7518 // Find out if this is a shift of a shift by a constant.
7519 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7520 if (ShiftOp && !ShiftOp->isShift())
7521 ShiftOp = 0;
7522
7523 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7524 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7525 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7526 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7527 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7528 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7529 Value *X = ShiftOp->getOperand(0);
7530
7531 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007532
7533 const IntegerType *Ty = cast<IntegerType>(I.getType());
7534
7535 // Check for (X << c1) << c2 and (X >> c1) >> c2
7536 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007537 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7538 // saturates.
7539 if (AmtSum >= TypeBits) {
7540 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007541 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007542 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7543 }
7544
Gabor Greifa645dd32008-05-16 19:29:10 +00007545 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007546 ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007547 }
7548
7549 if (ShiftOp->getOpcode() == Instruction::LShr &&
7550 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007551 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00007552 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007553
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007554 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00007555 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007556 }
7557
7558 if (ShiftOp->getOpcode() == Instruction::AShr &&
7559 I.getOpcode() == Instruction::LShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007560 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007561 if (AmtSum >= TypeBits)
7562 AmtSum = TypeBits-1;
7563
Chris Lattnerad7516a2009-08-30 18:50:58 +00007564 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007565
7566 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007567 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007568 }
7569
7570 // Okay, if we get here, one shift must be left, and the other shift must be
7571 // right. See if the amounts are equal.
7572 if (ShiftAmt1 == ShiftAmt2) {
7573 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7574 if (I.getOpcode() == Instruction::Shl) {
7575 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007576 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007577 }
7578 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7579 if (I.getOpcode() == Instruction::LShr) {
7580 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007581 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007582 }
7583 // We can simplify ((X << C) >>s C) into a trunc + sext.
7584 // NOTE: we could do this for any C, but that would make 'unusual' integer
7585 // types. For now, just stick to ones well-supported by the code
7586 // generators.
7587 const Type *SExtType = 0;
7588 switch (Ty->getBitWidth() - ShiftAmt1) {
7589 case 1 :
7590 case 8 :
7591 case 16 :
7592 case 32 :
7593 case 64 :
7594 case 128:
Owen Anderson35b47072009-08-13 21:58:54 +00007595 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007596 break;
7597 default: break;
7598 }
Chris Lattnerad7516a2009-08-30 18:50:58 +00007599 if (SExtType)
7600 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007601 // Otherwise, we can't handle it yet.
7602 } else if (ShiftAmt1 < ShiftAmt2) {
7603 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7604
7605 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7606 if (I.getOpcode() == Instruction::Shl) {
7607 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7608 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007609 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007610
7611 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007612 return BinaryOperator::CreateAnd(Shift,
7613 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007614 }
7615
7616 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7617 if (I.getOpcode() == Instruction::LShr) {
7618 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007619 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007620
7621 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007622 return BinaryOperator::CreateAnd(Shift,
7623 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007624 }
7625
7626 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7627 } else {
7628 assert(ShiftAmt2 < ShiftAmt1);
7629 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7630
7631 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7632 if (I.getOpcode() == Instruction::Shl) {
7633 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7634 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007635 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7636 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007637
7638 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007639 return BinaryOperator::CreateAnd(Shift,
7640 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007641 }
7642
7643 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7644 if (I.getOpcode() == Instruction::LShr) {
7645 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007646 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007647
7648 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007649 return BinaryOperator::CreateAnd(Shift,
7650 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007651 }
7652
7653 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7654 }
7655 }
7656 return 0;
7657}
7658
7659
7660/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7661/// expression. If so, decompose it, returning some value X, such that Val is
7662/// X*Scale+Offset.
7663///
7664static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007665 int &Offset, LLVMContext *Context) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007666 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7667 "Unexpected allocation size type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007668 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7669 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007670 Scale = 0;
Owen Anderson35b47072009-08-13 21:58:54 +00007671 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007672 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7673 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7674 if (I->getOpcode() == Instruction::Shl) {
7675 // This is a value scaled by '1 << the shift amt'.
7676 Scale = 1U << RHS->getZExtValue();
7677 Offset = 0;
7678 return I->getOperand(0);
7679 } else if (I->getOpcode() == Instruction::Mul) {
7680 // This value is scaled by 'RHS'.
7681 Scale = RHS->getZExtValue();
7682 Offset = 0;
7683 return I->getOperand(0);
7684 } else if (I->getOpcode() == Instruction::Add) {
7685 // We have X+C. Check to see if we really have (X*C2)+C1,
7686 // where C1 is divisible by C2.
7687 unsigned SubScale;
7688 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00007689 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7690 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007691 Offset += RHS->getZExtValue();
7692 Scale = SubScale;
7693 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007694 }
7695 }
7696 }
7697
7698 // Otherwise, we can't look past this.
7699 Scale = 1;
7700 Offset = 0;
7701 return Val;
7702}
7703
7704
7705/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7706/// try to eliminate the cast by moving the type information into the alloc.
7707Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7708 AllocationInst &AI) {
7709 const PointerType *PTy = cast<PointerType>(CI.getType());
7710
Chris Lattnerad7516a2009-08-30 18:50:58 +00007711 BuilderTy AllocaBuilder(*Builder);
7712 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7713
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007714 // Remove any uses of AI that are dead.
7715 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7716
7717 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7718 Instruction *User = cast<Instruction>(*UI++);
7719 if (isInstructionTriviallyDead(User)) {
7720 while (UI != E && *UI == User)
7721 ++UI; // If this instruction uses AI more than once, don't break UI.
7722
7723 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00007724 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007725 EraseInstFromFunction(*User);
7726 }
7727 }
Dan Gohmana80e2712009-07-21 23:21:54 +00007728
7729 // This requires TargetData to get the alloca alignment and size information.
7730 if (!TD) return 0;
7731
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007732 // Get the type really allocated and the type casted to.
7733 const Type *AllocElTy = AI.getAllocatedType();
7734 const Type *CastElTy = PTy->getElementType();
7735 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7736
7737 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7738 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7739 if (CastElTyAlign < AllocElTyAlign) return 0;
7740
7741 // If the allocation has multiple uses, only promote it if we are strictly
7742 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007743 // same, we open the door to infinite loops of various kinds. (A reference
7744 // from a dbg.declare doesn't count as a use for this purpose.)
7745 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7746 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007747
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007748 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7749 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007750 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7751
7752 // See if we can satisfy the modulus by pulling a scale out of the array
7753 // size argument.
7754 unsigned ArraySizeScale;
7755 int ArrayOffset;
7756 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00007757 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7758 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007759
7760 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7761 // do the xform.
7762 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7763 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7764
7765 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7766 Value *Amt = 0;
7767 if (Scale == 1) {
7768 Amt = NumElements;
7769 } else {
Owen Anderson35b47072009-08-13 21:58:54 +00007770 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007771 // Insert before the alloca, not before the cast.
7772 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007773 }
7774
7775 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson35b47072009-08-13 21:58:54 +00007776 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007777 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007778 }
7779
7780 AllocationInst *New;
7781 if (isa<MallocInst>(AI))
Chris Lattnerad7516a2009-08-30 18:50:58 +00007782 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007783 else
Chris Lattnerad7516a2009-08-30 18:50:58 +00007784 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7785 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007786 New->takeName(&AI);
7787
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007788 // If the allocation has one real use plus a dbg.declare, just remove the
7789 // declare.
7790 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7791 EraseInstFromFunction(*DI);
7792 }
7793 // If the allocation has multiple real uses, insert a cast and change all
7794 // things that used it to use the new cast. This will also hack on CI, but it
7795 // will die soon.
7796 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007797 // New is the allocation instruction, pointer typed. AI is the original
7798 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerad7516a2009-08-30 18:50:58 +00007799 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007800 AI.replaceAllUsesWith(NewCast);
7801 }
7802 return ReplaceInstUsesWith(CI, New);
7803}
7804
7805/// CanEvaluateInDifferentType - Return true if we can take the specified value
7806/// and return it as type Ty without inserting any new casts and without
7807/// changing the computed value. This is used by code that tries to decide
7808/// whether promoting or shrinking integer operations to wider or smaller types
7809/// will allow us to eliminate a truncate or extend.
7810///
7811/// This is a truncation operation if Ty is smaller than V->getType(), or an
7812/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007813///
7814/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7815/// should return true if trunc(V) can be computed by computing V in the smaller
7816/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7817/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7818/// efficiently truncated.
7819///
7820/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7821/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7822/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007823bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00007824 unsigned CastOpc,
7825 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007826 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007827 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007828 return true;
7829
7830 Instruction *I = dyn_cast<Instruction>(V);
7831 if (!I) return false;
7832
Dan Gohman8fd520a2009-06-15 22:12:54 +00007833 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007834
Chris Lattneref70bb82007-08-02 06:11:14 +00007835 // If this is an extension or truncate, we can often eliminate it.
7836 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7837 // If this is a cast from the destination type, we can trivially eliminate
7838 // it, and this will remove a cast overall.
7839 if (I->getOperand(0)->getType() == Ty) {
7840 // If the first operand is itself a cast, and is eliminable, do not count
7841 // this as an eliminable cast. We would prefer to eliminate those two
7842 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007843 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007844 ++NumCastsRemoved;
7845 return true;
7846 }
7847 }
7848
7849 // We can't extend or shrink something that has multiple uses: doing so would
7850 // require duplicating the instruction in general, which isn't profitable.
7851 if (!I->hasOneUse()) return false;
7852
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007853 unsigned Opc = I->getOpcode();
7854 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007855 case Instruction::Add:
7856 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007857 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007858 case Instruction::And:
7859 case Instruction::Or:
7860 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007861 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007862 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007863 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007864 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007865 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007866
Eli Friedman08c45bc2009-07-13 22:46:01 +00007867 case Instruction::UDiv:
7868 case Instruction::URem: {
7869 // UDiv and URem can be truncated if all the truncated bits are zero.
7870 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7871 uint32_t BitWidth = Ty->getScalarSizeInBits();
7872 if (BitWidth < OrigBitWidth) {
7873 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7874 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7875 MaskedValueIsZero(I->getOperand(1), Mask)) {
7876 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7877 NumCastsRemoved) &&
7878 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7879 NumCastsRemoved);
7880 }
7881 }
7882 break;
7883 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007884 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007885 // If we are truncating the result of this SHL, and if it's a shift of a
7886 // constant amount, we can always perform a SHL in a smaller type.
7887 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007888 uint32_t BitWidth = Ty->getScalarSizeInBits();
7889 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007890 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007891 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007892 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007893 }
7894 break;
7895 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007896 // If this is a truncate of a logical shr, we can truncate it to a smaller
7897 // lshr iff we know that the bits we would otherwise be shifting in are
7898 // already zeros.
7899 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007900 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7901 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007902 if (BitWidth < OrigBitWidth &&
7903 MaskedValueIsZero(I->getOperand(0),
7904 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7905 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007906 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007907 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007908 }
7909 }
7910 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007911 case Instruction::ZExt:
7912 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007913 case Instruction::Trunc:
7914 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007915 // can safely replace it. Note that replacing it does not reduce the number
7916 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007917 if (Opc == CastOpc)
7918 return true;
7919
7920 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00007921 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007922 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007923 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007924 case Instruction::Select: {
7925 SelectInst *SI = cast<SelectInst>(I);
7926 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007927 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007928 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007929 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007930 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007931 case Instruction::PHI: {
7932 // We can change a phi if we can change all operands.
7933 PHINode *PN = cast<PHINode>(I);
7934 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7935 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007936 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00007937 return false;
7938 return true;
7939 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007940 default:
7941 // TODO: Can handle more cases here.
7942 break;
7943 }
7944
7945 return false;
7946}
7947
7948/// EvaluateInDifferentType - Given an expression that
7949/// CanEvaluateInDifferentType returns true for, actually insert the code to
7950/// evaluate the expression.
7951Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7952 bool isSigned) {
7953 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +00007954 return ConstantExpr::getIntegerCast(C, Ty,
Owen Anderson24be4c12009-07-03 00:17:18 +00007955 isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007956
7957 // Otherwise, it must be an instruction.
7958 Instruction *I = cast<Instruction>(V);
7959 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007960 unsigned Opc = I->getOpcode();
7961 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007962 case Instruction::Add:
7963 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007964 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007965 case Instruction::And:
7966 case Instruction::Or:
7967 case Instruction::Xor:
7968 case Instruction::AShr:
7969 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00007970 case Instruction::Shl:
7971 case Instruction::UDiv:
7972 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007973 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7974 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007975 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007976 break;
7977 }
7978 case Instruction::Trunc:
7979 case Instruction::ZExt:
7980 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007981 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007982 // just return the source. There's no need to insert it because it is not
7983 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007984 if (I->getOperand(0)->getType() == Ty)
7985 return I->getOperand(0);
7986
Chris Lattner4200c2062008-06-18 04:00:49 +00007987 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007988 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00007989 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00007990 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007991 case Instruction::Select: {
7992 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7993 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7994 Res = SelectInst::Create(I->getOperand(0), True, False);
7995 break;
7996 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007997 case Instruction::PHI: {
7998 PHINode *OPN = cast<PHINode>(I);
7999 PHINode *NPN = PHINode::Create(Ty);
8000 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8001 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8002 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8003 }
8004 Res = NPN;
8005 break;
8006 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008007 default:
8008 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00008009 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008010 break;
8011 }
8012
Chris Lattner4200c2062008-06-18 04:00:49 +00008013 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008014 return InsertNewInstBefore(Res, *I);
8015}
8016
8017/// @brief Implement the transforms common to all CastInst visitors.
8018Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8019 Value *Src = CI.getOperand(0);
8020
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008021 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8022 // eliminate it now.
8023 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8024 if (Instruction::CastOps opc =
8025 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8026 // The first cast (CSrc) is eliminable so we need to fix up or replace
8027 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008028 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008029 }
8030 }
8031
8032 // If we are casting a select then fold the cast into the select
8033 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8034 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8035 return NV;
8036
8037 // If we are casting a PHI then fold the cast into the PHI
8038 if (isa<PHINode>(Src))
8039 if (Instruction *NV = FoldOpIntoPhi(CI))
8040 return NV;
8041
8042 return 0;
8043}
8044
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008045/// FindElementAtOffset - Given a type and a constant offset, determine whether
8046/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008047/// the specified offset. If so, fill them into NewIndices and return the
8048/// resultant element type, otherwise return null.
8049static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8050 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008051 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008052 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008053 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008054 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008055
8056 // Start with the index over the outer type. Note that the type size
8057 // might be zero (even if the offset isn't zero) if the indexed type
8058 // is something like [0 x {int, int}]
Owen Anderson35b47072009-08-13 21:58:54 +00008059 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008060 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008061 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008062 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008063 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008064
Chris Lattnerce48c462009-01-11 20:15:20 +00008065 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008066 if (Offset < 0) {
8067 --FirstIdx;
8068 Offset += TySize;
8069 assert(Offset >= 0);
8070 }
8071 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8072 }
8073
Owen Andersoneacb44d2009-07-24 23:12:02 +00008074 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008075
8076 // Index into the types. If we fail, set OrigBase to null.
8077 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008078 // Indexing into tail padding between struct/array elements.
8079 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008080 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008081
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008082 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8083 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008084 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8085 "Offset must stay within the indexed type");
8086
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008087 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson35b47072009-08-13 21:58:54 +00008088 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008089
8090 Offset -= SL->getElementOffset(Elt);
8091 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008092 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008093 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008094 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00008095 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008096 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008097 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008098 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008099 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008100 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008101 }
8102 }
8103
Chris Lattner54dddc72009-01-24 01:00:13 +00008104 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008105}
8106
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008107/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8108Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8109 Value *Src = CI.getOperand(0);
8110
8111 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8112 // If casting the result of a getelementptr instruction with no offset, turn
8113 // this into a cast of the original pointer!
8114 if (GEP->hasAllZeroIndices()) {
8115 // Changing the cast operand is usually not a good idea but it is safe
8116 // here because the pointer operand is being replaced with another
8117 // pointer operand so the opcode doesn't need to change.
Chris Lattner3183fb62009-08-30 06:13:40 +00008118 Worklist.Add(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008119 CI.setOperand(0, GEP->getOperand(0));
8120 return &CI;
8121 }
8122
8123 // If the GEP has a single use, and the base pointer is a bitcast, and the
8124 // GEP computes a constant offset, see if we can convert these three
8125 // instructions into fewer. This typically happens with unions and other
8126 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008127 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008128 if (GEP->hasAllConstantIndices()) {
8129 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +00008130 ConstantInt *OffsetV =
8131 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008132 int64_t Offset = OffsetV->getSExtValue();
8133
8134 // Get the base pointer input of the bitcast, and the type it points to.
8135 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8136 const Type *GEPIdxTy =
8137 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008138 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008139 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008140 // If we were able to index down into an element, create the GEP
8141 // and bitcast the result. This eliminates one bitcast, potentially
8142 // two.
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008143 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8144 Builder->CreateInBoundsGEP(OrigBase,
8145 NewIndices.begin(), NewIndices.end()) :
8146 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008147 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008148
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008149 if (isa<BitCastInst>(CI))
8150 return new BitCastInst(NGEP, CI.getType());
8151 assert(isa<PtrToIntInst>(CI));
8152 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008153 }
8154 }
8155 }
8156 }
8157
8158 return commonCastTransforms(CI);
8159}
8160
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008161/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8162/// type like i42. We don't want to introduce operations on random non-legal
8163/// integer types where they don't already exist in the code. In the future,
8164/// we should consider making this based off target-data, so that 32-bit targets
8165/// won't get i64 operations etc.
8166static bool isSafeIntegerType(const Type *Ty) {
8167 switch (Ty->getPrimitiveSizeInBits()) {
8168 case 8:
8169 case 16:
8170 case 32:
8171 case 64:
8172 return true;
8173 default:
8174 return false;
8175 }
8176}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008177
Eli Friedman827e37a2009-07-13 20:58:59 +00008178/// commonIntCastTransforms - This function implements the common transforms
8179/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008180Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8181 if (Instruction *Result = commonCastTransforms(CI))
8182 return Result;
8183
8184 Value *Src = CI.getOperand(0);
8185 const Type *SrcTy = Src->getType();
8186 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008187 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8188 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008189
8190 // See if we can simplify any instructions used by the LHS whose sole
8191 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008192 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008193 return &CI;
8194
8195 // If the source isn't an instruction or has more than one use then we
8196 // can't do anything more.
8197 Instruction *SrcI = dyn_cast<Instruction>(Src);
8198 if (!SrcI || !Src->hasOneUse())
8199 return 0;
8200
8201 // Attempt to propagate the cast into the instruction for int->int casts.
8202 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008203 // Only do this if the dest type is a simple type, don't convert the
8204 // expression tree to something weird like i93 unless the source is also
8205 // strange.
8206 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman8fd520a2009-06-15 22:12:54 +00008207 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8208 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng814a00c2009-01-16 02:11:43 +00008209 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008210 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008211 // eliminates the cast, so it is always a win. If this is a zero-extension,
8212 // we need to do an AND to maintain the clear top-part of the computation,
8213 // so we require that the input have eliminated at least one cast. If this
8214 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008215 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008216 bool DoXForm = false;
8217 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008218 switch (CI.getOpcode()) {
8219 default:
8220 // All the others use floating point so we shouldn't actually
8221 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008222 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008223 case Instruction::Trunc:
8224 DoXForm = true;
8225 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008226 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008227 DoXForm = NumCastsRemoved >= 1;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008228 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008229 // If it's unnecessary to issue an AND to clear the high bits, it's
8230 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008231 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008232 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8233 if (MaskedValueIsZero(TryRes, Mask))
8234 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008235
8236 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008237 if (TryI->use_empty())
8238 EraseInstFromFunction(*TryI);
8239 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008240 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008241 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008242 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008243 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008244 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008245 // If we do not have to emit the truncate + sext pair, then it's always
8246 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008247 //
8248 // It's not safe to eliminate the trunc + sext pair if one of the
8249 // eliminated cast is a truncate. e.g.
8250 // t2 = trunc i32 t1 to i16
8251 // t3 = sext i16 t2 to i32
8252 // !=
8253 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008254 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008255 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8256 if (NumSignBits > (DestBitSize - SrcBitSize))
8257 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008258
8259 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008260 if (TryI->use_empty())
8261 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008262 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008263 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008264 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008265 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008266
8267 if (DoXForm) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00008268 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8269 " to avoid cast: " << CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008270 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8271 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008272 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008273 // Just replace this cast with the result.
8274 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008275
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008276 assert(Res->getType() == DestTy);
8277 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008278 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008279 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008280 // Just replace this cast with the result.
8281 return ReplaceInstUsesWith(CI, Res);
8282 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008283 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008284
8285 // If the high bits are already zero, just replace this cast with the
8286 // result.
8287 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8288 if (MaskedValueIsZero(Res, Mask))
8289 return ReplaceInstUsesWith(CI, Res);
8290
8291 // We need to emit an AND to clear the high bits.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008292 Constant *C = ConstantInt::get(*Context,
8293 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008294 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008295 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008296 case Instruction::SExt: {
8297 // If the high bits are already filled with sign bit, just replace this
8298 // cast with the result.
8299 unsigned NumSignBits = ComputeNumSignBits(Res);
8300 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008301 return ReplaceInstUsesWith(CI, Res);
8302
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008303 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008304 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008305 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008306 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008307 }
8308 }
8309
8310 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8311 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8312
8313 switch (SrcI->getOpcode()) {
8314 case Instruction::Add:
8315 case Instruction::Mul:
8316 case Instruction::And:
8317 case Instruction::Or:
8318 case Instruction::Xor:
8319 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008320 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8321 // Don't insert two casts unless at least one can be eliminated.
8322 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008323 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008324 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8325 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008326 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008327 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8328 }
8329 }
8330
8331 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8332 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8333 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson4f720fa2009-07-31 17:39:07 +00008334 Op1 == ConstantInt::getTrue(*Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008335 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008336 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Anderson24be4c12009-07-03 00:17:18 +00008337 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008338 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008339 }
8340 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008341
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008342 case Instruction::Shl: {
8343 // Canonicalize trunc inside shl, if we can.
8344 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8345 if (CI && DestBitSize < SrcBitSize &&
8346 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008347 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8348 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008349 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008350 }
8351 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008352 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008353 }
8354 return 0;
8355}
8356
8357Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8358 if (Instruction *Result = commonIntCastTransforms(CI))
8359 return Result;
8360
8361 Value *Src = CI.getOperand(0);
8362 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008363 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8364 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008365
8366 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008367 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008368 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008369 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersonaac28372009-07-31 20:28:14 +00008370 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohmane6803b82009-08-25 23:17:54 +00008371 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008372 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008373
Chris Lattner32177f82009-03-24 18:15:30 +00008374 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8375 ConstantInt *ShAmtV = 0;
8376 Value *ShiftOp = 0;
8377 if (Src->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00008378 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner32177f82009-03-24 18:15:30 +00008379 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8380
8381 // Get a mask for the bits shifting in.
8382 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8383 if (MaskedValueIsZero(ShiftOp, Mask)) {
8384 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00008385 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008386
8387 // Okay, we can shrink this. Truncate the input, then return a new
8388 // shift.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008389 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Anderson02b48c32009-07-29 18:55:55 +00008390 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008391 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008392 }
8393 }
8394
8395 return 0;
8396}
8397
Evan Chenge3779cf2008-03-24 00:21:34 +00008398/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8399/// in order to eliminate the icmp.
8400Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8401 bool DoXform) {
8402 // If we are just checking for a icmp eq of a single bit and zext'ing it
8403 // to an integer, then shift the bit to the appropriate place and then
8404 // cast to integer to avoid the comparison.
8405 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8406 const APInt &Op1CV = Op1C->getValue();
8407
8408 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8409 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8410 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8411 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8412 if (!DoXform) return ICI;
8413
8414 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008415 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008416 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008417 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008418 if (In->getType() != CI.getType())
Chris Lattnerad7516a2009-08-30 18:50:58 +00008419 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008420
8421 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008422 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008423 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chenge3779cf2008-03-24 00:21:34 +00008424 }
8425
8426 return ReplaceInstUsesWith(CI, In);
8427 }
8428
8429
8430
8431 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8432 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8433 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8434 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8435 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8436 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8437 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8438 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8439 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8440 // This only works for EQ and NE
8441 ICI->isEquality()) {
8442 // If Op1C some other power of two, convert:
8443 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8444 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8445 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8446 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8447
8448 APInt KnownZeroMask(~KnownZero);
8449 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8450 if (!DoXform) return ICI;
8451
8452 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8453 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8454 // (X&4) == 2 --> false
8455 // (X&4) != 2 --> true
Owen Anderson35b47072009-08-13 21:58:54 +00008456 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00008457 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008458 return ReplaceInstUsesWith(CI, Res);
8459 }
8460
8461 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8462 Value *In = ICI->getOperand(0);
8463 if (ShiftAmt) {
8464 // Perform a logical shr by shiftamt.
8465 // Insert the shift to put the result in the low bit.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008466 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8467 In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008468 }
8469
8470 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008471 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008472 In = Builder->CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008473 }
8474
8475 if (CI.getType() == In->getType())
8476 return ReplaceInstUsesWith(CI, In);
8477 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008478 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008479 }
8480 }
8481 }
8482
8483 return 0;
8484}
8485
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008486Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8487 // If one of the common conversion will work ..
8488 if (Instruction *Result = commonIntCastTransforms(CI))
8489 return Result;
8490
8491 Value *Src = CI.getOperand(0);
8492
Chris Lattner215d56e2009-02-17 20:47:23 +00008493 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8494 // types and if the sizes are just right we can convert this into a logical
8495 // 'and' which will be much cheaper than the pair of casts.
8496 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8497 // Get the sizes of the types involved. We know that the intermediate type
8498 // will be smaller than A or C, but don't know the relation between A and C.
8499 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008500 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8501 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8502 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008503 // If we're actually extending zero bits, then if
8504 // SrcSize < DstSize: zext(a & mask)
8505 // SrcSize == DstSize: a & mask
8506 // SrcSize > DstSize: trunc(a) & mask
8507 if (SrcSize < DstSize) {
8508 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008509 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008510 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattner215d56e2009-02-17 20:47:23 +00008511 return new ZExtInst(And, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008512 }
8513
8514 if (SrcSize == DstSize) {
Chris Lattner215d56e2009-02-17 20:47:23 +00008515 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008516 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008517 AndValue));
Chris Lattnerad7516a2009-08-30 18:50:58 +00008518 }
8519 if (SrcSize > DstSize) {
8520 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattner215d56e2009-02-17 20:47:23 +00008521 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008522 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008523 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008524 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008525 }
8526 }
8527
Evan Chenge3779cf2008-03-24 00:21:34 +00008528 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8529 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008530
Evan Chenge3779cf2008-03-24 00:21:34 +00008531 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8532 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8533 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8534 // of the (zext icmp) will be transformed.
8535 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8536 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8537 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8538 (transformZExtICmp(LHS, CI, false) ||
8539 transformZExtICmp(RHS, CI, false))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008540 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8541 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008542 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008543 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008544 }
8545
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008546 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008547 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8548 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8549 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8550 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008551 if (TI0->getType() == CI.getType())
8552 return
8553 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00008554 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008555 }
8556
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008557 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8558 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8559 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8560 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8561 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8562 And->getOperand(1) == C)
8563 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8564 Value *TI0 = TI->getOperand(0);
8565 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00008566 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008567 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008568 return BinaryOperator::CreateXor(NewAnd, ZC);
8569 }
8570 }
8571
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008572 return 0;
8573}
8574
8575Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8576 if (Instruction *I = commonIntCastTransforms(CI))
8577 return I;
8578
8579 Value *Src = CI.getOperand(0);
8580
Dan Gohman35b76162008-10-30 20:40:10 +00008581 // Canonicalize sign-extend from i1 to a select.
Owen Anderson35b47072009-08-13 21:58:54 +00008582 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman35b76162008-10-30 20:40:10 +00008583 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00008584 Constant::getAllOnesValue(CI.getType()),
8585 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008586
8587 // See if the value being truncated is already sign extended. If so, just
8588 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00008589 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00008590 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008591 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8592 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8593 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008594 unsigned NumSignBits = ComputeNumSignBits(Op);
8595
8596 if (OpBits == DestBits) {
8597 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8598 // bits, it is already ready.
8599 if (NumSignBits > DestBits-MidBits)
8600 return ReplaceInstUsesWith(CI, Op);
8601 } else if (OpBits < DestBits) {
8602 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8603 // bits, just sext from i32.
8604 if (NumSignBits > OpBits-MidBits)
8605 return new SExtInst(Op, CI.getType(), "tmp");
8606 } else {
8607 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8608 // bits, just truncate to i32.
8609 if (NumSignBits > OpBits-MidBits)
8610 return new TruncInst(Op, CI.getType(), "tmp");
8611 }
8612 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008613
8614 // If the input is a shl/ashr pair of a same constant, then this is a sign
8615 // extension from a smaller value. If we could trust arbitrary bitwidth
8616 // integers, we could turn this into a truncate to the smaller bit and then
8617 // use a sext for the whole extension. Since we don't, look deeper and check
8618 // for a truncate. If the source and dest are the same type, eliminate the
8619 // trunc and extend and just do shifts. For example, turn:
8620 // %a = trunc i32 %i to i8
8621 // %b = shl i8 %a, 6
8622 // %c = ashr i8 %b, 6
8623 // %d = sext i8 %c to i32
8624 // into:
8625 // %a = shl i32 %i, 30
8626 // %d = ashr i32 %a, 30
8627 Value *A = 0;
8628 ConstantInt *BA = 0, *CA = 0;
8629 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohmancdff2122009-08-12 16:23:25 +00008630 m_ConstantInt(CA))) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008631 BA == CA && isa<TruncInst>(A)) {
8632 Value *I = cast<TruncInst>(A)->getOperand(0);
8633 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008634 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8635 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008636 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00008637 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008638 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner8a2d0592008-08-06 07:35:52 +00008639 return BinaryOperator::CreateAShr(I, ShAmtV);
8640 }
8641 }
8642
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008643 return 0;
8644}
8645
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008646/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8647/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008648static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008649 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008650 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008651 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008652 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8653 if (!losesInfo)
Owen Andersond363a0e2009-07-27 20:59:43 +00008654 return ConstantFP::get(*Context, F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008655 return 0;
8656}
8657
8658/// LookThroughFPExtensions - If this is an fp extension instruction, look
8659/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00008660static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008661 if (Instruction *I = dyn_cast<Instruction>(V))
8662 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00008663 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008664
8665 // If this value is a constant, return the constant in the smallest FP type
8666 // that can accurately represent it. This allows us to turn
8667 // (float)((double)X+2.0) into x+2.0f.
8668 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +00008669 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008670 return V; // No constant folding of this.
8671 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00008672 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008673 return V;
Owen Anderson35b47072009-08-13 21:58:54 +00008674 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008675 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00008676 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008677 return V;
8678 // Don't try to shrink to various long double types.
8679 }
8680
8681 return V;
8682}
8683
8684Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8685 if (Instruction *I = commonCastTransforms(CI))
8686 return I;
8687
Dan Gohman7ce405e2009-06-04 22:49:04 +00008688 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008689 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008690 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008691 // many builtins (sqrt, etc).
8692 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8693 if (OpI && OpI->hasOneUse()) {
8694 switch (OpI->getOpcode()) {
8695 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008696 case Instruction::FAdd:
8697 case Instruction::FSub:
8698 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008699 case Instruction::FDiv:
8700 case Instruction::FRem:
8701 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00008702 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8703 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008704 if (LHSTrunc->getType() != SrcTy &&
8705 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008706 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008707 // If the source types were both smaller than the destination type of
8708 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008709 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8710 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008711 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8712 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00008713 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008714 }
8715 }
8716 break;
8717 }
8718 }
8719 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008720}
8721
8722Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8723 return commonCastTransforms(CI);
8724}
8725
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008726Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008727 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8728 if (OpI == 0)
8729 return commonCastTransforms(FI);
8730
8731 // fptoui(uitofp(X)) --> X
8732 // fptoui(sitofp(X)) --> X
8733 // This is safe if the intermediate type has enough bits in its mantissa to
8734 // accurately represent all values of X. For example, do not do this with
8735 // i64->float->i64. This is also safe for sitofp case, because any negative
8736 // 'X' value would cause an undefined result for the fptoui.
8737 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8738 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008739 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008740 OpI->getType()->getFPMantissaWidth())
8741 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008742
8743 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008744}
8745
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008746Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008747 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8748 if (OpI == 0)
8749 return commonCastTransforms(FI);
8750
8751 // fptosi(sitofp(X)) --> X
8752 // fptosi(uitofp(X)) --> X
8753 // This is safe if the intermediate type has enough bits in its mantissa to
8754 // accurately represent all values of X. For example, do not do this with
8755 // i64->float->i64. This is also safe for sitofp case, because any negative
8756 // 'X' value would cause an undefined result for the fptoui.
8757 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8758 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008759 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008760 OpI->getType()->getFPMantissaWidth())
8761 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008762
8763 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008764}
8765
8766Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8767 return commonCastTransforms(CI);
8768}
8769
8770Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8771 return commonCastTransforms(CI);
8772}
8773
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008774Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8775 // If the destination integer type is smaller than the intptr_t type for
8776 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8777 // trunc to be exposed to other transforms. Don't do this for extending
8778 // ptrtoint's, because we don't know if the target sign or zero extends its
8779 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008780 if (TD &&
8781 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008782 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8783 TD->getIntPtrType(CI.getContext()),
8784 "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008785 return new TruncInst(P, CI.getType());
8786 }
8787
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008788 return commonPointerCastTransforms(CI);
8789}
8790
Chris Lattner7c1626482008-01-08 07:23:51 +00008791Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008792 // If the source integer type is larger than the intptr_t type for
8793 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8794 // allows the trunc to be exposed to other transforms. Don't do this for
8795 // extending inttoptr's, because we don't know if the target sign or zero
8796 // extends to pointers.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008797 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008798 TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008799 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8800 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008801 return new IntToPtrInst(P, CI.getType());
8802 }
8803
Chris Lattner7c1626482008-01-08 07:23:51 +00008804 if (Instruction *I = commonCastTransforms(CI))
8805 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00008806
Chris Lattner7c1626482008-01-08 07:23:51 +00008807 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008808}
8809
8810Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8811 // If the operands are integer typed then apply the integer transforms,
8812 // otherwise just apply the common ones.
8813 Value *Src = CI.getOperand(0);
8814 const Type *SrcTy = Src->getType();
8815 const Type *DestTy = CI.getType();
8816
Eli Friedman5013d3f2009-07-13 20:53:00 +00008817 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008818 if (Instruction *I = commonPointerCastTransforms(CI))
8819 return I;
8820 } else {
8821 if (Instruction *Result = commonCastTransforms(CI))
8822 return Result;
8823 }
8824
8825
8826 // Get rid of casts from one type to the same type. These are useless and can
8827 // be replaced by the operand.
8828 if (DestTy == Src->getType())
8829 return ReplaceInstUsesWith(CI, Src);
8830
8831 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8832 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8833 const Type *DstElTy = DstPTy->getElementType();
8834 const Type *SrcElTy = SrcPTy->getElementType();
8835
Nate Begemandf5b3612008-03-31 00:22:16 +00008836 // If the address spaces don't match, don't eliminate the bitcast, which is
8837 // required for changing types.
8838 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8839 return 0;
8840
Victor Hernandez48c3c542009-09-18 22:35:49 +00008841 // If we are casting a alloca to a pointer to a type of the same
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008842 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez48c3c542009-09-18 22:35:49 +00008843 // There is no need to modify malloc calls because it is their bitcast that
8844 // needs to be cleaned up.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008845 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8846 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8847 return V;
8848
8849 // If the source and destination are pointers, and this cast is equivalent
8850 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8851 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson35b47072009-08-13 21:58:54 +00008852 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008853 unsigned NumZeros = 0;
8854 while (SrcElTy != DstElTy &&
8855 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8856 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8857 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8858 ++NumZeros;
8859 }
8860
8861 // If we found a path from the src to dest, create the getelementptr now.
8862 if (SrcElTy == DstElTy) {
8863 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008864 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8865 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008866 }
8867 }
8868
Eli Friedman1d31dee2009-07-18 23:06:53 +00008869 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8870 if (DestVTy->getNumElements() == 1) {
8871 if (!isa<VectorType>(SrcTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008872 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00008873 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattnerd6164c22009-08-30 20:01:10 +00008874 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00008875 }
8876 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8877 }
8878 }
8879
8880 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8881 if (SrcVTy->getNumElements() == 1) {
8882 if (!isa<VectorType>(DestTy)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008883 Value *Elem =
8884 Builder->CreateExtractElement(Src,
8885 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00008886 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8887 }
8888 }
8889 }
8890
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008891 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8892 if (SVI->hasOneUse()) {
8893 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8894 // a bitconvert to a vector with the same # elts.
8895 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00008896 cast<VectorType>(DestTy)->getNumElements() ==
8897 SVI->getType()->getNumElements() &&
8898 SVI->getType()->getNumElements() ==
8899 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008900 CastInst *Tmp;
8901 // If either of the operands is a cast from CI.getType(), then
8902 // evaluating the shuffle in the casted destination's type will allow
8903 // us to eliminate at least one cast.
8904 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8905 Tmp->getOperand(0)->getType() == DestTy) ||
8906 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8907 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008908 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8909 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008910 // Return a new shuffle vector. Use the same element ID's, as we
8911 // know the vector types match #elts.
8912 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8913 }
8914 }
8915 }
8916 }
8917 return 0;
8918}
8919
8920/// GetSelectFoldableOperands - We want to turn code that looks like this:
8921/// %C = or %A, %B
8922/// %D = select %cond, %C, %A
8923/// into:
8924/// %C = select %cond, %B, 0
8925/// %D = or %A, %C
8926///
8927/// Assuming that the specified instruction is an operand to the select, return
8928/// a bitmask indicating which operands of this instruction are foldable if they
8929/// equal the other incoming value of the select.
8930///
8931static unsigned GetSelectFoldableOperands(Instruction *I) {
8932 switch (I->getOpcode()) {
8933 case Instruction::Add:
8934 case Instruction::Mul:
8935 case Instruction::And:
8936 case Instruction::Or:
8937 case Instruction::Xor:
8938 return 3; // Can fold through either operand.
8939 case Instruction::Sub: // Can only fold on the amount subtracted.
8940 case Instruction::Shl: // Can only fold on the shift amount.
8941 case Instruction::LShr:
8942 case Instruction::AShr:
8943 return 1;
8944 default:
8945 return 0; // Cannot fold
8946 }
8947}
8948
8949/// GetSelectFoldableConstant - For the same transformation as the previous
8950/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00008951static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00008952 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008953 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008954 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008955 case Instruction::Add:
8956 case Instruction::Sub:
8957 case Instruction::Or:
8958 case Instruction::Xor:
8959 case Instruction::Shl:
8960 case Instruction::LShr:
8961 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00008962 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008963 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00008964 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008965 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00008966 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008967 }
8968}
8969
8970/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8971/// have the same opcode and only one use each. Try to simplify this.
8972Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8973 Instruction *FI) {
8974 if (TI->getNumOperands() == 1) {
8975 // If this is a non-volatile load or a cast from the same type,
8976 // merge.
8977 if (TI->isCast()) {
8978 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8979 return 0;
8980 } else {
8981 return 0; // unknown unary op.
8982 }
8983
8984 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008985 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00008986 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008987 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008988 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008989 TI->getType());
8990 }
8991
8992 // Only handle binary operators here.
8993 if (!isa<BinaryOperator>(TI))
8994 return 0;
8995
8996 // Figure out if the operations have any operands in common.
8997 Value *MatchOp, *OtherOpT, *OtherOpF;
8998 bool MatchIsOpZero;
8999 if (TI->getOperand(0) == FI->getOperand(0)) {
9000 MatchOp = TI->getOperand(0);
9001 OtherOpT = TI->getOperand(1);
9002 OtherOpF = FI->getOperand(1);
9003 MatchIsOpZero = true;
9004 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9005 MatchOp = TI->getOperand(1);
9006 OtherOpT = TI->getOperand(0);
9007 OtherOpF = FI->getOperand(0);
9008 MatchIsOpZero = false;
9009 } else if (!TI->isCommutative()) {
9010 return 0;
9011 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9012 MatchOp = TI->getOperand(0);
9013 OtherOpT = TI->getOperand(1);
9014 OtherOpF = FI->getOperand(0);
9015 MatchIsOpZero = true;
9016 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9017 MatchOp = TI->getOperand(1);
9018 OtherOpT = TI->getOperand(0);
9019 OtherOpF = FI->getOperand(1);
9020 MatchIsOpZero = true;
9021 } else {
9022 return 0;
9023 }
9024
9025 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009026 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9027 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009028 InsertNewInstBefore(NewSI, SI);
9029
9030 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9031 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009032 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009033 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009034 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009035 }
Edwin Törökbd448e32009-07-14 16:55:14 +00009036 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009037 return 0;
9038}
9039
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009040static bool isSelect01(Constant *C1, Constant *C2) {
9041 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9042 if (!C1I)
9043 return false;
9044 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9045 if (!C2I)
9046 return false;
9047 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9048}
9049
9050/// FoldSelectIntoOp - Try fold the select into one of the operands to
9051/// facilitate further optimization.
9052Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9053 Value *FalseVal) {
9054 // See the comment above GetSelectFoldableOperands for a description of the
9055 // transformation we are doing here.
9056 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9057 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9058 !isa<Constant>(FalseVal)) {
9059 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9060 unsigned OpToFold = 0;
9061 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9062 OpToFold = 1;
9063 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9064 OpToFold = 2;
9065 }
9066
9067 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009068 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009069 Value *OOp = TVI->getOperand(2-OpToFold);
9070 // Avoid creating select between 2 constants unless it's selecting
9071 // between 0 and 1.
9072 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9073 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9074 InsertNewInstBefore(NewSel, SI);
9075 NewSel->takeName(TVI);
9076 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9077 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009078 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009079 }
9080 }
9081 }
9082 }
9083 }
9084
9085 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9086 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9087 !isa<Constant>(TrueVal)) {
9088 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9089 unsigned OpToFold = 0;
9090 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9091 OpToFold = 1;
9092 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9093 OpToFold = 2;
9094 }
9095
9096 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009097 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009098 Value *OOp = FVI->getOperand(2-OpToFold);
9099 // Avoid creating select between 2 constants unless it's selecting
9100 // between 0 and 1.
9101 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9102 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9103 InsertNewInstBefore(NewSel, SI);
9104 NewSel->takeName(FVI);
9105 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9106 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009107 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009108 }
9109 }
9110 }
9111 }
9112 }
9113
9114 return 0;
9115}
9116
Dan Gohman58c09632008-09-16 18:46:06 +00009117/// visitSelectInstWithICmp - Visit a SelectInst that has an
9118/// ICmpInst as its first operand.
9119///
9120Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9121 ICmpInst *ICI) {
9122 bool Changed = false;
9123 ICmpInst::Predicate Pred = ICI->getPredicate();
9124 Value *CmpLHS = ICI->getOperand(0);
9125 Value *CmpRHS = ICI->getOperand(1);
9126 Value *TrueVal = SI.getTrueValue();
9127 Value *FalseVal = SI.getFalseValue();
9128
9129 // Check cases where the comparison is with a constant that
9130 // can be adjusted to fit the min/max idiom. We may edit ICI in
9131 // place here, so make sure the select is the only user.
9132 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009133 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009134 switch (Pred) {
9135 default: break;
9136 case ICmpInst::ICMP_ULT:
9137 case ICmpInst::ICMP_SLT: {
9138 // X < MIN ? T : F --> F
9139 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9140 return ReplaceInstUsesWith(SI, FalseVal);
9141 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009142 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009143 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9144 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9145 Pred = ICmpInst::getSwappedPredicate(Pred);
9146 CmpRHS = AdjustedRHS;
9147 std::swap(FalseVal, TrueVal);
9148 ICI->setPredicate(Pred);
9149 ICI->setOperand(1, CmpRHS);
9150 SI.setOperand(1, TrueVal);
9151 SI.setOperand(2, FalseVal);
9152 Changed = true;
9153 }
9154 break;
9155 }
9156 case ICmpInst::ICMP_UGT:
9157 case ICmpInst::ICMP_SGT: {
9158 // X > MAX ? T : F --> F
9159 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9160 return ReplaceInstUsesWith(SI, FalseVal);
9161 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009162 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009163 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9164 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9165 Pred = ICmpInst::getSwappedPredicate(Pred);
9166 CmpRHS = AdjustedRHS;
9167 std::swap(FalseVal, TrueVal);
9168 ICI->setPredicate(Pred);
9169 ICI->setOperand(1, CmpRHS);
9170 SI.setOperand(1, TrueVal);
9171 SI.setOperand(2, FalseVal);
9172 Changed = true;
9173 }
9174 break;
9175 }
9176 }
9177
Dan Gohman35b76162008-10-30 20:40:10 +00009178 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9179 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009180 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohmancdff2122009-08-12 16:23:25 +00009181 if (match(TrueVal, m_ConstantInt<-1>()) &&
9182 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009183 Pred = ICI->getPredicate();
Dan Gohmancdff2122009-08-12 16:23:25 +00009184 else if (match(TrueVal, m_ConstantInt<0>()) &&
9185 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009186 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9187
Dan Gohman35b76162008-10-30 20:40:10 +00009188 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9189 // If we are just checking for a icmp eq of a single bit and zext'ing it
9190 // to an integer, then shift the bit to the appropriate place and then
9191 // cast to integer to avoid the comparison.
9192 const APInt &Op1CV = CI->getValue();
9193
9194 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9195 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9196 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009197 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009198 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00009199 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009200 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009201 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00009202 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00009203 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009204 if (In->getType() != SI.getType())
9205 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009206 true/*SExt*/, "tmp", ICI);
9207
9208 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohmancdff2122009-08-12 16:23:25 +00009209 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman35b76162008-10-30 20:40:10 +00009210 In->getName()+".not"), *ICI);
9211
9212 return ReplaceInstUsesWith(SI, In);
9213 }
9214 }
9215 }
9216
Dan Gohman58c09632008-09-16 18:46:06 +00009217 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9218 // Transform (X == Y) ? X : Y -> Y
9219 if (Pred == ICmpInst::ICMP_EQ)
9220 return ReplaceInstUsesWith(SI, FalseVal);
9221 // Transform (X != Y) ? X : Y -> X
9222 if (Pred == ICmpInst::ICMP_NE)
9223 return ReplaceInstUsesWith(SI, TrueVal);
9224 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9225
9226 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9227 // Transform (X == Y) ? Y : X -> X
9228 if (Pred == ICmpInst::ICMP_EQ)
9229 return ReplaceInstUsesWith(SI, FalseVal);
9230 // Transform (X != Y) ? Y : X -> Y
9231 if (Pred == ICmpInst::ICMP_NE)
9232 return ReplaceInstUsesWith(SI, TrueVal);
9233 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9234 }
9235
9236 /// NOTE: if we wanted to, this is where to detect integer ABS
9237
9238 return Changed ? &SI : 0;
9239}
9240
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009241/// isDefinedInBB - Return true if the value is an instruction defined in the
9242/// specified basicblock.
9243static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9244 const Instruction *I = dyn_cast<Instruction>(V);
9245 return I != 0 && I->getParent() == BB;
9246}
9247
9248
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009249Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9250 Value *CondVal = SI.getCondition();
9251 Value *TrueVal = SI.getTrueValue();
9252 Value *FalseVal = SI.getFalseValue();
9253
9254 // select true, X, Y -> X
9255 // select false, X, Y -> Y
9256 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9257 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9258
9259 // select C, X, X -> X
9260 if (TrueVal == FalseVal)
9261 return ReplaceInstUsesWith(SI, TrueVal);
9262
9263 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9264 return ReplaceInstUsesWith(SI, FalseVal);
9265 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9266 return ReplaceInstUsesWith(SI, TrueVal);
9267 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9268 if (isa<Constant>(TrueVal))
9269 return ReplaceInstUsesWith(SI, TrueVal);
9270 else
9271 return ReplaceInstUsesWith(SI, FalseVal);
9272 }
9273
Owen Anderson35b47072009-08-13 21:58:54 +00009274 if (SI.getType() == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009275 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9276 if (C->getZExtValue()) {
9277 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009278 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009279 } else {
9280 // Change: A = select B, false, C --> A = and !B, C
9281 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009282 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009283 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009284 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009285 }
9286 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9287 if (C->getZExtValue() == false) {
9288 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009289 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009290 } else {
9291 // Change: A = select B, C, true --> A = or !B, C
9292 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009293 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009294 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009295 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009296 }
9297 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009298
9299 // select a, b, a -> a&b
9300 // select a, a, b -> a|b
9301 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009302 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009303 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009304 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009305 }
9306
9307 // Selecting between two integer constants?
9308 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9309 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9310 // select C, 1, 0 -> zext C to int
9311 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009312 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009313 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9314 // select C, 0, 1 -> zext !C to int
9315 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009316 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009317 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009318 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009319 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009320
9321 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009322 // If one of the constants is zero (we know they can't both be) and we
9323 // have an icmp instruction with zero, and we have an 'and' with the
9324 // non-constant value, eliminate this whole mess. This corresponds to
9325 // cases like this: ((X & 27) ? 27 : 0)
9326 if (TrueValC->isZero() || FalseValC->isZero())
9327 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9328 cast<Constant>(IC->getOperand(1))->isNullValue())
9329 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9330 if (ICA->getOpcode() == Instruction::And &&
9331 isa<ConstantInt>(ICA->getOperand(1)) &&
9332 (ICA->getOperand(1) == TrueValC ||
9333 ICA->getOperand(1) == FalseValC) &&
9334 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9335 // Okay, now we know that everything is set up, we just don't
9336 // know whether we have a icmp_ne or icmp_eq and whether the
9337 // true or false val is the zero.
9338 bool ShouldNotVal = !TrueValC->isZero();
9339 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9340 Value *V = ICA;
9341 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009342 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009343 Instruction::Xor, V, ICA->getOperand(1)), SI);
9344 return ReplaceInstUsesWith(SI, V);
9345 }
9346 }
9347 }
9348
9349 // See if we are selecting two values based on a comparison of the two values.
9350 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9351 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9352 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009353 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9354 // This is not safe in general for floating point:
9355 // consider X== -0, Y== +0.
9356 // It becomes safe if either operand is a nonzero constant.
9357 ConstantFP *CFPt, *CFPf;
9358 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9359 !CFPt->getValueAPF().isZero()) ||
9360 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9361 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009362 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009363 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009364 // Transform (X != Y) ? X : Y -> X
9365 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9366 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009367 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009368
9369 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9370 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009371 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9372 // This is not safe in general for floating point:
9373 // consider X== -0, Y== +0.
9374 // It becomes safe if either operand is a nonzero constant.
9375 ConstantFP *CFPt, *CFPf;
9376 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9377 !CFPt->getValueAPF().isZero()) ||
9378 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9379 !CFPf->getValueAPF().isZero()))
9380 return ReplaceInstUsesWith(SI, FalseVal);
9381 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009382 // Transform (X != Y) ? Y : X -> Y
9383 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9384 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009385 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009386 }
Dan Gohman58c09632008-09-16 18:46:06 +00009387 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009388 }
9389
9390 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009391 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9392 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9393 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009394
9395 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9396 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9397 if (TI->hasOneUse() && FI->hasOneUse()) {
9398 Instruction *AddOp = 0, *SubOp = 0;
9399
9400 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9401 if (TI->getOpcode() == FI->getOpcode())
9402 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9403 return IV;
9404
9405 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9406 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009407 if ((TI->getOpcode() == Instruction::Sub &&
9408 FI->getOpcode() == Instruction::Add) ||
9409 (TI->getOpcode() == Instruction::FSub &&
9410 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009411 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009412 } else if ((FI->getOpcode() == Instruction::Sub &&
9413 TI->getOpcode() == Instruction::Add) ||
9414 (FI->getOpcode() == Instruction::FSub &&
9415 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009416 AddOp = TI; SubOp = FI;
9417 }
9418
9419 if (AddOp) {
9420 Value *OtherAddOp = 0;
9421 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9422 OtherAddOp = AddOp->getOperand(1);
9423 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9424 OtherAddOp = AddOp->getOperand(0);
9425 }
9426
9427 if (OtherAddOp) {
9428 // So at this point we know we have (Y -> OtherAddOp):
9429 // select C, (add X, Y), (sub X, Z)
9430 Value *NegVal; // Compute -Z
9431 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00009432 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009433 } else {
9434 NegVal = InsertNewInstBefore(
Dan Gohmancdff2122009-08-12 16:23:25 +00009435 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00009436 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009437 }
9438
9439 Value *NewTrueOp = OtherAddOp;
9440 Value *NewFalseOp = NegVal;
9441 if (AddOp != TI)
9442 std::swap(NewTrueOp, NewFalseOp);
9443 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009444 SelectInst::Create(CondVal, NewTrueOp,
9445 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009446
9447 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009448 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009449 }
9450 }
9451 }
9452
9453 // See if we can fold the select into one of our operands.
9454 if (SI.getType()->isInteger()) {
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009455 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9456 if (FoldI)
9457 return FoldI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009458 }
9459
Chris Lattnerf7843b72009-09-27 19:57:57 +00009460 // See if we can fold the select into a phi node. The true/false values have
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009461 // to be live in the predecessor blocks. If they are instructions in SI's
9462 // block, we can't map to the predecessor.
Chris Lattnerf7843b72009-09-27 19:57:57 +00009463 if (isa<PHINode>(SI.getCondition()) &&
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009464 (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9465 isa<PHINode>(SI.getTrueValue())) &&
9466 (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9467 isa<PHINode>(SI.getFalseValue())))
Chris Lattnerf7843b72009-09-27 19:57:57 +00009468 if (Instruction *NV = FoldOpIntoPhi(SI))
9469 return NV;
9470
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009471 if (BinaryOperator::isNot(CondVal)) {
9472 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9473 SI.setOperand(1, FalseVal);
9474 SI.setOperand(2, TrueVal);
9475 return &SI;
9476 }
9477
9478 return 0;
9479}
9480
Dan Gohman2d648bb2008-04-10 18:43:06 +00009481/// EnforceKnownAlignment - If the specified pointer points to an object that
9482/// we control, modify the object's alignment to PrefAlign. This isn't
9483/// often possible though. If alignment is important, a more reliable approach
9484/// is to simply align all global variables and allocation instructions to
9485/// their preferred alignment from the beginning.
9486///
9487static unsigned EnforceKnownAlignment(Value *V,
9488 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009489
Dan Gohman2d648bb2008-04-10 18:43:06 +00009490 User *U = dyn_cast<User>(V);
9491 if (!U) return Align;
9492
Dan Gohman9545fb02009-07-17 20:47:02 +00009493 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009494 default: break;
9495 case Instruction::BitCast:
9496 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9497 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009498 // If all indexes are zero, it is just the alignment of the base pointer.
9499 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009500 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009501 if (!isa<Constant>(*i) ||
9502 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009503 AllZeroOperands = false;
9504 break;
9505 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009506
9507 if (AllZeroOperands) {
9508 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009509 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009510 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009511 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009512 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009513 }
9514
9515 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9516 // If there is a large requested alignment and we can, bump up the alignment
9517 // of the global.
9518 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009519 if (GV->getAlignment() >= PrefAlign)
9520 Align = GV->getAlignment();
9521 else {
9522 GV->setAlignment(PrefAlign);
9523 Align = PrefAlign;
9524 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009525 }
Chris Lattnere8ad9ae2009-09-27 21:42:46 +00009526 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9527 // If there is a requested alignment and if this is an alloca, round up.
9528 if (AI->getAlignment() >= PrefAlign)
9529 Align = AI->getAlignment();
9530 else {
9531 AI->setAlignment(PrefAlign);
9532 Align = PrefAlign;
Dan Gohman2d648bb2008-04-10 18:43:06 +00009533 }
9534 }
9535
9536 return Align;
9537}
9538
9539/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9540/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9541/// and it is more than the alignment of the ultimate object, see if we can
9542/// increase the alignment of the ultimate object, making this check succeed.
9543unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9544 unsigned PrefAlign) {
9545 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9546 sizeof(PrefAlign) * CHAR_BIT;
9547 APInt Mask = APInt::getAllOnesValue(BitWidth);
9548 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9549 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9550 unsigned TrailZ = KnownZero.countTrailingOnes();
9551 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9552
9553 if (PrefAlign > Align)
9554 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9555
9556 // We don't need to make any adjustment.
9557 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009558}
9559
Chris Lattner00ae5132008-01-13 23:50:23 +00009560Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009561 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009562 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009563 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009564 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009565
9566 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009567 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009568 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00009569 return MI;
9570 }
9571
9572 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9573 // load/store.
9574 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9575 if (MemOpLength == 0) return 0;
9576
Chris Lattnerc669fb62008-01-14 00:28:35 +00009577 // Source and destination pointer types are always "i8*" for intrinsic. See
9578 // if the size is something we can handle with a single primitive load/store.
9579 // A single load+store correctly handles overlapping memory in the memmove
9580 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009581 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009582 if (Size == 0) return MI; // Delete this mem transfer.
9583
9584 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009585 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009586
Chris Lattnerc669fb62008-01-14 00:28:35 +00009587 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00009588 Type *NewPtrTy =
Owen Anderson35b47072009-08-13 21:58:54 +00009589 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009590
9591 // Memcpy forces the use of i8* for the source and destination. That means
9592 // that if you're using memcpy to move one double around, you'll get a cast
9593 // from double* to i8*. We'd much rather use a double load+store rather than
9594 // an i64 load+store, here because this improves the odds that the source or
9595 // dest address will be promotable. See if we can find a better type than the
9596 // integer datatype.
9597 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9598 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00009599 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009600 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9601 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009602 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009603 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9604 if (STy->getNumElements() == 1)
9605 SrcETy = STy->getElementType(0);
9606 else
9607 break;
9608 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9609 if (ATy->getNumElements() == 1)
9610 SrcETy = ATy->getElementType();
9611 else
9612 break;
9613 } else
9614 break;
9615 }
9616
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009617 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009618 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009619 }
9620 }
9621
9622
Chris Lattner00ae5132008-01-13 23:50:23 +00009623 // If the memcpy/memmove provides better alignment info than we can
9624 // infer, use it.
9625 SrcAlign = std::max(SrcAlign, CopyAlign);
9626 DstAlign = std::max(DstAlign, CopyAlign);
9627
Chris Lattner78628292009-08-30 19:47:22 +00009628 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9629 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009630 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9631 InsertNewInstBefore(L, *MI);
9632 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9633
9634 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009635 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009636 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009637}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009638
Chris Lattner5af8a912008-04-30 06:39:11 +00009639Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9640 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009641 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009642 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009643 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +00009644 return MI;
9645 }
9646
9647 // Extract the length and alignment and fill if they are constant.
9648 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9649 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson35b47072009-08-13 21:58:54 +00009650 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner5af8a912008-04-30 06:39:11 +00009651 return 0;
9652 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009653 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009654
9655 // If the length is zero, this is a no-op
9656 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9657
9658 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9659 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson35b47072009-08-13 21:58:54 +00009660 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00009661
9662 Value *Dest = MI->getDest();
Chris Lattner78628292009-08-30 19:47:22 +00009663 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner5af8a912008-04-30 06:39:11 +00009664
9665 // Alignment 0 is identity for alignment 1 for memset, but not store.
9666 if (Alignment == 0) Alignment = 1;
9667
9668 // Extract the fill value and store.
9669 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +00009670 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +00009671 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009672
9673 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009674 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00009675 return MI;
9676 }
9677
9678 return 0;
9679}
9680
9681
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009682/// visitCallInst - CallInst simplification. This mostly only handles folding
9683/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9684/// the heavy lifting.
9685///
9686Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraa295aa2009-05-13 17:39:14 +00009687 // If the caller function is nounwind, mark the call as nounwind, even if the
9688 // callee isn't.
9689 if (CI.getParent()->getParent()->doesNotThrow() &&
9690 !CI.doesNotThrow()) {
9691 CI.setDoesNotThrow();
9692 return &CI;
9693 }
9694
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009695 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9696 if (!II) return visitCallSite(&CI);
9697
9698 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9699 // visitCallSite.
9700 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9701 bool Changed = false;
9702
9703 // memmove/cpy/set of zero bytes is a noop.
9704 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9705 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9706
9707 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9708 if (CI->getZExtValue() == 1) {
9709 // Replace the instruction with just byte operations. We would
9710 // transform other cases to loads/stores, but we don't know if
9711 // alignment is sufficient.
9712 }
9713 }
9714
9715 // If we have a memmove and the source operation is a constant global,
9716 // then the source and dest pointers can't alias, so we can change this
9717 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009718 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009719 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9720 if (GVSrc->isConstant()) {
9721 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009722 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9723 const Type *Tys[1];
9724 Tys[0] = CI.getOperand(3)->getType();
9725 CI.setOperand(0,
9726 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009727 Changed = true;
9728 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009729
9730 // memmove(x,x,size) -> noop.
9731 if (MMI->getSource() == MMI->getDest())
9732 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009733 }
9734
9735 // If we can determine a pointer alignment that is bigger than currently
9736 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009737 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009738 if (Instruction *I = SimplifyMemTransfer(MI))
9739 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009740 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9741 if (Instruction *I = SimplifyMemSet(MSI))
9742 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009743 }
9744
9745 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009746 }
9747
9748 switch (II->getIntrinsicID()) {
9749 default: break;
9750 case Intrinsic::bswap:
9751 // bswap(bswap(x)) -> x
9752 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9753 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9754 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9755 break;
9756 case Intrinsic::ppc_altivec_lvx:
9757 case Intrinsic::ppc_altivec_lvxl:
9758 case Intrinsic::x86_sse_loadu_ps:
9759 case Intrinsic::x86_sse2_loadu_pd:
9760 case Intrinsic::x86_sse2_loadu_dq:
9761 // Turn PPC lvx -> load if the pointer is known aligned.
9762 // Turn X86 loadups -> load if the pointer is known aligned.
9763 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner78628292009-08-30 19:47:22 +00009764 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9765 PointerType::getUnqual(II->getType()));
Chris Lattner989ba312008-06-18 04:33:20 +00009766 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009767 }
Chris Lattner989ba312008-06-18 04:33:20 +00009768 break;
9769 case Intrinsic::ppc_altivec_stvx:
9770 case Intrinsic::ppc_altivec_stvxl:
9771 // Turn stvx -> store if the pointer is known aligned.
9772 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9773 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009774 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00009775 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00009776 return new StoreInst(II->getOperand(1), Ptr);
9777 }
9778 break;
9779 case Intrinsic::x86_sse_storeu_ps:
9780 case Intrinsic::x86_sse2_storeu_pd:
9781 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009782 // Turn X86 storeu -> store if the pointer is known aligned.
9783 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9784 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009785 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00009786 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00009787 return new StoreInst(II->getOperand(2), Ptr);
9788 }
9789 break;
9790
9791 case Intrinsic::x86_sse_cvttss2si: {
9792 // These intrinsics only demands the 0th element of its input vector. If
9793 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00009794 unsigned VWidth =
9795 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9796 APInt DemandedElts(VWidth, 1);
9797 APInt UndefElts(VWidth, 0);
9798 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00009799 UndefElts)) {
9800 II->setOperand(1, V);
9801 return II;
9802 }
9803 break;
9804 }
9805
9806 case Intrinsic::ppc_altivec_vperm:
9807 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9808 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9809 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009810
Chris Lattner989ba312008-06-18 04:33:20 +00009811 // Check that all of the elements are integer constants or undefs.
9812 bool AllEltsOk = true;
9813 for (unsigned i = 0; i != 16; ++i) {
9814 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9815 !isa<UndefValue>(Mask->getOperand(i))) {
9816 AllEltsOk = false;
9817 break;
9818 }
9819 }
9820
9821 if (AllEltsOk) {
9822 // Cast the input vectors to byte vectors.
Chris Lattner78628292009-08-30 19:47:22 +00009823 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9824 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00009825 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009826
Chris Lattner989ba312008-06-18 04:33:20 +00009827 // Only extract each element once.
9828 Value *ExtractedElts[32];
9829 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9830
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009831 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00009832 if (isa<UndefValue>(Mask->getOperand(i)))
9833 continue;
9834 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9835 Idx &= 31; // Match the hardware behavior.
9836
9837 if (ExtractedElts[Idx] == 0) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009838 ExtractedElts[Idx] =
9839 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9840 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9841 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009842 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009843
Chris Lattner989ba312008-06-18 04:33:20 +00009844 // Insert this value into the result vector.
Chris Lattnerad7516a2009-08-30 18:50:58 +00009845 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9846 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9847 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009848 }
Chris Lattner989ba312008-06-18 04:33:20 +00009849 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009850 }
Chris Lattner989ba312008-06-18 04:33:20 +00009851 }
9852 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009853
Chris Lattner989ba312008-06-18 04:33:20 +00009854 case Intrinsic::stackrestore: {
9855 // If the save is right next to the restore, remove the restore. This can
9856 // happen when variable allocas are DCE'd.
9857 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9858 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9859 BasicBlock::iterator BI = SS;
9860 if (&*++BI == II)
9861 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009862 }
Chris Lattner989ba312008-06-18 04:33:20 +00009863 }
9864
9865 // Scan down this block to see if there is another stack restore in the
9866 // same block without an intervening call/alloca.
9867 BasicBlock::iterator BI = II;
9868 TerminatorInst *TI = II->getParent()->getTerminator();
9869 bool CannotRemove = false;
9870 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez48c3c542009-09-18 22:35:49 +00009871 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner989ba312008-06-18 04:33:20 +00009872 CannotRemove = true;
9873 break;
9874 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00009875 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9876 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9877 // If there is a stackrestore below this one, remove this one.
9878 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9879 return EraseInstFromFunction(CI);
9880 // Otherwise, ignore the intrinsic.
9881 } else {
9882 // If we found a non-intrinsic call, we can't remove the stack
9883 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00009884 CannotRemove = true;
9885 break;
9886 }
Chris Lattner989ba312008-06-18 04:33:20 +00009887 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009888 }
Chris Lattner989ba312008-06-18 04:33:20 +00009889
9890 // If the stack restore is in a return/unwind block and if there are no
9891 // allocas or calls between the restore and the return, nuke the restore.
9892 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9893 return EraseInstFromFunction(CI);
9894 break;
9895 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009896 }
9897
9898 return visitCallSite(II);
9899}
9900
9901// InvokeInst simplification
9902//
9903Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9904 return visitCallSite(&II);
9905}
9906
Dale Johannesen96021832008-04-25 21:16:07 +00009907/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9908/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00009909static bool isSafeToEliminateVarargsCast(const CallSite CS,
9910 const CastInst * const CI,
9911 const TargetData * const TD,
9912 const int ix) {
9913 if (!CI->isLosslessCast())
9914 return false;
9915
9916 // The size of ByVal arguments is derived from the type, so we
9917 // can't change to a type with a different size. If the size were
9918 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +00009919 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +00009920 return true;
9921
9922 const Type* SrcTy =
9923 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9924 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9925 if (!SrcTy->isSized() || !DstTy->isSized())
9926 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +00009927 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +00009928 return false;
9929 return true;
9930}
9931
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009932// visitCallSite - Improvements for call and invoke instructions.
9933//
9934Instruction *InstCombiner::visitCallSite(CallSite CS) {
9935 bool Changed = false;
9936
9937 // If the callee is a constexpr cast of a function, attempt to move the cast
9938 // to the arguments of the call/invoke.
9939 if (transformConstExprCastCall(CS)) return 0;
9940
9941 Value *Callee = CS.getCalledValue();
9942
9943 if (Function *CalleeF = dyn_cast<Function>(Callee))
9944 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9945 Instruction *OldCall = CS.getInstruction();
9946 // If the call and callee calling conventions don't match, this call must
9947 // be unreachable, as the call is undefined.
Owen Anderson4f720fa2009-07-31 17:39:07 +00009948 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson35b47072009-08-13 21:58:54 +00009949 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Anderson24be4c12009-07-03 00:17:18 +00009950 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009951 if (!OldCall->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00009952 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009953 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9954 return EraseInstFromFunction(*OldCall);
9955 return 0;
9956 }
9957
9958 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9959 // This instruction is not reachable, just remove it. We insert a store to
9960 // undef so that we know that this code is not reachable, despite the fact
9961 // that we can't modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +00009962 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson35b47072009-08-13 21:58:54 +00009963 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009964 CS.getInstruction());
9965
9966 if (!CS.getInstruction()->use_empty())
9967 CS.getInstruction()->
Owen Andersonb99ecca2009-07-30 23:03:37 +00009968 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009969
9970 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9971 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009972 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson4f720fa2009-07-31 17:39:07 +00009973 ConstantInt::getTrue(*Context), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009974 }
9975 return EraseInstFromFunction(*CS.getInstruction());
9976 }
9977
Duncan Sands74833f22007-09-17 10:26:40 +00009978 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9979 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9980 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9981 return transformCallThroughTrampoline(CS);
9982
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009983 const PointerType *PTy = cast<PointerType>(Callee->getType());
9984 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9985 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00009986 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009987 // See if we can optimize any arguments passed through the varargs area of
9988 // the call.
9989 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00009990 E = CS.arg_end(); I != E; ++I, ++ix) {
9991 CastInst *CI = dyn_cast<CastInst>(*I);
9992 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9993 *I = CI->getOperand(0);
9994 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009995 }
Dale Johannesen35615462008-04-23 18:34:37 +00009996 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009997 }
9998
Duncan Sands2937e352007-12-19 21:13:37 +00009999 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010000 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010001 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010002 Changed = true;
10003 }
10004
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010005 return Changed ? CS.getInstruction() : 0;
10006}
10007
10008// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10009// attempt to move the cast to the arguments of the call/invoke.
10010//
10011bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10012 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10013 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10014 if (CE->getOpcode() != Instruction::BitCast ||
10015 !isa<Function>(CE->getOperand(0)))
10016 return false;
10017 Function *Callee = cast<Function>(CE->getOperand(0));
10018 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010019 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010020
10021 // Okay, this is a cast from a function to a different type. Unless doing so
10022 // would cause a type conversion of one of our arguments, change this call to
10023 // be a direct call with arguments casted to the appropriate types.
10024 //
10025 const FunctionType *FT = Callee->getFunctionType();
10026 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010027 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010028
Duncan Sands7901ce12008-06-01 07:38:42 +000010029 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010030 return false; // TODO: Handle multiple return values.
10031
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010032 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010033 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010034 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010035 // Conversion is ok if changing from one pointer type to another or from
10036 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +000010037 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010038 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000010039 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010040 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010041 return false; // Cannot transform this return value.
10042
Duncan Sands5c489582008-01-06 10:12:28 +000010043 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010044 // void -> non-void is handled specially
Owen Anderson35b47072009-08-13 21:58:54 +000010045 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010046 return false; // Cannot transform this return value.
10047
Chris Lattner1c8733e2008-03-12 17:45:29 +000010048 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010049 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010050 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010051 return false; // Attribute not compatible with transformed value.
10052 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010053
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010054 // If the callsite is an invoke instruction, and the return value is used by
10055 // a PHI node in a successor, we cannot change the return type of the call
10056 // because there is no place to put the cast instruction (without breaking
10057 // the critical edge). Bail out in this case.
10058 if (!Caller->use_empty())
10059 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10060 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10061 UI != E; ++UI)
10062 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10063 if (PN->getParent() == II->getNormalDest() ||
10064 PN->getParent() == II->getUnwindDest())
10065 return false;
10066 }
10067
10068 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10069 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10070
10071 CallSite::arg_iterator AI = CS.arg_begin();
10072 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10073 const Type *ParamTy = FT->getParamType(i);
10074 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010075
10076 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010077 return false; // Cannot transform this parameter value.
10078
Devang Patelf2a4a922008-09-26 22:53:05 +000010079 if (CallerPAL.getParamAttributes(i + 1)
10080 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010081 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010082
Duncan Sands7901ce12008-06-01 07:38:42 +000010083 // Converting from one pointer type to another or between a pointer and an
10084 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010085 bool isConvertible = ActTy == ParamTy ||
Owen Anderson35b47072009-08-13 21:58:54 +000010086 (TD && ((isa<PointerType>(ParamTy) ||
10087 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10088 (isa<PointerType>(ActTy) ||
10089 ActTy == TD->getIntPtrType(Caller->getContext()))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010090 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010091 }
10092
10093 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10094 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010095 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010096
Chris Lattner1c8733e2008-03-12 17:45:29 +000010097 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10098 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010099 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010100 // won't be dropping them. Check that these extra arguments have attributes
10101 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010102 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10103 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010104 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010105 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010106 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010107 return false;
10108 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010109
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010110 // Okay, we decided that this is a safe thing to do: go ahead and start
10111 // inserting cast instructions as necessary...
10112 std::vector<Value*> Args;
10113 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010114 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010115 attrVec.reserve(NumCommonArgs);
10116
10117 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010118 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010119
10120 // If the return value is not being used, the type may not be compatible
10121 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010122 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010123
10124 // Add the new return attributes.
10125 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010126 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010127
10128 AI = CS.arg_begin();
10129 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10130 const Type *ParamTy = FT->getParamType(i);
10131 if ((*AI)->getType() == ParamTy) {
10132 Args.push_back(*AI);
10133 } else {
10134 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10135 false, ParamTy, false);
Chris Lattnerad7516a2009-08-30 18:50:58 +000010136 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010137 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010138
10139 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010140 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010141 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010142 }
10143
10144 // If the function takes more arguments than the call was taking, add them
Chris Lattnerad7516a2009-08-30 18:50:58 +000010145 // now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010146 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +000010147 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010148
Chris Lattnerad7516a2009-08-30 18:50:58 +000010149 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010150 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010151 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +000010152 errs() << "WARNING: While resolving call to function '"
10153 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010154 } else {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010155 // Add all of the arguments in their promoted form to the arg list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010156 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10157 const Type *PTy = getPromotedType((*AI)->getType());
10158 if (PTy != (*AI)->getType()) {
10159 // Must promote to pass through va_arg area!
Chris Lattnerad7516a2009-08-30 18:50:58 +000010160 Instruction::CastOps opcode =
10161 CastInst::getCastOpcode(*AI, false, PTy, false);
10162 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010163 } else {
10164 Args.push_back(*AI);
10165 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010166
Duncan Sands4ced1f82008-01-13 08:02:44 +000010167 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010168 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010169 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010170 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010171 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010172 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010173
Devang Patelf2a4a922008-09-26 22:53:05 +000010174 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10175 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10176
Owen Anderson35b47072009-08-13 21:58:54 +000010177 if (NewRetTy == Type::getVoidTy(*Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010178 Caller->setName(""); // Void type should not have a name.
10179
Eric Christopher3e7381f2009-07-25 02:45:27 +000010180 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10181 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010182
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010183 Instruction *NC;
10184 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010185 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010186 Args.begin(), Args.end(),
10187 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010188 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010189 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010190 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010191 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10192 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010193 CallInst *CI = cast<CallInst>(Caller);
10194 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010195 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010196 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010197 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010198 }
10199
10200 // Insert a cast of the return type as necessary.
10201 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010202 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson35b47072009-08-13 21:58:54 +000010203 if (NV->getType() != Type::getVoidTy(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010204 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010205 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010206 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010207
10208 // If this is an invoke instruction, we should insert it after the first
10209 // non-phi, instruction in the normal successor block.
10210 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010211 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010212 InsertNewInstBefore(NC, *I);
10213 } else {
10214 // Otherwise, it's a call, just insert cast right after the call instr
10215 InsertNewInstBefore(NC, *Caller);
10216 }
Chris Lattner4796b622009-08-30 06:22:51 +000010217 Worklist.AddUsersToWorkList(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010218 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010219 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010220 }
10221 }
10222
Chris Lattner26b7f942009-08-31 05:17:58 +000010223
10224 if (!Caller->use_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010225 Caller->replaceAllUsesWith(NV);
Chris Lattner26b7f942009-08-31 05:17:58 +000010226
10227 EraseInstFromFunction(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010228 return true;
10229}
10230
Duncan Sands74833f22007-09-17 10:26:40 +000010231// transformCallThroughTrampoline - Turn a call to a function created by the
10232// init_trampoline intrinsic into a direct call to the underlying function.
10233//
10234Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10235 Value *Callee = CS.getCalledValue();
10236 const PointerType *PTy = cast<PointerType>(Callee->getType());
10237 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010238 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010239
10240 // If the call already has the 'nest' attribute somewhere then give up -
10241 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010242 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010243 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010244
10245 IntrinsicInst *Tramp =
10246 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10247
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010248 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010249 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10250 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10251
Devang Pateld222f862008-09-25 21:00:45 +000010252 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010253 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010254 unsigned NestIdx = 1;
10255 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010256 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010257
10258 // Look for a parameter marked with the 'nest' attribute.
10259 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10260 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010261 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010262 // Record the parameter type and any other attributes.
10263 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010264 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010265 break;
10266 }
10267
10268 if (NestTy) {
10269 Instruction *Caller = CS.getInstruction();
10270 std::vector<Value*> NewArgs;
10271 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10272
Devang Pateld222f862008-09-25 21:00:45 +000010273 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010274 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010275
Duncan Sands74833f22007-09-17 10:26:40 +000010276 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010277 // mean appending it. Likewise for attributes.
10278
Devang Patelf2a4a922008-09-26 22:53:05 +000010279 // Add any result attributes.
10280 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010281 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010282
Duncan Sands74833f22007-09-17 10:26:40 +000010283 {
10284 unsigned Idx = 1;
10285 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10286 do {
10287 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010288 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010289 Value *NestVal = Tramp->getOperand(3);
10290 if (NestVal->getType() != NestTy)
10291 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10292 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010293 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010294 }
10295
10296 if (I == E)
10297 break;
10298
Duncan Sands48b81112008-01-14 19:52:09 +000010299 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010300 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010301 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010302 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010303 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010304
10305 ++Idx, ++I;
10306 } while (1);
10307 }
10308
Devang Patelf2a4a922008-09-26 22:53:05 +000010309 // Add any function attributes.
10310 if (Attributes Attr = Attrs.getFnAttributes())
10311 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10312
Duncan Sands74833f22007-09-17 10:26:40 +000010313 // The trampoline may have been bitcast to a bogus type (FTy).
10314 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010315 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010316
Duncan Sands74833f22007-09-17 10:26:40 +000010317 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010318 NewTypes.reserve(FTy->getNumParams()+1);
10319
Duncan Sands74833f22007-09-17 10:26:40 +000010320 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010321 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010322 {
10323 unsigned Idx = 1;
10324 FunctionType::param_iterator I = FTy->param_begin(),
10325 E = FTy->param_end();
10326
10327 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010328 if (Idx == NestIdx)
10329 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010330 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010331
10332 if (I == E)
10333 break;
10334
Duncan Sands48b81112008-01-14 19:52:09 +000010335 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010336 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010337
10338 ++Idx, ++I;
10339 } while (1);
10340 }
10341
10342 // Replace the trampoline call with a direct call. Let the generic
10343 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010344 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +000010345 FTy->isVarArg());
10346 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010347 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +000010348 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010349 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +000010350 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10351 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010352
10353 Instruction *NewCaller;
10354 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010355 NewCaller = InvokeInst::Create(NewCallee,
10356 II->getNormalDest(), II->getUnwindDest(),
10357 NewArgs.begin(), NewArgs.end(),
10358 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010359 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010360 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010361 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010362 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10363 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010364 if (cast<CallInst>(Caller)->isTailCall())
10365 cast<CallInst>(NewCaller)->setTailCall();
10366 cast<CallInst>(NewCaller)->
10367 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010368 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010369 }
Owen Anderson35b47072009-08-13 21:58:54 +000010370 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sands74833f22007-09-17 10:26:40 +000010371 Caller->replaceAllUsesWith(NewCaller);
10372 Caller->eraseFromParent();
Chris Lattner3183fb62009-08-30 06:13:40 +000010373 Worklist.Remove(Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010374 return 0;
10375 }
10376 }
10377
10378 // Replace the trampoline call with a direct call. Since there is no 'nest'
10379 // parameter, there is no need to adjust the argument list. Let the generic
10380 // code sort out any function type mismatches.
10381 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010382 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +000010383 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010384 CS.setCalledFunction(NewCallee);
10385 return CS.getInstruction();
10386}
10387
Dan Gohman09cf2b62009-09-16 16:50:24 +000010388/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10389/// 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 +000010390/// and a single binop.
10391Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10392 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010393 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010394 unsigned Opc = FirstInst->getOpcode();
10395 Value *LHSVal = FirstInst->getOperand(0);
10396 Value *RHSVal = FirstInst->getOperand(1);
10397
10398 const Type *LHSType = LHSVal->getType();
10399 const Type *RHSType = RHSVal->getType();
10400
Dan Gohman09cf2b62009-09-16 16:50:24 +000010401 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010402 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010403 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10404 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10405 // Verify type of the LHS matches so we don't fold cmp's of different
10406 // types or GEP's with different index types.
10407 I->getOperand(0)->getType() != LHSType ||
10408 I->getOperand(1)->getType() != RHSType)
10409 return 0;
10410
10411 // If they are CmpInst instructions, check their predicates
10412 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10413 if (cast<CmpInst>(I)->getPredicate() !=
10414 cast<CmpInst>(FirstInst)->getPredicate())
10415 return 0;
10416
10417 // Keep track of which operand needs a phi node.
10418 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10419 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10420 }
Dan Gohman09cf2b62009-09-16 16:50:24 +000010421
10422 // If both LHS and RHS would need a PHI, don't do this transformation,
10423 // because it would increase the number of PHIs entering the block,
10424 // which leads to higher register pressure. This is especially
10425 // bad when the PHIs are in the header of a loop.
10426 if (!LHSVal && !RHSVal)
10427 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010428
Chris Lattner30078012008-12-01 03:42:51 +000010429 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010430
10431 Value *InLHS = FirstInst->getOperand(0);
10432 Value *InRHS = FirstInst->getOperand(1);
10433 PHINode *NewLHS = 0, *NewRHS = 0;
10434 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010435 NewLHS = PHINode::Create(LHSType,
10436 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010437 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10438 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10439 InsertNewInstBefore(NewLHS, PN);
10440 LHSVal = NewLHS;
10441 }
10442
10443 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010444 NewRHS = PHINode::Create(RHSType,
10445 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010446 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10447 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10448 InsertNewInstBefore(NewRHS, PN);
10449 RHSVal = NewRHS;
10450 }
10451
10452 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010453 if (NewLHS || NewRHS) {
10454 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10455 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10456 if (NewLHS) {
10457 Value *NewInLHS = InInst->getOperand(0);
10458 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10459 }
10460 if (NewRHS) {
10461 Value *NewInRHS = InInst->getOperand(1);
10462 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10463 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010464 }
10465 }
10466
10467 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010468 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010469 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohmane6803b82009-08-25 23:17:54 +000010470 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson6601fcd2009-07-09 23:48:35 +000010471 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010472}
10473
Chris Lattner9e1916e2008-12-01 02:34:36 +000010474Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10475 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10476
10477 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10478 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010479 // This is true if all GEP bases are allocas and if all indices into them are
10480 // constants.
10481 bool AllBasePointersAreAllocas = true;
Dan Gohman37a534b2009-09-16 02:01:52 +000010482
10483 // We don't want to replace this phi if the replacement would require
Dan Gohman09cf2b62009-09-16 16:50:24 +000010484 // more than one phi, which leads to higher register pressure. This is
10485 // especially bad when the PHIs are in the header of a loop.
Dan Gohman37a534b2009-09-16 02:01:52 +000010486 bool NeededPhi = false;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010487
Dan Gohman09cf2b62009-09-16 16:50:24 +000010488 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010489 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10490 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10491 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10492 GEP->getNumOperands() != FirstInst->getNumOperands())
10493 return 0;
10494
Chris Lattneradf354b2009-02-21 00:46:50 +000010495 // Keep track of whether or not all GEPs are of alloca pointers.
10496 if (AllBasePointersAreAllocas &&
10497 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10498 !GEP->hasAllConstantIndices()))
10499 AllBasePointersAreAllocas = false;
10500
Chris Lattner9e1916e2008-12-01 02:34:36 +000010501 // Compare the operand lists.
10502 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10503 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10504 continue;
10505
10506 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10507 // if one of the PHIs has a constant for the index. The index may be
10508 // substantially cheaper to compute for the constants, so making it a
10509 // variable index could pessimize the path. This also handles the case
10510 // for struct indices, which must always be constant.
10511 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10512 isa<ConstantInt>(GEP->getOperand(op)))
10513 return 0;
10514
10515 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10516 return 0;
Dan Gohman37a534b2009-09-16 02:01:52 +000010517
10518 // If we already needed a PHI for an earlier operand, and another operand
10519 // also requires a PHI, we'd be introducing more PHIs than we're
10520 // eliminating, which increases register pressure on entry to the PHI's
10521 // block.
10522 if (NeededPhi)
10523 return 0;
10524
Chris Lattner9e1916e2008-12-01 02:34:36 +000010525 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohman37a534b2009-09-16 02:01:52 +000010526 NeededPhi = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010527 }
10528 }
10529
Chris Lattneradf354b2009-02-21 00:46:50 +000010530 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010531 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010532 // offset calculation, but all the predecessors will have to materialize the
10533 // stack address into a register anyway. We'd actually rather *clone* the
10534 // load up into the predecessors so that we have a load of a gep of an alloca,
10535 // which can usually all be folded into the load.
10536 if (AllBasePointersAreAllocas)
10537 return 0;
10538
Chris Lattner9e1916e2008-12-01 02:34:36 +000010539 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10540 // that is variable.
10541 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10542
10543 bool HasAnyPHIs = false;
10544 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10545 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10546 Value *FirstOp = FirstInst->getOperand(i);
10547 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10548 FirstOp->getName()+".pn");
10549 InsertNewInstBefore(NewPN, PN);
10550
10551 NewPN->reserveOperandSpace(e);
10552 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10553 OperandPhis[i] = NewPN;
10554 FixedOperands[i] = NewPN;
10555 HasAnyPHIs = true;
10556 }
10557
10558
10559 // Add all operands to the new PHIs.
10560 if (HasAnyPHIs) {
10561 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10562 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10563 BasicBlock *InBB = PN.getIncomingBlock(i);
10564
10565 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10566 if (PHINode *OpPhi = OperandPhis[op])
10567 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10568 }
10569 }
10570
10571 Value *Base = FixedOperands[0];
Dan Gohmanf3a08b82009-09-07 23:54:19 +000010572 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10573 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10574 FixedOperands.end()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000010575 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10576 FixedOperands.end());
Chris Lattner9e1916e2008-12-01 02:34:36 +000010577}
10578
10579
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010580/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10581/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010582/// obvious the value of the load is not changed from the point of the load to
10583/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010584///
10585/// Finally, it is safe, but not profitable, to sink a load targetting a
10586/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10587/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010588static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010589 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10590
10591 for (++BBI; BBI != E; ++BBI)
10592 if (BBI->mayWriteToMemory())
10593 return false;
10594
10595 // Check for non-address taken alloca. If not address-taken already, it isn't
10596 // profitable to do this xform.
10597 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10598 bool isAddressTaken = false;
10599 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10600 UI != E; ++UI) {
10601 if (isa<LoadInst>(UI)) continue;
10602 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10603 // If storing TO the alloca, then the address isn't taken.
10604 if (SI->getOperand(1) == AI) continue;
10605 }
10606 isAddressTaken = true;
10607 break;
10608 }
10609
Chris Lattneradf354b2009-02-21 00:46:50 +000010610 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010611 return false;
10612 }
10613
Chris Lattneradf354b2009-02-21 00:46:50 +000010614 // If this load is a load from a GEP with a constant offset from an alloca,
10615 // then we don't want to sink it. In its present form, it will be
10616 // load [constant stack offset]. Sinking it will cause us to have to
10617 // materialize the stack addresses in each predecessor in a register only to
10618 // do a shared load from register in the successor.
10619 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10620 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10621 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10622 return false;
10623
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010624 return true;
10625}
10626
10627
10628// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10629// operator and they all are only used by the PHI, PHI together their
10630// inputs, and do the operation once, to the result of the PHI.
10631Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10632 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10633
10634 // Scan the instruction, looking for input operations that can be folded away.
10635 // If all input operands to the phi are the same instruction (e.g. a cast from
10636 // the same type or "+42") we can pull the operation through the PHI, reducing
10637 // code size and simplifying code.
10638 Constant *ConstantOp = 0;
10639 const Type *CastSrcTy = 0;
10640 bool isVolatile = false;
10641 if (isa<CastInst>(FirstInst)) {
10642 CastSrcTy = FirstInst->getOperand(0)->getType();
10643 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10644 // Can fold binop, compare or shift here if the RHS is a constant,
10645 // otherwise call FoldPHIArgBinOpIntoPHI.
10646 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10647 if (ConstantOp == 0)
10648 return FoldPHIArgBinOpIntoPHI(PN);
10649 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10650 isVolatile = LI->isVolatile();
10651 // We can't sink the load if the loaded value could be modified between the
10652 // load and the PHI.
10653 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010654 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010655 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010656
10657 // If the PHI is of volatile loads and the load block has multiple
10658 // successors, sinking it would remove a load of the volatile value from
10659 // the path through the other successor.
10660 if (isVolatile &&
10661 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10662 return 0;
10663
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010664 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010665 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010666 } else {
10667 return 0; // Cannot fold this operation.
10668 }
10669
10670 // Check to see if all arguments are the same operation.
10671 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10672 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10673 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10674 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10675 return 0;
10676 if (CastSrcTy) {
10677 if (I->getOperand(0)->getType() != CastSrcTy)
10678 return 0; // Cast operation must match.
10679 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10680 // We can't sink the load if the loaded value could be modified between
10681 // the load and the PHI.
10682 if (LI->isVolatile() != isVolatile ||
10683 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010684 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010685 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010686
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010687 // If the PHI is of volatile loads and the load block has multiple
10688 // successors, sinking it would remove a load of the volatile value from
10689 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010690 if (isVolatile &&
10691 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10692 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010693
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010694 } else if (I->getOperand(1) != ConstantOp) {
10695 return 0;
10696 }
10697 }
10698
10699 // Okay, they are all the same operation. Create a new PHI node of the
10700 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010701 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10702 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010703 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10704
10705 Value *InVal = FirstInst->getOperand(0);
10706 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10707
10708 // Add all operands to the new PHI.
10709 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10710 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10711 if (NewInVal != InVal)
10712 InVal = 0;
10713 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10714 }
10715
10716 Value *PhiVal;
10717 if (InVal) {
10718 // The new PHI unions all of the same values together. This is really
10719 // common, so we handle it intelligently here for compile-time speed.
10720 PhiVal = InVal;
10721 delete NewPN;
10722 } else {
10723 InsertNewInstBefore(NewPN, PN);
10724 PhiVal = NewPN;
10725 }
10726
10727 // Insert and return the new operation.
10728 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010729 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010730 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010731 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010732 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohmane6803b82009-08-25 23:17:54 +000010733 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010734 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010735 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10736
10737 // If this was a volatile load that we are merging, make sure to loop through
10738 // and mark all the input loads as non-volatile. If we don't do this, we will
10739 // insert a new volatile load and the old ones will not be deletable.
10740 if (isVolatile)
10741 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10742 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10743
10744 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010745}
10746
10747/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10748/// that is dead.
10749static bool DeadPHICycle(PHINode *PN,
10750 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10751 if (PN->use_empty()) return true;
10752 if (!PN->hasOneUse()) return false;
10753
10754 // Remember this node, and if we find the cycle, return.
10755 if (!PotentiallyDeadPHIs.insert(PN))
10756 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010757
10758 // Don't scan crazily complex things.
10759 if (PotentiallyDeadPHIs.size() == 16)
10760 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010761
10762 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10763 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10764
10765 return false;
10766}
10767
Chris Lattner27b695d2007-11-06 21:52:06 +000010768/// PHIsEqualValue - Return true if this phi node is always equal to
10769/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10770/// z = some value; x = phi (y, z); y = phi (x, z)
10771static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10772 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10773 // See if we already saw this PHI node.
10774 if (!ValueEqualPHIs.insert(PN))
10775 return true;
10776
10777 // Don't scan crazily complex things.
10778 if (ValueEqualPHIs.size() == 16)
10779 return false;
10780
10781 // Scan the operands to see if they are either phi nodes or are equal to
10782 // the value.
10783 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10784 Value *Op = PN->getIncomingValue(i);
10785 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10786 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10787 return false;
10788 } else if (Op != NonPhiInVal)
10789 return false;
10790 }
10791
10792 return true;
10793}
10794
10795
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010796// PHINode simplification
10797//
10798Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10799 // If LCSSA is around, don't mess with Phi nodes
10800 if (MustPreserveLCSSA) return 0;
10801
10802 if (Value *V = PN.hasConstantValue())
10803 return ReplaceInstUsesWith(PN, V);
10804
10805 // If all PHI operands are the same operation, pull them through the PHI,
10806 // reducing code size.
10807 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010808 isa<Instruction>(PN.getIncomingValue(1)) &&
10809 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10810 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10811 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10812 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010813 PN.getIncomingValue(0)->hasOneUse())
10814 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10815 return Result;
10816
10817 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10818 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10819 // PHI)... break the cycle.
10820 if (PN.hasOneUse()) {
10821 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10822 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10823 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10824 PotentiallyDeadPHIs.insert(&PN);
10825 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010826 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010827 }
10828
10829 // If this phi has a single use, and if that use just computes a value for
10830 // the next iteration of a loop, delete the phi. This occurs with unused
10831 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10832 // common case here is good because the only other things that catch this
10833 // are induction variable analysis (sometimes) and ADCE, which is only run
10834 // late.
10835 if (PHIUser->hasOneUse() &&
10836 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10837 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010838 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010839 }
10840 }
10841
Chris Lattner27b695d2007-11-06 21:52:06 +000010842 // We sometimes end up with phi cycles that non-obviously end up being the
10843 // same value, for example:
10844 // z = some value; x = phi (y, z); y = phi (x, z)
10845 // where the phi nodes don't necessarily need to be in the same block. Do a
10846 // quick check to see if the PHI node only contains a single non-phi value, if
10847 // so, scan to see if the phi cycle is actually equal to that value.
10848 {
10849 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10850 // Scan for the first non-phi operand.
10851 while (InValNo != NumOperandVals &&
10852 isa<PHINode>(PN.getIncomingValue(InValNo)))
10853 ++InValNo;
10854
10855 if (InValNo != NumOperandVals) {
10856 Value *NonPhiInVal = PN.getOperand(InValNo);
10857
10858 // Scan the rest of the operands to see if there are any conflicts, if so
10859 // there is no need to recursively scan other phis.
10860 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10861 Value *OpVal = PN.getIncomingValue(InValNo);
10862 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10863 break;
10864 }
10865
10866 // If we scanned over all operands, then we have one unique value plus
10867 // phi values. Scan PHI nodes to see if they all merge in each other or
10868 // the value.
10869 if (InValNo == NumOperandVals) {
10870 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10871 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10872 return ReplaceInstUsesWith(PN, NonPhiInVal);
10873 }
10874 }
10875 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010876 return 0;
10877}
10878
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010879Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10880 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerf3a23592009-08-30 20:36:46 +000010881 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010882 if (GEP.getNumOperands() == 1)
10883 return ReplaceInstUsesWith(GEP, PtrOp);
10884
10885 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010886 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010887
10888 bool HasZeroPointerIndex = false;
10889 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10890 HasZeroPointerIndex = C->isNullValue();
10891
10892 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10893 return ReplaceInstUsesWith(GEP, PtrOp);
10894
10895 // Eliminate unneeded casts for indices.
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010896 if (TD) {
10897 bool MadeChange = false;
10898 unsigned PtrSize = TD->getPointerSizeInBits();
10899
10900 gep_type_iterator GTI = gep_type_begin(GEP);
10901 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10902 I != E; ++I, ++GTI) {
10903 if (!isa<SequentialType>(*GTI)) continue;
10904
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010905 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010906 // to what we need. If narrower, sign-extend it to what we need. This
10907 // explicit cast can make subsequent optimizations more obvious.
10908 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010909 if (OpBits == PtrSize)
10910 continue;
10911
Chris Lattnerd6164c22009-08-30 20:01:10 +000010912 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010913 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010914 }
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010915 if (MadeChange) return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010916 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010917
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010918 // Combine Indices - If the source pointer to this getelementptr instruction
10919 // is a getelementptr instruction, combine the indices of the two
10920 // getelementptr instructions into a single instruction.
10921 //
Dan Gohman17f46f72009-07-28 01:40:03 +000010922 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010923 // Note that if our source is a gep chain itself that we wait for that
10924 // chain to be resolved before we perform this transformation. This
10925 // avoids us creating a TON of code in some cases.
10926 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010927 if (GetElementPtrInst *SrcGEP =
10928 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10929 if (SrcGEP->getNumOperands() == 2)
10930 return 0; // Wait until our source is folded to completion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010931
10932 SmallVector<Value*, 8> Indices;
10933
10934 // Find out whether the last index in the source GEP is a sequential idx.
10935 bool EndsWithSequential = false;
Chris Lattner1c641fc2009-08-30 05:30:55 +000010936 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10937 I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010938 EndsWithSequential = !isa<StructType>(*I);
10939
10940 // Can we combine the two pointer arithmetics offsets?
10941 if (EndsWithSequential) {
10942 // Replace: gep (gep %P, long B), long A, ...
10943 // With: T = long A+B; gep %P, T, ...
10944 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010945 Value *Sum;
10946 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10947 Value *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +000010948 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010949 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +000010950 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010951 Sum = SO1;
10952 } else {
Chris Lattner1c641fc2009-08-30 05:30:55 +000010953 // If they aren't the same type, then the input hasn't been processed
10954 // by the loop above yet (which canonicalizes sequential index types to
10955 // intptr_t). Just avoid transforming this until the input has been
10956 // normalized.
10957 if (SO1->getType() != GO1->getType())
10958 return 0;
Chris Lattnerad7516a2009-08-30 18:50:58 +000010959 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010960 }
10961
Chris Lattner1c641fc2009-08-30 05:30:55 +000010962 // Update the GEP in place if possible.
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010963 if (Src->getNumOperands() == 2) {
10964 GEP.setOperand(0, Src->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010965 GEP.setOperand(1, Sum);
10966 return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010967 }
Chris Lattner1c641fc2009-08-30 05:30:55 +000010968 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010969 Indices.push_back(Sum);
Chris Lattner1c641fc2009-08-30 05:30:55 +000010970 Indices.append(GEP.op_begin()+2, GEP.op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010971 } else if (isa<Constant>(*GEP.idx_begin()) &&
10972 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010973 Src->getNumOperands() != 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010974 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner1c641fc2009-08-30 05:30:55 +000010975 Indices.append(Src->op_begin()+1, Src->op_end());
10976 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010977 }
10978
Dan Gohmanf3a08b82009-09-07 23:54:19 +000010979 if (!Indices.empty())
10980 return (cast<GEPOperator>(&GEP)->isInBounds() &&
10981 Src->isInBounds()) ?
10982 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
10983 Indices.end(), GEP.getName()) :
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010984 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerc0f553e2009-08-30 04:49:01 +000010985 Indices.end(), GEP.getName());
Chris Lattner95ba1ec2009-08-30 05:00:50 +000010986 }
10987
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000010988 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10989 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner95ba1ec2009-08-30 05:00:50 +000010990 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattnerf3a23592009-08-30 20:36:46 +000010991
Chris Lattner83288fa2009-08-30 20:38:21 +000010992 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
10993 // want to change the gep until the bitcasts are eliminated.
10994 if (getBitCastOperand(X)) {
10995 Worklist.AddValue(PtrOp);
10996 return 0;
10997 }
10998
Chris Lattnerf3a23592009-08-30 20:36:46 +000010999 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11000 // into : GEP [10 x i8]* X, i32 0, ...
11001 //
11002 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11003 // into : GEP i8* X, ...
11004 //
11005 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011006 if (HasZeroPointerIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011007 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11008 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011009 if (const ArrayType *CATy =
11010 dyn_cast<ArrayType>(CPTy->getElementType())) {
11011 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11012 if (CATy->getElementType() == XTy->getElementType()) {
11013 // -> GEP i8* X, ...
11014 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011015 return cast<GEPOperator>(&GEP)->isInBounds() ?
11016 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11017 GEP.getName()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000011018 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11019 GEP.getName());
Chris Lattnerf3a23592009-08-30 20:36:46 +000011020 }
11021
11022 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sandscf866e62009-03-02 09:18:21 +000011023 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011024 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011025 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011026 // At this point, we know that the cast source type is a pointer
11027 // to an array of the same type as the destination pointer
11028 // array. Because the array type is never stepped over (there
11029 // is a leading zero) we can fold the cast into this GEP.
11030 GEP.setOperand(0, X);
11031 return &GEP;
11032 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011033 }
11034 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011035 } else if (GEP.getNumOperands() == 2) {
11036 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011037 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11038 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011039 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11040 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000011041 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011042 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11043 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011044 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011045 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011046 Idx[1] = GEP.getOperand(1);
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011047 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11048 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerad7516a2009-08-30 18:50:58 +000011049 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011050 // V and GEP are both pointer types --> BitCast
Chris Lattnerad7516a2009-08-30 18:50:58 +000011051 return new BitCastInst(NewGEP, GEP.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011052 }
11053
11054 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011055 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011056 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011057 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011058
Owen Anderson35b47072009-08-13 21:58:54 +000011059 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011060 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011061 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011062
11063 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11064 // allow either a mul, shift, or constant here.
11065 Value *NewIdx = 0;
11066 ConstantInt *Scale = 0;
11067 if (ArrayEltSize == 1) {
11068 NewIdx = GEP.getOperand(1);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011069 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011070 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011071 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011072 Scale = CI;
11073 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11074 if (Inst->getOpcode() == Instruction::Shl &&
11075 isa<ConstantInt>(Inst->getOperand(1))) {
11076 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11077 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +000011078 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011079 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011080 NewIdx = Inst->getOperand(0);
11081 } else if (Inst->getOpcode() == Instruction::Mul &&
11082 isa<ConstantInt>(Inst->getOperand(1))) {
11083 Scale = cast<ConstantInt>(Inst->getOperand(1));
11084 NewIdx = Inst->getOperand(0);
11085 }
11086 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011087
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011088 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011089 // out, perform the transformation. Note, we don't know whether Scale is
11090 // signed or not. We'll use unsigned version of division/modulo
11091 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011092 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011093 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011094 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011095 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011096 if (Scale->getZExtValue() != 1) {
Chris Lattnerbf09d632009-08-30 05:56:44 +000011097 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11098 false /*ZExt*/);
Chris Lattnerad7516a2009-08-30 18:50:58 +000011099 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011100 }
11101
11102 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011103 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011104 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011105 Idx[1] = NewIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011106 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11107 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11108 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011109 // The NewGEP must be pointer typed, so must the old one -> BitCast
11110 return new BitCastInst(NewGEP, GEP.getType());
11111 }
11112 }
11113 }
11114 }
Chris Lattner111ea772009-01-09 04:53:57 +000011115
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011116 /// See if we can simplify:
Chris Lattner5119c702009-08-30 05:55:36 +000011117 /// X = bitcast A* to B*
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011118 /// Y = gep X, <...constant indices...>
11119 /// into a gep of the original struct. This is important for SROA and alias
11120 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011121 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011122 if (TD &&
11123 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011124 // Determine how much the GEP moves the pointer. We are guaranteed to get
11125 // a constant back from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +000011126 ConstantInt *OffsetV =
11127 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011128 int64_t Offset = OffsetV->getSExtValue();
11129
11130 // If this GEP instruction doesn't move the pointer, just replace the GEP
11131 // with a bitcast of the real input to the dest type.
11132 if (Offset == 0) {
11133 // If the bitcast is of an allocation, and the allocation will be
11134 // converted to match the type of the cast, don't touch this.
Victor Hernandez48c3c542009-09-18 22:35:49 +000011135 if (isa<AllocationInst>(BCI->getOperand(0)) ||
11136 isMalloc(BCI->getOperand(0))) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011137 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11138 if (Instruction *I = visitBitCast(*BCI)) {
11139 if (I != BCI) {
11140 I->takeName(BCI);
11141 BCI->getParent()->getInstList().insert(BCI, I);
11142 ReplaceInstUsesWith(*BCI, I);
11143 }
11144 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011145 }
Chris Lattner111ea772009-01-09 04:53:57 +000011146 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011147 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011148 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011149
11150 // Otherwise, if the offset is non-zero, we need to find out if there is a
11151 // field at Offset in 'A's type. If so, we can pull the cast through the
11152 // GEP.
11153 SmallVector<Value*, 8> NewIndices;
11154 const Type *InTy =
11155 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000011156 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011157 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11158 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11159 NewIndices.end()) :
11160 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11161 NewIndices.end());
Chris Lattnerad7516a2009-08-30 18:50:58 +000011162
11163 if (NGEP->getType() == GEP.getType())
11164 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011165 NGEP->takeName(&GEP);
11166 return new BitCastInst(NGEP, GEP.getType());
11167 }
Chris Lattner111ea772009-01-09 04:53:57 +000011168 }
11169 }
11170
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011171 return 0;
11172}
11173
11174Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11175 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011176 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011177 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11178 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011179 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011180 AllocationInst *New = 0;
11181
11182 // Create and insert the replacement instruction...
11183 if (isa<MallocInst>(AI))
Chris Lattnerad7516a2009-08-30 18:50:58 +000011184 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011185 else {
11186 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerad7516a2009-08-30 18:50:58 +000011187 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011188 }
Chris Lattnerad7516a2009-08-30 18:50:58 +000011189 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011190
11191 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011192 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011193 //
11194 BasicBlock::iterator It = New;
Dale Johannesena499d0d2009-03-11 22:19:43 +000011195 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011196
11197 // Now that I is pointing to the first non-allocation-inst in the block,
11198 // insert our getelementptr instruction...
11199 //
Owen Anderson35b47072009-08-13 21:58:54 +000011200 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011201 Value *Idx[2];
11202 Idx[0] = NullIdx;
11203 Idx[1] = NullIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011204 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11205 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011206
11207 // Now make everything use the getelementptr instead of the original
11208 // allocation.
11209 return ReplaceInstUsesWith(AI, V);
11210 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +000011211 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011212 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011213 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011214
Dan Gohmana80e2712009-07-21 23:21:54 +000011215 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000011216 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011217 // Note that we only do this for alloca's, because malloc should allocate
11218 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011219 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +000011220 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000011221
11222 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11223 if (AI.getAlignment() == 0)
11224 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11225 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011226
11227 return 0;
11228}
11229
11230Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11231 Value *Op = FI.getOperand(0);
11232
11233 // free undef -> unreachable.
11234 if (isa<UndefValue>(Op)) {
11235 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000011236 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson35b47072009-08-13 21:58:54 +000011237 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011238 return EraseInstFromFunction(FI);
11239 }
11240
11241 // If we have 'free null' delete the instruction. This can happen in stl code
11242 // when lots of inlining happens.
11243 if (isa<ConstantPointerNull>(Op))
11244 return EraseInstFromFunction(FI);
11245
11246 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11247 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11248 FI.setOperand(0, CI->getOperand(0));
11249 return &FI;
11250 }
11251
11252 // Change free (gep X, 0,0,0,0) into free(X)
11253 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11254 if (GEPI->hasAllZeroIndices()) {
Chris Lattner3183fb62009-08-30 06:13:40 +000011255 Worklist.Add(GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011256 FI.setOperand(0, GEPI->getOperand(0));
11257 return &FI;
11258 }
11259 }
11260
11261 // Change free(malloc) into nothing, if the malloc has a single use.
11262 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11263 if (MI->hasOneUse()) {
11264 EraseInstFromFunction(FI);
11265 return EraseInstFromFunction(*MI);
11266 }
Victor Hernandez48c3c542009-09-18 22:35:49 +000011267 if (isMalloc(Op)) {
11268 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11269 if (Op->hasOneUse() && CI->hasOneUse()) {
11270 EraseInstFromFunction(FI);
11271 EraseInstFromFunction(*CI);
11272 return EraseInstFromFunction(*cast<Instruction>(Op));
11273 }
11274 } else {
11275 // Op is a call to malloc
11276 if (Op->hasOneUse()) {
11277 EraseInstFromFunction(FI);
11278 return EraseInstFromFunction(*cast<Instruction>(Op));
11279 }
11280 }
11281 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011282
11283 return 0;
11284}
11285
11286
11287/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011288static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011289 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011290 User *CI = cast<User>(LI.getOperand(0));
11291 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011292 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011293
Nick Lewycky291c5942009-05-08 06:47:37 +000011294 if (TD) {
11295 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11296 // Instead of loading constant c string, use corresponding integer value
11297 // directly if string length is small enough.
11298 std::string Str;
11299 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11300 unsigned len = Str.length();
11301 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11302 unsigned numBits = Ty->getPrimitiveSizeInBits();
11303 // Replace LI with immediate integer store.
11304 if ((numBits >> 3) == len + 1) {
11305 APInt StrVal(numBits, 0);
11306 APInt SingleChar(numBits, 0);
11307 if (TD->isLittleEndian()) {
11308 for (signed i = len-1; i >= 0; i--) {
11309 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11310 StrVal = (StrVal << 8) | SingleChar;
11311 }
11312 } else {
11313 for (unsigned i = 0; i < len; i++) {
11314 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11315 StrVal = (StrVal << 8) | SingleChar;
11316 }
11317 // Append NULL at the end.
11318 SingleChar = 0;
Bill Wendling44a36ea2008-02-26 10:53:30 +000011319 StrVal = (StrVal << 8) | SingleChar;
11320 }
Owen Andersoneacb44d2009-07-24 23:12:02 +000011321 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky291c5942009-05-08 06:47:37 +000011322 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling44a36ea2008-02-26 10:53:30 +000011323 }
Devang Patela0f8ea82007-10-18 19:52:32 +000011324 }
11325 }
11326 }
11327
Mon P Wangbd05ed82009-02-07 22:19:29 +000011328 const PointerType *DestTy = cast<PointerType>(CI->getType());
11329 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011330 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011331
11332 // If the address spaces don't match, don't eliminate the cast.
11333 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11334 return 0;
11335
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011336 const Type *SrcPTy = SrcTy->getElementType();
11337
11338 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11339 isa<VectorType>(DestPTy)) {
11340 // If the source is an array, the code below will not succeed. Check to
11341 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11342 // constants.
11343 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11344 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11345 if (ASrcTy->getNumElements() != 0) {
11346 Value *Idxs[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011347 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Anderson02b48c32009-07-29 18:55:55 +000011348 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011349 SrcTy = cast<PointerType>(CastOp->getType());
11350 SrcPTy = SrcTy->getElementType();
11351 }
11352
Dan Gohmana80e2712009-07-21 23:21:54 +000011353 if (IC.getTargetData() &&
11354 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011355 isa<VectorType>(SrcPTy)) &&
11356 // Do not allow turning this into a load of an integer, which is then
11357 // casted to a pointer, this pessimizes pointer analysis a lot.
11358 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000011359 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11360 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011361
11362 // Okay, we are casting from one integer or pointer type to another of
11363 // the same size. Instead of casting the pointer before the load, cast
11364 // the result of the loaded value.
Chris Lattnerad7516a2009-08-30 18:50:58 +000011365 Value *NewLoad =
11366 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011367 // Now cast the result of the load.
11368 return new BitCastInst(NewLoad, LI.getType());
11369 }
11370 }
11371 }
11372 return 0;
11373}
11374
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011375Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11376 Value *Op = LI.getOperand(0);
11377
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011378 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011379 if (TD) {
11380 unsigned KnownAlign =
11381 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11382 if (KnownAlign >
11383 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11384 LI.getAlignment()))
11385 LI.setAlignment(KnownAlign);
11386 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011387
Chris Lattnerf3a23592009-08-30 20:36:46 +000011388 // load (cast X) --> cast (load X) iff safe.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011389 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011390 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011391 return Res;
11392
11393 // None of the following transforms are legal for volatile loads.
11394 if (LI.isVolatile()) return 0;
11395
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011396 // Do really simple store-to-load forwarding and load CSE, to catch cases
11397 // where there are several consequtive memory accesses to the same location,
11398 // separated by a few arithmetic operations.
11399 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011400 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11401 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011402
Christopher Lamb2c175392007-12-29 07:56:53 +000011403 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11404 const Value *GEPI0 = GEPI->getOperand(0);
11405 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +000011406 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011407 // Insert a new store to null instruction before the load to indicate
11408 // that this code is not reachable. We do this instead of inserting
11409 // an unreachable instruction directly because we cannot modify the
11410 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011411 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011412 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011413 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011414 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011415 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011416
11417 if (Constant *C = dyn_cast<Constant>(Op)) {
11418 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000011419 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +000011420 if (isa<UndefValue>(C) ||
11421 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011422 // Insert a new store to null instruction before the load to indicate that
11423 // this code is not reachable. We do this instead of inserting an
11424 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011425 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011426 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011427 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011428 }
11429
11430 // Instcombine load (constant global) into the value loaded.
11431 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands54e70f62009-03-21 21:27:31 +000011432 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011433 return ReplaceInstUsesWith(LI, GV->getInitializer());
11434
11435 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011436 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011437 if (CE->getOpcode() == Instruction::GetElementPtr) {
11438 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +000011439 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011440 if (Constant *V =
Owen Andersond4d90a02009-07-06 18:42:36 +000011441 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Anderson175b6542009-07-22 00:24:57 +000011442 *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011443 return ReplaceInstUsesWith(LI, V);
11444 if (CE->getOperand(0)->isNullValue()) {
11445 // Insert a new store to null instruction before the load to indicate
11446 // that this code is not reachable. We do this instead of inserting
11447 // an unreachable instruction directly because we cannot modify the
11448 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011449 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011450 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011451 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011452 }
11453
11454 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000011455 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011456 return Res;
11457 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011458 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011459 }
Chris Lattner0270a112007-08-11 18:48:48 +000011460
11461 // If this load comes from anywhere in a constant global, and if the global
11462 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000011463 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands54e70f62009-03-21 21:27:31 +000011464 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner0270a112007-08-11 18:48:48 +000011465 if (GV->getInitializer()->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +000011466 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011467 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011468 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011469 }
11470 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011471
11472 if (Op->hasOneUse()) {
11473 // Change select and PHI nodes to select values instead of addresses: this
11474 // helps alias analysis out a lot, allows many others simplifications, and
11475 // exposes redundancy in the code.
11476 //
11477 // Note that we cannot do the transformation unless we know that the
11478 // introduced loads cannot trap! Something like this is valid as long as
11479 // the condition is always false: load (select bool %C, int* null, int* %G),
11480 // but it would not be valid if we transformed it to load from null
11481 // unconditionally.
11482 //
11483 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11484 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11485 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11486 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000011487 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11488 SI->getOperand(1)->getName()+".val");
11489 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11490 SI->getOperand(2)->getName()+".val");
Gabor Greifd6da1d02008-04-06 20:25:17 +000011491 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011492 }
11493
11494 // load (select (cond, null, P)) -> load P
11495 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11496 if (C->isNullValue()) {
11497 LI.setOperand(0, SI->getOperand(2));
11498 return &LI;
11499 }
11500
11501 // load (select (cond, P, null)) -> load P
11502 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11503 if (C->isNullValue()) {
11504 LI.setOperand(0, SI->getOperand(1));
11505 return &LI;
11506 }
11507 }
11508 }
11509 return 0;
11510}
11511
11512/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011513/// when possible. This makes it generally easy to do alias analysis and/or
11514/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011515static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11516 User *CI = cast<User>(SI.getOperand(1));
11517 Value *CastOp = CI->getOperand(0);
11518
11519 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011520 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11521 if (SrcTy == 0) return 0;
11522
11523 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011524
Chris Lattnera032c0e2009-01-16 20:08:59 +000011525 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11526 return 0;
11527
Chris Lattner54dddc72009-01-24 01:00:13 +000011528 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11529 /// to its first element. This allows us to handle things like:
11530 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11531 /// on 32-bit hosts.
11532 SmallVector<Value*, 4> NewGEPIndices;
11533
Chris Lattnera032c0e2009-01-16 20:08:59 +000011534 // If the source is an array, the code below will not succeed. Check to
11535 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11536 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011537 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11538 // Index through pointer.
Owen Anderson35b47072009-08-13 21:58:54 +000011539 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner54dddc72009-01-24 01:00:13 +000011540 NewGEPIndices.push_back(Zero);
11541
11542 while (1) {
11543 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011544 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011545 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011546 NewGEPIndices.push_back(Zero);
11547 SrcPTy = STy->getElementType(0);
11548 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11549 NewGEPIndices.push_back(Zero);
11550 SrcPTy = ATy->getElementType();
11551 } else {
11552 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011553 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011554 }
11555
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011556 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000011557 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011558
11559 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11560 return 0;
11561
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011562 // If the pointers point into different address spaces or if they point to
11563 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000011564 if (!IC.getTargetData() ||
11565 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011566 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000011567 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11568 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000011569 return 0;
11570
11571 // Okay, we are casting from one integer or pointer type to another of
11572 // the same size. Instead of casting the pointer before
11573 // the store, cast the value to be stored.
11574 Value *NewCast;
11575 Value *SIOp0 = SI.getOperand(0);
11576 Instruction::CastOps opcode = Instruction::BitCast;
11577 const Type* CastSrcTy = SIOp0->getType();
11578 const Type* CastDstTy = SrcPTy;
11579 if (isa<PointerType>(CastDstTy)) {
11580 if (CastSrcTy->isInteger())
11581 opcode = Instruction::IntToPtr;
11582 } else if (isa<IntegerType>(CastDstTy)) {
11583 if (isa<PointerType>(SIOp0->getType()))
11584 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011585 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011586
11587 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11588 // emit a GEP to index into its first field.
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011589 if (!NewGEPIndices.empty())
11590 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11591 NewGEPIndices.end());
Chris Lattner54dddc72009-01-24 01:00:13 +000011592
Chris Lattnerad7516a2009-08-30 18:50:58 +000011593 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11594 SIOp0->getName()+".c");
Chris Lattnera032c0e2009-01-16 20:08:59 +000011595 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011596}
11597
Chris Lattner6fd8c802008-11-27 08:56:30 +000011598/// equivalentAddressValues - Test if A and B will obviously have the same
11599/// value. This includes recognizing that %t0 and %t1 will have the same
11600/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000011601/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011602/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000011603/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011604/// %t2 = load i32* %t1
11605///
11606static bool equivalentAddressValues(Value *A, Value *B) {
11607 // Test if the values are trivially equivalent.
11608 if (A == B) return true;
11609
11610 // Test if the values come form identical arithmetic instructions.
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000011611 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11612 // its only used to compare two uses within the same basic block, which
11613 // means that they'll always either have the same value or one of them
11614 // will have an undefined value.
Chris Lattner6fd8c802008-11-27 08:56:30 +000011615 if (isa<BinaryOperator>(A) ||
11616 isa<CastInst>(A) ||
11617 isa<PHINode>(A) ||
11618 isa<GetElementPtrInst>(A))
11619 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000011620 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner6fd8c802008-11-27 08:56:30 +000011621 return true;
11622
11623 // Otherwise they may not be equivalent.
11624 return false;
11625}
11626
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011627// If this instruction has two uses, one of which is a llvm.dbg.declare,
11628// return the llvm.dbg.declare.
11629DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11630 if (!V->hasNUses(2))
11631 return 0;
11632 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11633 UI != E; ++UI) {
11634 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11635 return DI;
11636 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11637 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11638 return DI;
11639 }
11640 }
11641 return 0;
11642}
11643
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011644Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11645 Value *Val = SI.getOperand(0);
11646 Value *Ptr = SI.getOperand(1);
11647
11648 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11649 EraseInstFromFunction(SI);
11650 ++NumCombined;
11651 return 0;
11652 }
11653
11654 // If the RHS is an alloca with a single use, zapify the store, making the
11655 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011656 // If the RHS is an alloca with a two uses, the other one being a
11657 // llvm.dbg.declare, zapify the store and the declare, making the
11658 // alloca dead. We must do this to prevent declare's from affecting
11659 // codegen.
11660 if (!SI.isVolatile()) {
11661 if (Ptr->hasOneUse()) {
11662 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011663 EraseInstFromFunction(SI);
11664 ++NumCombined;
11665 return 0;
11666 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011667 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11668 if (isa<AllocaInst>(GEP->getOperand(0))) {
11669 if (GEP->getOperand(0)->hasOneUse()) {
11670 EraseInstFromFunction(SI);
11671 ++NumCombined;
11672 return 0;
11673 }
11674 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11675 EraseInstFromFunction(*DI);
11676 EraseInstFromFunction(SI);
11677 ++NumCombined;
11678 return 0;
11679 }
11680 }
11681 }
11682 }
11683 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11684 EraseInstFromFunction(*DI);
11685 EraseInstFromFunction(SI);
11686 ++NumCombined;
11687 return 0;
11688 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011689 }
11690
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011691 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011692 if (TD) {
11693 unsigned KnownAlign =
11694 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11695 if (KnownAlign >
11696 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11697 SI.getAlignment()))
11698 SI.setAlignment(KnownAlign);
11699 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011700
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011701 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011702 // stores to the same location, separated by a few arithmetic operations. This
11703 // situation often occurs with bitfield accesses.
11704 BasicBlock::iterator BBI = &SI;
11705 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11706 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000011707 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000011708 // Don't count debug info directives, lest they affect codegen,
11709 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11710 // It is necessary for correctness to skip those that feed into a
11711 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000011712 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000011713 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011714 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011715 continue;
11716 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011717
11718 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11719 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011720 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11721 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011722 ++NumDeadStore;
11723 ++BBI;
11724 EraseInstFromFunction(*PrevSI);
11725 continue;
11726 }
11727 break;
11728 }
11729
11730 // If this is a load, we have to stop. However, if the loaded value is from
11731 // the pointer we're loading and is producing the pointer we're storing,
11732 // then *this* store is dead (X = load P; store X -> P).
11733 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011734 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11735 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011736 EraseInstFromFunction(SI);
11737 ++NumCombined;
11738 return 0;
11739 }
11740 // Otherwise, this is a load from some other location. Stores before it
11741 // may not be dead.
11742 break;
11743 }
11744
11745 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011746 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011747 break;
11748 }
11749
11750
11751 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11752
11753 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner6807a242009-08-30 20:06:40 +000011754 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011755 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000011756 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011757 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner3183fb62009-08-30 06:13:40 +000011758 Worklist.Add(U); // Dropped a use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011759 ++NumCombined;
11760 }
11761 return 0; // Do not modify these!
11762 }
11763
11764 // store undef, Ptr -> noop
11765 if (isa<UndefValue>(Val)) {
11766 EraseInstFromFunction(SI);
11767 ++NumCombined;
11768 return 0;
11769 }
11770
11771 // If the pointer destination is a cast, see if we can fold the cast into the
11772 // source instead.
11773 if (isa<CastInst>(Ptr))
11774 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11775 return Res;
11776 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11777 if (CE->isCast())
11778 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11779 return Res;
11780
11781
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011782 // If this store is the last instruction in the basic block (possibly
11783 // excepting debug info instructions and the pointer bitcasts that feed
11784 // into them), and if the block ends with an unconditional branch, try
11785 // to move it to the successor block.
11786 BBI = &SI;
11787 do {
11788 ++BBI;
11789 } while (isa<DbgInfoIntrinsic>(BBI) ||
11790 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011791 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11792 if (BI->isUnconditional())
11793 if (SimplifyStoreAtEndOfBlock(SI))
11794 return 0; // xform done!
11795
11796 return 0;
11797}
11798
11799/// SimplifyStoreAtEndOfBlock - Turn things like:
11800/// if () { *P = v1; } else { *P = v2 }
11801/// into a phi node with a store in the successor.
11802///
11803/// Simplify things like:
11804/// *P = v1; if () { *P = v2; }
11805/// into a phi node with a store in the successor.
11806///
11807bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11808 BasicBlock *StoreBB = SI.getParent();
11809
11810 // Check to see if the successor block has exactly two incoming edges. If
11811 // so, see if the other predecessor contains a store to the same location.
11812 // if so, insert a PHI node (if needed) and move the stores down.
11813 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11814
11815 // Determine whether Dest has exactly two predecessors and, if so, compute
11816 // the other predecessor.
11817 pred_iterator PI = pred_begin(DestBB);
11818 BasicBlock *OtherBB = 0;
11819 if (*PI != StoreBB)
11820 OtherBB = *PI;
11821 ++PI;
11822 if (PI == pred_end(DestBB))
11823 return false;
11824
11825 if (*PI != StoreBB) {
11826 if (OtherBB)
11827 return false;
11828 OtherBB = *PI;
11829 }
11830 if (++PI != pred_end(DestBB))
11831 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000011832
11833 // Bail out if all the relevant blocks aren't distinct (this can happen,
11834 // for example, if SI is in an infinite loop)
11835 if (StoreBB == DestBB || OtherBB == DestBB)
11836 return false;
11837
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011838 // Verify that the other block ends in a branch and is not otherwise empty.
11839 BasicBlock::iterator BBI = OtherBB->getTerminator();
11840 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11841 if (!OtherBr || BBI == OtherBB->begin())
11842 return false;
11843
11844 // If the other block ends in an unconditional branch, check for the 'if then
11845 // else' case. there is an instruction before the branch.
11846 StoreInst *OtherStore = 0;
11847 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011848 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011849 // Skip over debugging info.
11850 while (isa<DbgInfoIntrinsic>(BBI) ||
11851 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11852 if (BBI==OtherBB->begin())
11853 return false;
11854 --BBI;
11855 }
11856 // If this isn't a store, or isn't a store to the same location, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011857 OtherStore = dyn_cast<StoreInst>(BBI);
11858 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11859 return false;
11860 } else {
11861 // Otherwise, the other block ended with a conditional branch. If one of the
11862 // destinations is StoreBB, then we have the if/then case.
11863 if (OtherBr->getSuccessor(0) != StoreBB &&
11864 OtherBr->getSuccessor(1) != StoreBB)
11865 return false;
11866
11867 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11868 // if/then triangle. See if there is a store to the same ptr as SI that
11869 // lives in OtherBB.
11870 for (;; --BBI) {
11871 // Check to see if we find the matching store.
11872 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11873 if (OtherStore->getOperand(1) != SI.getOperand(1))
11874 return false;
11875 break;
11876 }
Eli Friedman3a311d52008-06-13 22:02:12 +000011877 // If we find something that may be using or overwriting the stored
11878 // value, or if we run out of instructions, we can't do the xform.
11879 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011880 BBI == OtherBB->begin())
11881 return false;
11882 }
11883
11884 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000011885 // make sure nothing reads or overwrites the stored value in
11886 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011887 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11888 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000011889 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011890 return false;
11891 }
11892 }
11893
11894 // Insert a PHI node now if we need it.
11895 Value *MergedVal = OtherStore->getOperand(0);
11896 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000011897 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011898 PN->reserveOperandSpace(2);
11899 PN->addIncoming(SI.getOperand(0), SI.getParent());
11900 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11901 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11902 }
11903
11904 // Advance to a place where it is safe to insert the new store and
11905 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000011906 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011907 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11908 OtherStore->isVolatile()), *BBI);
11909
11910 // Nuke the old stores.
11911 EraseInstFromFunction(SI);
11912 EraseInstFromFunction(*OtherStore);
11913 ++NumCombined;
11914 return true;
11915}
11916
11917
11918Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11919 // Change br (not X), label True, label False to: br X, label False, True
11920 Value *X = 0;
11921 BasicBlock *TrueDest;
11922 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +000011923 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011924 !isa<Constant>(X)) {
11925 // Swap Destinations and condition...
11926 BI.setCondition(X);
11927 BI.setSuccessor(0, FalseDest);
11928 BI.setSuccessor(1, TrueDest);
11929 return &BI;
11930 }
11931
11932 // Cannonicalize fcmp_one -> fcmp_oeq
11933 FCmpInst::Predicate FPred; Value *Y;
11934 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000011935 TrueDest, FalseDest)) &&
11936 BI.getCondition()->hasOneUse())
11937 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11938 FPred == FCmpInst::FCMP_OGE) {
11939 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11940 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11941
11942 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011943 BI.setSuccessor(0, FalseDest);
11944 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000011945 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011946 return &BI;
11947 }
11948
11949 // Cannonicalize icmp_ne -> icmp_eq
11950 ICmpInst::Predicate IPred;
11951 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000011952 TrueDest, FalseDest)) &&
11953 BI.getCondition()->hasOneUse())
11954 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11955 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11956 IPred == ICmpInst::ICMP_SGE) {
11957 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11958 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11959 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011960 BI.setSuccessor(0, FalseDest);
11961 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000011962 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011963 return &BI;
11964 }
11965
11966 return 0;
11967}
11968
11969Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11970 Value *Cond = SI.getCondition();
11971 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11972 if (I->getOpcode() == Instruction::Add)
11973 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11974 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11975 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000011976 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +000011977 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011978 AddRHS));
11979 SI.setOperand(0, I->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +000011980 Worklist.Add(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011981 return &SI;
11982 }
11983 }
11984 return 0;
11985}
11986
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011987Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011988 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011989
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011990 if (!EV.hasIndices())
11991 return ReplaceInstUsesWith(EV, Agg);
11992
11993 if (Constant *C = dyn_cast<Constant>(Agg)) {
11994 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011995 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011996
11997 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +000011998 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011999
12000 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12001 // Extract the element indexed by the first index out of the constant
12002 Value *V = C->getOperand(*EV.idx_begin());
12003 if (EV.getNumIndices() > 1)
12004 // Extract the remaining indices out of the constant indexed by the
12005 // first index
12006 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12007 else
12008 return ReplaceInstUsesWith(EV, V);
12009 }
12010 return 0; // Can't handle other constants
12011 }
12012 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12013 // We're extracting from an insertvalue instruction, compare the indices
12014 const unsigned *exti, *exte, *insi, *inse;
12015 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12016 exte = EV.idx_end(), inse = IV->idx_end();
12017 exti != exte && insi != inse;
12018 ++exti, ++insi) {
12019 if (*insi != *exti)
12020 // The insert and extract both reference distinctly different elements.
12021 // This means the extract is not influenced by the insert, and we can
12022 // replace the aggregate operand of the extract with the aggregate
12023 // operand of the insert. i.e., replace
12024 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12025 // %E = extractvalue { i32, { i32 } } %I, 0
12026 // with
12027 // %E = extractvalue { i32, { i32 } } %A, 0
12028 return ExtractValueInst::Create(IV->getAggregateOperand(),
12029 EV.idx_begin(), EV.idx_end());
12030 }
12031 if (exti == exte && insi == inse)
12032 // Both iterators are at the end: Index lists are identical. Replace
12033 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12034 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12035 // with "i32 42"
12036 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12037 if (exti == exte) {
12038 // The extract list is a prefix of the insert list. i.e. replace
12039 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12040 // %E = extractvalue { i32, { i32 } } %I, 1
12041 // with
12042 // %X = extractvalue { i32, { i32 } } %A, 1
12043 // %E = insertvalue { i32 } %X, i32 42, 0
12044 // by switching the order of the insert and extract (though the
12045 // insertvalue should be left in, since it may have other uses).
Chris Lattnerad7516a2009-08-30 18:50:58 +000012046 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12047 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012048 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12049 insi, inse);
12050 }
12051 if (insi == inse)
12052 // The insert list is a prefix of the extract list
12053 // We can simply remove the common indices from the extract and make it
12054 // operate on the inserted value instead of the insertvalue result.
12055 // i.e., replace
12056 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12057 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12058 // with
12059 // %E extractvalue { i32 } { i32 42 }, 0
12060 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12061 exti, exte);
12062 }
12063 // Can't simplify extracts from other values. Note that nested extracts are
12064 // already simplified implicitely by the above (extract ( extract (insert) )
12065 // will be translated into extract ( insert ( extract ) ) first and then just
12066 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012067 return 0;
12068}
12069
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012070/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12071/// is to leave as a vector operation.
12072static bool CheapToScalarize(Value *V, bool isConstant) {
12073 if (isa<ConstantAggregateZero>(V))
12074 return true;
12075 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12076 if (isConstant) return true;
12077 // If all elts are the same, we can extract.
12078 Constant *Op0 = C->getOperand(0);
12079 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12080 if (C->getOperand(i) != Op0)
12081 return false;
12082 return true;
12083 }
12084 Instruction *I = dyn_cast<Instruction>(V);
12085 if (!I) return false;
12086
12087 // Insert element gets simplified to the inserted element or is deleted if
12088 // this is constant idx extract element and its a constant idx insertelt.
12089 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12090 isa<ConstantInt>(I->getOperand(2)))
12091 return true;
12092 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12093 return true;
12094 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12095 if (BO->hasOneUse() &&
12096 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12097 CheapToScalarize(BO->getOperand(1), isConstant)))
12098 return true;
12099 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12100 if (CI->hasOneUse() &&
12101 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12102 CheapToScalarize(CI->getOperand(1), isConstant)))
12103 return true;
12104
12105 return false;
12106}
12107
12108/// Read and decode a shufflevector mask.
12109///
12110/// It turns undef elements into values that are larger than the number of
12111/// elements in the input.
12112static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12113 unsigned NElts = SVI->getType()->getNumElements();
12114 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12115 return std::vector<unsigned>(NElts, 0);
12116 if (isa<UndefValue>(SVI->getOperand(2)))
12117 return std::vector<unsigned>(NElts, 2*NElts);
12118
12119 std::vector<unsigned> Result;
12120 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012121 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12122 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012123 Result.push_back(NElts*2); // undef -> 8
12124 else
Gabor Greif17396002008-06-12 21:37:33 +000012125 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012126 return Result;
12127}
12128
12129/// FindScalarElement - Given a vector and an element number, see if the scalar
12130/// value is already around as a register, for example if it were inserted then
12131/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012132static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012133 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012134 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12135 const VectorType *PTy = cast<VectorType>(V->getType());
12136 unsigned Width = PTy->getNumElements();
12137 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012138 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012139
12140 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012141 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012142 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +000012143 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012144 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12145 return CP->getOperand(EltNo);
12146 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12147 // If this is an insert to a variable element, we don't know what it is.
12148 if (!isa<ConstantInt>(III->getOperand(2)))
12149 return 0;
12150 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12151
12152 // If this is an insert to the element we are looking for, return the
12153 // inserted value.
12154 if (EltNo == IIElt)
12155 return III->getOperand(1);
12156
12157 // Otherwise, the insertelement doesn't modify the value, recurse on its
12158 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000012159 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012160 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012161 unsigned LHSWidth =
12162 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012163 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012164 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012165 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012166 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012167 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012168 else
Owen Andersonb99ecca2009-07-30 23:03:37 +000012169 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012170 }
12171
12172 // Otherwise, we don't know.
12173 return 0;
12174}
12175
12176Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012177 // If vector val is undef, replace extract with scalar undef.
12178 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012179 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012180
12181 // If vector val is constant 0, replace extract with scalar 0.
12182 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +000012183 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012184
12185 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012186 // If vector val is constant with all elements the same, replace EI with
12187 // that element. When the elements are not identical, we cannot replace yet
12188 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012189 Constant *op0 = C->getOperand(0);
Chris Lattner1ba36b72009-09-08 03:44:51 +000012190 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012191 if (C->getOperand(i) != op0) {
12192 op0 = 0;
12193 break;
12194 }
12195 if (op0)
12196 return ReplaceInstUsesWith(EI, op0);
12197 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000012198
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012199 // If extracting a specified index from the vector, see if we can recursively
12200 // find a previously computed scalar that was inserted into the vector.
12201 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12202 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner1ba36b72009-09-08 03:44:51 +000012203 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012204
12205 // If this is extracting an invalid index, turn this into undef, to avoid
12206 // crashing the code below.
12207 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +000012208 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012209
12210 // This instruction only demands the single element from the input vector.
12211 // If the input vector has a single use, simplify it based on this use
12212 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000012213 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012214 APInt UndefElts(VectorWidth, 0);
12215 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012216 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012217 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012218 EI.setOperand(0, V);
12219 return &EI;
12220 }
12221 }
12222
Owen Anderson24be4c12009-07-03 00:17:18 +000012223 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012224 return ReplaceInstUsesWith(EI, Elt);
12225
12226 // If the this extractelement is directly using a bitcast from a vector of
12227 // the same number of elements, see if we can find the source element from
12228 // it. In this case, we will end up needing to bitcast the scalars.
12229 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12230 if (const VectorType *VT =
12231 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12232 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012233 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12234 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012235 return new BitCastInst(Elt, EI.getType());
12236 }
12237 }
12238
12239 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattnera97bc602009-09-08 18:48:01 +000012240 // Push extractelement into predecessor operation if legal and
12241 // profitable to do so
12242 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12243 if (I->hasOneUse() &&
12244 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12245 Value *newEI0 =
12246 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12247 EI.getName()+".lhs");
12248 Value *newEI1 =
12249 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12250 EI.getName()+".rhs");
12251 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012252 }
Chris Lattnera97bc602009-09-08 18:48:01 +000012253 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012254 // Extracting the inserted element?
12255 if (IE->getOperand(2) == EI.getOperand(1))
12256 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12257 // If the inserted and extracted elements are constants, they must not
12258 // be the same value, extract from the pre-inserted value instead.
Chris Lattner78628292009-08-30 19:47:22 +000012259 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +000012260 Worklist.AddValue(EI.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012261 EI.setOperand(0, IE->getOperand(0));
12262 return &EI;
12263 }
12264 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12265 // If this is extracting an element from a shufflevector, figure out where
12266 // it came from and extract from the appropriate input element instead.
12267 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12268 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12269 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012270 unsigned LHSWidth =
12271 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12272
12273 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012274 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012275 else if (SrcIdx < LHSWidth*2) {
12276 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012277 Src = SVI->getOperand(1);
12278 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012279 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012280 }
Eric Christopher1ba36872009-07-25 02:28:41 +000012281 return ExtractElementInst::Create(Src,
Chris Lattner78628292009-08-30 19:47:22 +000012282 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12283 false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012284 }
12285 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000012286 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012287 }
12288 return 0;
12289}
12290
12291/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12292/// elements from either LHS or RHS, return the shuffle mask and true.
12293/// Otherwise, return false.
12294static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000012295 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012296 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012297 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12298 "Invalid CollectSingleShuffleElements");
12299 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12300
12301 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012302 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012303 return true;
12304 } else if (V == LHS) {
12305 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012306 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012307 return true;
12308 } else if (V == RHS) {
12309 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012310 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012311 return true;
12312 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12313 // If this is an insert of an extract from some other vector, include it.
12314 Value *VecOp = IEI->getOperand(0);
12315 Value *ScalarOp = IEI->getOperand(1);
12316 Value *IdxOp = IEI->getOperand(2);
12317
12318 if (!isa<ConstantInt>(IdxOp))
12319 return false;
12320 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12321
12322 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12323 // Okay, we can handle this if the vector we are insertinting into is
12324 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012325 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012326 // If so, update the mask to reflect the inserted undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012327 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012328 return true;
12329 }
12330 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12331 if (isa<ConstantInt>(EI->getOperand(1)) &&
12332 EI->getOperand(0)->getType() == V->getType()) {
12333 unsigned ExtractedIdx =
12334 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12335
12336 // This must be extracting from either LHS or RHS.
12337 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12338 // Okay, we can handle this if the vector we are insertinting into is
12339 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012340 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012341 // If so, update the mask to reflect the inserted value.
12342 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012343 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012344 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012345 } else {
12346 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012347 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012348 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012349
12350 }
12351 return true;
12352 }
12353 }
12354 }
12355 }
12356 }
12357 // TODO: Handle shufflevector here!
12358
12359 return false;
12360}
12361
12362/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12363/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12364/// that computes V and the LHS value of the shuffle.
12365static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012366 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012367 assert(isa<VectorType>(V->getType()) &&
12368 (RHS == 0 || V->getType() == RHS->getType()) &&
12369 "Invalid shuffle!");
12370 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12371
12372 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012373 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012374 return V;
12375 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012376 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012377 return V;
12378 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12379 // If this is an insert of an extract from some other vector, include it.
12380 Value *VecOp = IEI->getOperand(0);
12381 Value *ScalarOp = IEI->getOperand(1);
12382 Value *IdxOp = IEI->getOperand(2);
12383
12384 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12385 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12386 EI->getOperand(0)->getType() == V->getType()) {
12387 unsigned ExtractedIdx =
12388 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12389 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12390
12391 // Either the extracted from or inserted into vector must be RHSVec,
12392 // otherwise we'd end up with a shuffle of three inputs.
12393 if (EI->getOperand(0) == RHS || RHS == 0) {
12394 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000012395 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012396 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012397 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012398 return V;
12399 }
12400
12401 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012402 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12403 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012404 // Everything but the extracted element is replaced with the RHS.
12405 for (unsigned i = 0; i != NumElts; ++i) {
12406 if (i != InsertedIdx)
Owen Anderson35b47072009-08-13 21:58:54 +000012407 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012408 }
12409 return V;
12410 }
12411
12412 // If this insertelement is a chain that comes from exactly these two
12413 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000012414 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12415 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012416 return EI->getOperand(0);
12417
12418 }
12419 }
12420 }
12421 // TODO: Handle shufflevector here!
12422
12423 // Otherwise, can't do anything fancy. Return an identity vector.
12424 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012425 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012426 return V;
12427}
12428
12429Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12430 Value *VecOp = IE.getOperand(0);
12431 Value *ScalarOp = IE.getOperand(1);
12432 Value *IdxOp = IE.getOperand(2);
12433
12434 // Inserting an undef or into an undefined place, remove this.
12435 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12436 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000012437
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012438 // If the inserted element was extracted from some other vector, and if the
12439 // indexes are constant, try to turn this into a shufflevector operation.
12440 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12441 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12442 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000012443 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012444 unsigned ExtractedIdx =
12445 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12446 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12447
12448 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12449 return ReplaceInstUsesWith(IE, VecOp);
12450
12451 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012452 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012453
12454 // If we are extracting a value from a vector, then inserting it right
12455 // back into the same place, just use the input vector.
12456 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12457 return ReplaceInstUsesWith(IE, VecOp);
12458
12459 // We could theoretically do this for ANY input. However, doing so could
12460 // turn chains of insertelement instructions into a chain of shufflevector
12461 // instructions, and right now we do not merge shufflevectors. As such,
12462 // only do this in a situation where it is clear that there is benefit.
12463 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12464 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12465 // the values of VecOp, except then one read from EIOp0.
12466 // Build a new shuffle mask.
12467 std::vector<Constant*> Mask;
12468 if (isa<UndefValue>(VecOp))
Owen Anderson35b47072009-08-13 21:58:54 +000012469 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012470 else {
12471 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson35b47072009-08-13 21:58:54 +000012472 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012473 NumVectorElts));
12474 }
Owen Anderson24be4c12009-07-03 00:17:18 +000012475 Mask[InsertedIdx] =
Owen Anderson35b47072009-08-13 21:58:54 +000012476 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012477 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Anderson2f422e02009-07-28 21:19:26 +000012478 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012479 }
12480
12481 // If this insertelement isn't used by some other insertelement, turn it
12482 // (and any insertelements it points to), into one big shuffle.
12483 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12484 std::vector<Constant*> Mask;
12485 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000012486 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Andersonb99ecca2009-07-30 23:03:37 +000012487 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012488 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000012489 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +000012490 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012491 }
12492 }
12493 }
12494
Eli Friedmanbefee262009-06-06 20:08:03 +000012495 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12496 APInt UndefElts(VWidth, 0);
12497 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12498 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12499 return &IE;
12500
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012501 return 0;
12502}
12503
12504
12505Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12506 Value *LHS = SVI.getOperand(0);
12507 Value *RHS = SVI.getOperand(1);
12508 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12509
12510 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012511
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012512 // Undefined shuffle mask -> undefined value.
12513 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012514 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012515
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012516 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012517
12518 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12519 return 0;
12520
Evan Cheng63295ab2009-02-03 10:05:09 +000012521 APInt UndefElts(VWidth, 0);
12522 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12523 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012524 LHS = SVI.getOperand(0);
12525 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012526 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012527 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012528
12529 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12530 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12531 if (LHS == RHS || isa<UndefValue>(LHS)) {
12532 if (isa<UndefValue>(LHS) && LHS == RHS) {
12533 // shuffle(undef,undef,mask) -> undef.
12534 return ReplaceInstUsesWith(SVI, LHS);
12535 }
12536
12537 // Remap any references to RHS to use LHS.
12538 std::vector<Constant*> Elts;
12539 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12540 if (Mask[i] >= 2*e)
Owen Anderson35b47072009-08-13 21:58:54 +000012541 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012542 else {
12543 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012544 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012545 Mask[i] = 2*e; // Turn into undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012546 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012547 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012548 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson35b47072009-08-13 21:58:54 +000012549 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012550 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012551 }
12552 }
12553 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +000012554 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +000012555 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012556 LHS = SVI.getOperand(0);
12557 RHS = SVI.getOperand(1);
12558 MadeChange = true;
12559 }
12560
12561 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12562 bool isLHSID = true, isRHSID = true;
12563
12564 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12565 if (Mask[i] >= e*2) continue; // Ignore undef values.
12566 // Is this an identity shuffle of the LHS value?
12567 isLHSID &= (Mask[i] == i);
12568
12569 // Is this an identity shuffle of the RHS value?
12570 isRHSID &= (Mask[i]-e == i);
12571 }
12572
12573 // Eliminate identity shuffles.
12574 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12575 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12576
12577 // If the LHS is a shufflevector itself, see if we can combine it with this
12578 // one without producing an unusual shuffle. Here we are really conservative:
12579 // we are absolutely afraid of producing a shuffle mask not in the input
12580 // program, because the code gen may not be smart enough to turn a merged
12581 // shuffle into two specific shuffles: it may produce worse code. As such,
12582 // we only merge two shuffles if the result is one of the two input shuffle
12583 // masks. In this case, merging the shuffles just removes one instruction,
12584 // which we know is safe. This is good for things like turning:
12585 // (splat(splat)) -> splat.
12586 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12587 if (isa<UndefValue>(RHS)) {
12588 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12589
12590 std::vector<unsigned> NewMask;
12591 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12592 if (Mask[i] >= 2*e)
12593 NewMask.push_back(2*e);
12594 else
12595 NewMask.push_back(LHSMask[Mask[i]]);
12596
12597 // If the result mask is equal to the src shuffle or this shuffle mask, do
12598 // the replacement.
12599 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000012600 unsigned LHSInNElts =
12601 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012602 std::vector<Constant*> Elts;
12603 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000012604 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson35b47072009-08-13 21:58:54 +000012605 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012606 } else {
Owen Anderson35b47072009-08-13 21:58:54 +000012607 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012608 }
12609 }
12610 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12611 LHSSVI->getOperand(1),
Owen Anderson2f422e02009-07-28 21:19:26 +000012612 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012613 }
12614 }
12615 }
12616
12617 return MadeChange ? &SVI : 0;
12618}
12619
12620
12621
12622
12623/// TryToSinkInstruction - Try to move the specified instruction from its
12624/// current block into the beginning of DestBlock, which can only happen if it's
12625/// safe to move the instruction past all of the instructions between it and the
12626/// end of its block.
12627static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12628 assert(I->hasOneUse() && "Invariants didn't hold!");
12629
12630 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000012631 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012632 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012633
12634 // Do not sink alloca instructions out of the entry block.
12635 if (isa<AllocaInst>(I) && I->getParent() ==
12636 &DestBlock->getParent()->getEntryBlock())
12637 return false;
12638
12639 // We can only sink load instructions if there is nothing between the load and
12640 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012641 if (I->mayReadFromMemory()) {
12642 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012643 Scan != E; ++Scan)
12644 if (Scan->mayWriteToMemory())
12645 return false;
12646 }
12647
Dan Gohman514277c2008-05-23 21:05:58 +000012648 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012649
Dale Johannesen24339f12009-03-03 01:09:07 +000012650 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012651 I->moveBefore(InsertPos);
12652 ++NumSunkInst;
12653 return true;
12654}
12655
12656
12657/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12658/// all reachable code to the worklist.
12659///
12660/// This has a couple of tricks to make the code faster and more powerful. In
12661/// particular, we constant fold and DCE instructions as we go, to avoid adding
12662/// them to the worklist (this significantly speeds up instcombine on code where
12663/// many instructions are dead or constant). Additionally, if we find a branch
12664/// whose condition is a known constant, we only visit the reachable successors.
12665///
12666static void AddReachableCodeToWorklist(BasicBlock *BB,
12667 SmallPtrSet<BasicBlock*, 64> &Visited,
12668 InstCombiner &IC,
12669 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000012670 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012671 Worklist.push_back(BB);
12672
12673 while (!Worklist.empty()) {
12674 BB = Worklist.back();
12675 Worklist.pop_back();
12676
12677 // We have now visited this block! If we've already been here, ignore it.
12678 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012679
12680 DbgInfoIntrinsic *DBI_Prev = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012681 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12682 Instruction *Inst = BBI++;
12683
12684 // DCE instruction if trivially dead.
12685 if (isInstructionTriviallyDead(Inst)) {
12686 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +000012687 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012688 Inst->eraseFromParent();
12689 continue;
12690 }
12691
12692 // ConstantProp instruction if trivially constant.
Owen Andersond4d90a02009-07-06 18:42:36 +000012693 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012694 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12695 << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012696 Inst->replaceAllUsesWith(C);
12697 ++NumConstProp;
12698 Inst->eraseFromParent();
12699 continue;
12700 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000012701
Devang Patel794140c2008-11-19 18:56:50 +000012702 // If there are two consecutive llvm.dbg.stoppoint calls then
12703 // it is likely that the optimizer deleted code in between these
12704 // two intrinsics.
12705 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12706 if (DBI_Next) {
12707 if (DBI_Prev
12708 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12709 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner3183fb62009-08-30 06:13:40 +000012710 IC.Worklist.Remove(DBI_Prev);
Devang Patel794140c2008-11-19 18:56:50 +000012711 DBI_Prev->eraseFromParent();
12712 }
12713 DBI_Prev = DBI_Next;
Zhou Sheng77e03b92009-02-23 10:14:11 +000012714 } else {
12715 DBI_Prev = 0;
Devang Patel794140c2008-11-19 18:56:50 +000012716 }
12717
Chris Lattner3183fb62009-08-30 06:13:40 +000012718 IC.Worklist.Add(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012719 }
12720
12721 // Recursively visit successors. If this is a branch or switch on a
12722 // constant, only visit the reachable successor.
12723 TerminatorInst *TI = BB->getTerminator();
12724 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12725 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12726 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012727 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012728 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012729 continue;
12730 }
12731 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12732 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12733 // See if this is an explicit destination.
12734 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12735 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012736 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012737 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012738 continue;
12739 }
12740
12741 // Otherwise it is the default destination.
12742 Worklist.push_back(SI->getSuccessor(0));
12743 continue;
12744 }
12745 }
12746
12747 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12748 Worklist.push_back(TI->getSuccessor(i));
12749 }
12750}
12751
12752bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner21d79e22009-08-31 06:57:37 +000012753 MadeIRChange = false;
Dan Gohmana80e2712009-07-21 23:21:54 +000012754 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012755
Daniel Dunbar005975c2009-07-25 00:23:56 +000012756 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12757 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012758
12759 {
12760 // Do a depth-first traversal of the function, populate the worklist with
12761 // the reachable instructions. Ignore blocks that are not reachable. Keep
12762 // track of which blocks we visit.
12763 SmallPtrSet<BasicBlock*, 64> Visited;
12764 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12765
12766 // Do a quick scan over the function. If we find any blocks that are
12767 // unreachable, remove any instructions inside of them. This prevents
12768 // the instcombine code from having to deal with some bad special cases.
12769 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12770 if (!Visited.count(BB)) {
12771 Instruction *Term = BB->getTerminator();
12772 while (Term != BB->begin()) { // Remove instrs bottom-up
12773 BasicBlock::iterator I = Term; --I;
12774
Chris Lattner8a6411c2009-08-23 04:37:46 +000012775 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +000012776 // A debug intrinsic shouldn't force another iteration if we weren't
12777 // going to do one without it.
12778 if (!isa<DbgInfoIntrinsic>(I)) {
12779 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000012780 MadeIRChange = true;
Dale Johannesendf356c62009-03-10 21:19:49 +000012781 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012782 if (!I->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +000012783 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012784 I->eraseFromParent();
12785 }
12786 }
12787 }
12788
Chris Lattner5119c702009-08-30 05:55:36 +000012789 while (!Worklist.isEmpty()) {
12790 Instruction *I = Worklist.RemoveOne();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012791 if (I == 0) continue; // skip null values.
12792
12793 // Check to see if we can DCE the instruction.
12794 if (isInstructionTriviallyDead(I)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012795 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner3183fb62009-08-30 06:13:40 +000012796 EraseInstFromFunction(*I);
12797 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000012798 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012799 continue;
12800 }
12801
12802 // Instruction isn't dead, see if we can constant propagate it.
Owen Andersond4d90a02009-07-06 18:42:36 +000012803 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012804 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012805
12806 // Add operands to the worklist.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012807 ReplaceInstUsesWith(*I, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012808 ++NumConstProp;
Chris Lattner3183fb62009-08-30 06:13:40 +000012809 EraseInstFromFunction(*I);
Chris Lattner21d79e22009-08-31 06:57:37 +000012810 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012811 continue;
12812 }
12813
Eli Friedman5c619182009-07-15 22:13:34 +000012814 if (TD) {
Nick Lewyckyadb67922008-05-25 20:56:15 +000012815 // See if we can constant fold its operands.
Chris Lattnerf6d58862009-01-31 07:04:22 +000012816 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12817 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Andersond4d90a02009-07-06 18:42:36 +000012818 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12819 F.getContext(), TD))
Chris Lattnerf6d58862009-01-31 07:04:22 +000012820 if (NewC != CE) {
12821 i->set(NewC);
Chris Lattner21d79e22009-08-31 06:57:37 +000012822 MadeIRChange = true;
Chris Lattnerf6d58862009-01-31 07:04:22 +000012823 }
Nick Lewyckyadb67922008-05-25 20:56:15 +000012824 }
12825
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012826 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000012827 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012828 BasicBlock *BB = I->getParent();
12829 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12830 if (UserParent != BB) {
12831 bool UserIsSuccessor = false;
12832 // See if the user is one of our successors.
12833 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12834 if (*SI == UserParent) {
12835 UserIsSuccessor = true;
12836 break;
12837 }
12838
12839 // If the user is one of our immediate successors, and if that successor
12840 // only has us as a predecessors (we'd have to split the critical edge
12841 // otherwise), we can keep going.
12842 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12843 next(pred_begin(UserParent)) == pred_end(UserParent))
12844 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattner21d79e22009-08-31 06:57:37 +000012845 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012846 }
12847 }
12848
Chris Lattnerc7694852009-08-30 07:44:24 +000012849 // Now that we have an instruction, try combining it to simplify it.
12850 Builder->SetInsertPoint(I->getParent(), I);
12851
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012852#ifndef NDEBUG
12853 std::string OrigI;
12854#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +000012855 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattnerc7694852009-08-30 07:44:24 +000012856
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012857 if (Instruction *Result = visit(*I)) {
12858 ++NumCombined;
12859 // Should we replace the old instruction with a new one?
12860 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012861 DEBUG(errs() << "IC: Old = " << *I << '\n'
12862 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012863
12864 // Everything uses the new instruction now.
12865 I->replaceAllUsesWith(Result);
12866
12867 // Push the new instruction and any users onto the worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +000012868 Worklist.Add(Result);
Chris Lattner4796b622009-08-30 06:22:51 +000012869 Worklist.AddUsersToWorkList(*Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012870
12871 // Move the name to the new instruction first.
12872 Result->takeName(I);
12873
12874 // Insert the new instruction into the basic block...
12875 BasicBlock *InstParent = I->getParent();
12876 BasicBlock::iterator InsertPos = I;
12877
12878 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12879 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12880 ++InsertPos;
12881
12882 InstParent->getInstList().insert(InsertPos, Result);
12883
Chris Lattner3183fb62009-08-30 06:13:40 +000012884 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012885 } else {
12886#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +000012887 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12888 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012889#endif
12890
12891 // If the instruction was modified, it's possible that it is now dead.
12892 // if so, remove it.
12893 if (isInstructionTriviallyDead(I)) {
Chris Lattner3183fb62009-08-30 06:13:40 +000012894 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012895 } else {
Chris Lattner3183fb62009-08-30 06:13:40 +000012896 Worklist.Add(I);
Chris Lattner4796b622009-08-30 06:22:51 +000012897 Worklist.AddUsersToWorkList(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012898 }
12899 }
Chris Lattner21d79e22009-08-31 06:57:37 +000012900 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012901 }
12902 }
12903
Chris Lattner5119c702009-08-30 05:55:36 +000012904 Worklist.Zap();
Chris Lattner21d79e22009-08-31 06:57:37 +000012905 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012906}
12907
12908
12909bool InstCombiner::runOnFunction(Function &F) {
12910 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000012911 Context = &F.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012912
Chris Lattnerc7694852009-08-30 07:44:24 +000012913
12914 /// Builder - This is an IRBuilder that automatically inserts new
12915 /// instructions into the worklist when they are created.
12916 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12917 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12918 InstCombineIRInserter(Worklist));
12919 Builder = &TheBuilder;
12920
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012921 bool EverMadeChange = false;
12922
12923 // Iterate while there is work to do.
12924 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000012925 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012926 EverMadeChange = true;
Chris Lattnerc7694852009-08-30 07:44:24 +000012927
12928 Builder = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012929 return EverMadeChange;
12930}
12931
12932FunctionPass *llvm::createInstructionCombiningPass() {
12933 return new InstCombiner();
12934}