blob: 514e91bdef32d6baea755388b86ba9983b571647 [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"
Chris Lattnera432bc72008-06-02 01:18:21 +000045#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Local.h"
49#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000050#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
54#include "llvm/Support/InstVisitor.h"
55#include "llvm/Support/MathExtras.h"
56#include "llvm/Support/PatternMatch.h"
57#include "llvm/Support/Compiler.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000058#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059#include "llvm/ADT/DenseMap.h"
60#include "llvm/ADT/SmallVector.h"
61#include "llvm/ADT/SmallPtrSet.h"
62#include "llvm/ADT/Statistic.h"
63#include "llvm/ADT/STLExtras.h"
64#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000065#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000066#include <sstream>
67using 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 {
77 class VISIBILITY_HIDDEN InstCombiner
78 : public FunctionPass,
79 public InstVisitor<InstCombiner, Instruction*> {
80 // Worklist of all of the instructions that need to be simplified.
Chris Lattnera06291a2008-08-15 04:03:01 +000081 SmallVector<Instruction*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082 DenseMap<Instruction*, unsigned> WorklistMap;
83 TargetData *TD;
84 bool MustPreserveLCSSA;
85 public:
86 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000087 InstCombiner() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088
Owen Anderson175b6542009-07-22 00:24:57 +000089 LLVMContext *Context;
90 LLVMContext *getContext() const { return Context; }
Owen Anderson24be4c12009-07-03 00:17:18 +000091
Dan Gohmanf17a25c2007-07-18 16:29:46 +000092 /// AddToWorkList - Add the specified instruction to the worklist if it
93 /// isn't already in it.
94 void AddToWorkList(Instruction *I) {
Dan Gohman55d19662008-07-07 17:46:23 +000095 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096 Worklist.push_back(I);
97 }
98
99 // RemoveFromWorkList - remove I from the worklist if it exists.
100 void RemoveFromWorkList(Instruction *I) {
101 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
102 if (It == WorklistMap.end()) return; // Not in worklist.
103
104 // Don't bother moving everything down, just null out the slot.
105 Worklist[It->second] = 0;
106
107 WorklistMap.erase(It);
108 }
109
110 Instruction *RemoveOneFromWorkList() {
111 Instruction *I = Worklist.back();
112 Worklist.pop_back();
113 WorklistMap.erase(I);
114 return I;
115 }
116
117
118 /// AddUsersToWorkList - When an instruction is simplified, add all users of
119 /// the instruction to the work lists because they might get more simplified
120 /// now.
121 ///
122 void AddUsersToWorkList(Value &I) {
123 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
124 UI != UE; ++UI)
125 AddToWorkList(cast<Instruction>(*UI));
126 }
127
128 /// AddUsesToWorkList - When an instruction is simplified, add operands to
129 /// the work lists because they might get more simplified now.
130 ///
131 void AddUsesToWorkList(Instruction &I) {
Gabor Greif17396002008-06-12 21:37:33 +0000132 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
133 if (Instruction *Op = dyn_cast<Instruction>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134 AddToWorkList(Op);
135 }
136
137 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
138 /// dead. Add all of its operands to the worklist, turning them into
139 /// undef's to reduce the number of uses of those instructions.
140 ///
141 /// Return the specified operand before it is turned into an undef.
142 ///
143 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
144 Value *R = I.getOperand(op);
145
Gabor Greif17396002008-06-12 21:37:33 +0000146 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
147 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148 AddToWorkList(Op);
149 // Set the operand to undef to drop the use.
Owen Andersonb99ecca2009-07-30 23:03:37 +0000150 *i = UndefValue::get(Op->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151 }
152
153 return R;
154 }
155
156 public:
157 virtual bool runOnFunction(Function &F);
158
159 bool DoOneIteration(Function &F, unsigned ItNum);
160
161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 AU.addPreservedID(LCSSAID);
163 AU.setPreservesCFG();
164 }
165
Dan Gohmana80e2712009-07-21 23:21:54 +0000166 TargetData *getTargetData() const { return TD; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167
168 // Visitation implementation - Implement instruction combining for different
169 // instruction types. The semantics are as follows:
170 // Return Value:
171 // null - No change was made
172 // I - Change was made, I is still valid, I may be dead though
173 // otherwise - Change was made, replace I with returned instruction
174 //
175 Instruction *visitAdd(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000176 Instruction *visitFAdd(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000178 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000180 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 Instruction *visitURem(BinaryOperator &I);
182 Instruction *visitSRem(BinaryOperator &I);
183 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000184 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 Instruction *commonRemTransforms(BinaryOperator &I);
186 Instruction *commonIRemTransforms(BinaryOperator &I);
187 Instruction *commonDivTransforms(BinaryOperator &I);
188 Instruction *commonIDivTransforms(BinaryOperator &I);
189 Instruction *visitUDiv(BinaryOperator &I);
190 Instruction *visitSDiv(BinaryOperator &I);
191 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000192 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +0000193 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000195 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner57e66fa2009-07-23 05:46:22 +0000196 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000197 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000198 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 Instruction *visitOr (BinaryOperator &I);
200 Instruction *visitXor(BinaryOperator &I);
201 Instruction *visitShl(BinaryOperator &I);
202 Instruction *visitAShr(BinaryOperator &I);
203 Instruction *visitLShr(BinaryOperator &I);
204 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000205 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
206 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000207 Instruction *visitFCmpInst(FCmpInst &I);
208 Instruction *visitICmpInst(ICmpInst &I);
209 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
210 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
211 Instruction *LHS,
212 ConstantInt *RHS);
213 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
214 ConstantInt *DivRHS);
215
Dan Gohman17f46f72009-07-28 01:40:03 +0000216 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 ICmpInst::Predicate Cond, Instruction &I);
218 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
219 BinaryOperator &I);
220 Instruction *commonCastTransforms(CastInst &CI);
221 Instruction *commonIntCastTransforms(CastInst &CI);
222 Instruction *commonPointerCastTransforms(CastInst &CI);
223 Instruction *visitTrunc(TruncInst &CI);
224 Instruction *visitZExt(ZExtInst &CI);
225 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000226 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000228 Instruction *visitFPToUI(FPToUIInst &FI);
229 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 Instruction *visitUIToFP(CastInst &CI);
231 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000232 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000233 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 Instruction *visitBitCast(BitCastInst &CI);
235 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
236 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000237 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman58c09632008-09-16 18:46:06 +0000238 Instruction *visitSelectInst(SelectInst &SI);
239 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240 Instruction *visitCallInst(CallInst &CI);
241 Instruction *visitInvokeInst(InvokeInst &II);
242 Instruction *visitPHINode(PHINode &PN);
243 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
244 Instruction *visitAllocationInst(AllocationInst &AI);
245 Instruction *visitFreeInst(FreeInst &FI);
246 Instruction *visitLoadInst(LoadInst &LI);
247 Instruction *visitStoreInst(StoreInst &SI);
248 Instruction *visitBranchInst(BranchInst &BI);
249 Instruction *visitSwitchInst(SwitchInst &SI);
250 Instruction *visitInsertElementInst(InsertElementInst &IE);
251 Instruction *visitExtractElementInst(ExtractElementInst &EI);
252 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000253 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254
255 // visitInstruction - Specify what to return for unhandled instructions...
256 Instruction *visitInstruction(Instruction &I) { return 0; }
257
258 private:
259 Instruction *visitCallSite(CallSite CS);
260 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000261 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000262 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
263 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000264 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000265 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
266
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267
268 public:
269 // InsertNewInstBefore - insert an instruction New before instruction Old
270 // in the program. Add the new instruction to the worklist.
271 //
272 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
273 assert(New && New->getParent() == 0 &&
274 "New instruction already inserted into a basic block!");
275 BasicBlock *BB = Old.getParent();
276 BB->getInstList().insert(&Old, New); // Insert inst
277 AddToWorkList(New);
278 return New;
279 }
280
281 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
282 /// This also adds the cast to the worklist. Finally, this returns the
283 /// cast.
284 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
285 Instruction &Pos) {
286 if (V->getType() == Ty) return V;
287
288 if (Constant *CV = dyn_cast<Constant>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000289 return ConstantExpr::getCast(opc, CV, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290
Gabor Greifa645dd32008-05-16 19:29:10 +0000291 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 AddToWorkList(C);
293 return C;
294 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000295
296 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
297 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
298 }
299
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300
301 // ReplaceInstUsesWith - This method is to be used when an instruction is
302 // found to be dead, replacable with another preexisting expression. Here
303 // we add all uses of I to the worklist, replace all uses of I with the new
304 // value, then return I, so that the inst combiner will know that I was
305 // modified.
306 //
307 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
308 AddUsersToWorkList(I); // Add all modified instrs to worklist
309 if (&I != V) {
310 I.replaceAllUsesWith(V);
311 return &I;
312 } else {
313 // If we are replacing the instruction with itself, this must be in a
314 // segment of unreachable code, so just clobber the instruction.
Owen Andersonb99ecca2009-07-30 23:03:37 +0000315 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 return &I;
317 }
318 }
319
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000320 // EraseInstFromFunction - When dealing with an instruction that has side
321 // effects or produces a void value, we can't rely on DCE to delete the
322 // instruction. Instead, visit methods should return the value returned by
323 // this function.
324 Instruction *EraseInstFromFunction(Instruction &I) {
325 assert(I.use_empty() && "Cannot erase instruction that is used!");
326 AddUsesToWorkList(I);
327 RemoveFromWorkList(&I);
328 I.eraseFromParent();
329 return 0; // Don't do anything with FI
330 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000331
332 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
333 APInt &KnownOne, unsigned Depth = 0) const {
334 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
335 }
336
337 bool MaskedValueIsZero(Value *V, const APInt &Mask,
338 unsigned Depth = 0) const {
339 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
340 }
341 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
342 return llvm::ComputeNumSignBits(Op, TD, Depth);
343 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344
345 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346
347 /// SimplifyCommutative - This performs a few simplifications for
348 /// commutative operators.
349 bool SimplifyCommutative(BinaryOperator &I);
350
351 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
352 /// most-complex to least-complex order.
353 bool SimplifyCompare(CmpInst &I);
354
Chris Lattner676c78e2009-01-31 08:15:18 +0000355 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
356 /// based on the demanded bits.
357 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
358 APInt& KnownZero, APInt& KnownOne,
359 unsigned Depth);
360 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000362 unsigned Depth=0);
363
364 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
365 /// SimplifyDemandedBits knows about. See if the instruction has any
366 /// properties that allow us to simplify its operands.
367 bool SimplifyDemandedInstructionBits(Instruction &Inst);
368
Evan Cheng63295ab2009-02-03 10:05:09 +0000369 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
370 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371
372 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
373 // PHI node as operand #0, see if we can fold the instruction into the PHI
374 // (which is only possible if all operands to the PHI are constants).
375 Instruction *FoldOpIntoPhi(Instruction &I);
376
377 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
378 // operator and they all are only used by the PHI, PHI together their
379 // inputs, and do the operation once, to the result of the PHI.
380 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
381 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000382 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
383
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384
385 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
386 ConstantInt *AndRHS, BinaryOperator &TheAnd);
387
388 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
389 bool isSub, Instruction &I);
390 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
391 bool isSigned, bool Inside, Instruction &IB);
392 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
393 Instruction *MatchBSwap(BinaryOperator &I);
394 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000395 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000396 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000397
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000398
399 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000400
Dan Gohman8fd520a2009-06-15 22:12:54 +0000401 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000402 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000403 unsigned GetOrEnforceKnownAlignment(Value *V,
404 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000405
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000406 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000407}
408
Dan Gohman089efff2008-05-13 00:00:25 +0000409char InstCombiner::ID = 0;
410static RegisterPass<InstCombiner>
411X("instcombine", "Combine redundant instructions");
412
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000413// getComplexity: Assign a complexity or rank value to LLVM Values...
414// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson15b39322009-07-13 04:09:18 +0000415static unsigned getComplexity(LLVMContext *Context, Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000416 if (isa<Instruction>(V)) {
Owen Anderson76f49252009-07-13 22:18:28 +0000417 if (BinaryOperator::isNeg(V) ||
418 BinaryOperator::isFNeg(V) ||
Dan Gohman7ce405e2009-06-04 22:49:04 +0000419 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420 return 3;
421 return 4;
422 }
423 if (isa<Argument>(V)) return 3;
424 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
425}
426
427// isOnlyUse - Return true if this instruction will be deleted if we stop using
428// it.
429static bool isOnlyUse(Value *V) {
430 return V->hasOneUse() || isa<Constant>(V);
431}
432
433// getPromotedType - Return the specified type promoted as it would be to pass
434// though a va_arg area...
435static const Type *getPromotedType(const Type *Ty) {
436 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
437 if (ITy->getBitWidth() < 32)
438 return Type::Int32Ty;
439 }
440 return Ty;
441}
442
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000443/// getBitCastOperand - If the specified operand is a CastInst, a constant
444/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
445/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000446static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000447 if (Operator *O = dyn_cast<Operator>(V)) {
448 if (O->getOpcode() == Instruction::BitCast)
449 return O->getOperand(0);
450 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
451 if (GEP->hasAllZeroIndices())
452 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000453 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454 return 0;
455}
456
457/// This function is a wrapper around CastInst::isEliminableCastPair. It
458/// simply extracts arguments and returns what that function returns.
459static Instruction::CastOps
460isEliminableCastPair(
461 const CastInst *CI, ///< The first cast instruction
462 unsigned opcode, ///< The opcode of the second cast instruction
463 const Type *DstTy, ///< The target type for the second cast instruction
464 TargetData *TD ///< The target data for pointer size
465) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000466
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
468 const Type *MidTy = CI->getType(); // B from above
469
470 // Get the opcodes of the two Cast instructions
471 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
472 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
473
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000474 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmana80e2712009-07-21 23:21:54 +0000475 DstTy,
476 TD ? TD->getIntPtrType() : 0);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000477
478 // We don't want to form an inttoptr or ptrtoint that converts to an integer
479 // type that differs from the pointer size.
480 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
481 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
482 Res = 0;
483
484 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000485}
486
487/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
488/// in any code being generated. It does not require codegen if V is simple
489/// enough or if the cast can be folded into other casts.
490static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
491 const Type *Ty, TargetData *TD) {
492 if (V->getType() == Ty || isa<Constant>(V)) return false;
493
494 // If this is another cast that can be eliminated, it isn't codegen either.
495 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000496 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 return false;
498 return true;
499}
500
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501// SimplifyCommutative - This performs a few simplifications for commutative
502// operators:
503//
504// 1. Order operands such that they are listed from right (least complex) to
505// left (most complex). This puts constants before unary operators before
506// binary operators.
507//
508// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
509// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
510//
511bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
512 bool Changed = false;
Owen Anderson15b39322009-07-13 04:09:18 +0000513 if (getComplexity(Context, I.getOperand(0)) <
514 getComplexity(Context, I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000515 Changed = !I.swapOperands();
516
517 if (!I.isAssociative()) return Changed;
518 Instruction::BinaryOps Opcode = I.getOpcode();
519 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
520 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
521 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000522 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000523 cast<Constant>(I.getOperand(1)),
524 cast<Constant>(Op->getOperand(1)));
525 I.setOperand(0, Op->getOperand(0));
526 I.setOperand(1, Folded);
527 return true;
528 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
529 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
530 isOnlyUse(Op) && isOnlyUse(Op1)) {
531 Constant *C1 = cast<Constant>(Op->getOperand(1));
532 Constant *C2 = cast<Constant>(Op1->getOperand(1));
533
534 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000535 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000536 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000537 Op1->getOperand(0),
538 Op1->getName(), &I);
539 AddToWorkList(New);
540 I.setOperand(0, New);
541 I.setOperand(1, Folded);
542 return true;
543 }
544 }
545 return Changed;
546}
547
548/// SimplifyCompare - For a CmpInst this function just orders the operands
549/// so that theyare listed from right (least complex) to left (most complex).
550/// This puts constants before unary operators before binary operators.
551bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson15b39322009-07-13 04:09:18 +0000552 if (getComplexity(Context, I.getOperand(0)) >=
553 getComplexity(Context, I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554 return false;
555 I.swapOperands();
556 // Compare instructions are not associative so there's nothing else we can do.
557 return true;
558}
559
560// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561// if the LHS is a constant zero (which is the 'negate' form).
562//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000563static inline Value *dyn_castNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000564 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565 return BinaryOperator::getNegArgument(V);
566
567 // Constants can be considered to be negated values if they can be folded.
568 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000569 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000570
571 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000573 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000574
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 return 0;
576}
577
Dan Gohman7ce405e2009-06-04 22:49:04 +0000578// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
579// instruction if the LHS is a constant negative zero (which is the 'negate'
580// form).
581//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000582static inline Value *dyn_castFNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000583 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000584 return BinaryOperator::getFNegArgument(V);
585
586 // Constants can be considered to be negated values if they can be folded.
587 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000588 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000589
590 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
591 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000592 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000593
594 return 0;
595}
596
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000597static inline Value *dyn_castNotVal(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000598 if (BinaryOperator::isNot(V))
599 return BinaryOperator::getNotArgument(V);
600
601 // Constants can be considered to be not'ed values...
602 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000603 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000604 return 0;
605}
606
607// dyn_castFoldableMul - If this value is a multiply that can be folded into
608// other computations (because it has a constant operand), return the
609// non-constant operand of the multiply, and set CST to point to the multiplier.
610// Otherwise, return null.
611//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000612static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 if (V->hasOneUse() && V->getType()->isInteger())
614 if (Instruction *I = dyn_cast<Instruction>(V)) {
615 if (I->getOpcode() == Instruction::Mul)
616 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
617 return I->getOperand(0);
618 if (I->getOpcode() == Instruction::Shl)
619 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
620 // The multiplier is really 1 << CST.
621 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
622 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000623 CST = ConstantInt::get(V->getType()->getContext(),
624 APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625 return I->getOperand(0);
626 }
627 }
628 return 0;
629}
630
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000631/// AddOne - Add one to a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000632static Constant *AddOne(Constant *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000633 return ConstantExpr::getAdd(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000634 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000635}
636/// SubOne - Subtract one from a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000637static Constant *SubOne(ConstantInt *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000638 return ConstantExpr::getSub(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000639 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000641/// MultiplyOverflows - True if the multiply can not be expressed in an int
642/// this size.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000643static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000644 uint32_t W = C1->getBitWidth();
645 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
646 if (sign) {
647 LHSExt.sext(W * 2);
648 RHSExt.sext(W * 2);
649 } else {
650 LHSExt.zext(W * 2);
651 RHSExt.zext(W * 2);
652 }
653
654 APInt MulExt = LHSExt * RHSExt;
655
656 if (sign) {
657 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
658 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
659 return MulExt.slt(Min) || MulExt.sgt(Max);
660 } else
661 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
662}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664
665/// ShrinkDemandedConstant - Check to see if the specified operand of the
666/// specified instruction is a constant integer. If so, check to see if there
667/// are any bits set in the constant that are not demanded. If so, shrink the
668/// constant and return true.
669static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000670 APInt Demanded) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671 assert(I && "No instruction?");
672 assert(OpNo < I->getNumOperands() && "Operand index too large");
673
674 // If the operand is not a constant integer, nothing to do.
675 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
676 if (!OpC) return false;
677
678 // If there are no bits set that aren't demanded, nothing to do.
679 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
680 if ((~Demanded & OpC->getValue()) == 0)
681 return false;
682
683 // This instruction is producing bits that are not demanded. Shrink the RHS.
684 Demanded &= OpC->getValue();
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000685 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686 return true;
687}
688
689// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
690// set of known zero and one bits, compute the maximum and minimum values that
691// could have the specified known zero and known one bits, returning them in
692// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000693static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694 const APInt& KnownOne,
695 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000696 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
697 KnownZero.getBitWidth() == Min.getBitWidth() &&
698 KnownZero.getBitWidth() == Max.getBitWidth() &&
699 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700 APInt UnknownBits = ~(KnownZero|KnownOne);
701
702 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
703 // bit if it is unknown.
704 Min = KnownOne;
705 Max = KnownOne|UnknownBits;
706
Dan Gohman7934d592009-04-25 17:12:48 +0000707 if (UnknownBits.isNegative()) { // Sign bit is unknown
708 Min.set(Min.getBitWidth()-1);
709 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000710 }
711}
712
713// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
714// a set of known zero and one bits, compute the maximum and minimum values that
715// could have the specified known zero and known one bits, returning them in
716// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000717static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000718 const APInt &KnownOne,
719 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000720 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
721 KnownZero.getBitWidth() == Min.getBitWidth() &&
722 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
724 APInt UnknownBits = ~(KnownZero|KnownOne);
725
726 // The minimum value is when the unknown bits are all zeros.
727 Min = KnownOne;
728 // The maximum value is when the unknown bits are all ones.
729 Max = KnownOne|UnknownBits;
730}
731
Chris Lattner676c78e2009-01-31 08:15:18 +0000732/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
733/// SimplifyDemandedBits knows about. See if the instruction has any
734/// properties that allow us to simplify its operands.
735bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000736 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000737 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
738 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
739
740 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
741 KnownZero, KnownOne, 0);
742 if (V == 0) return false;
743 if (V == &Inst) return true;
744 ReplaceInstUsesWith(Inst, V);
745 return true;
746}
747
748/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
749/// specified instruction operand if possible, updating it in place. It returns
750/// true if it made any change and false otherwise.
751bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
752 APInt &KnownZero, APInt &KnownOne,
753 unsigned Depth) {
754 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
755 KnownZero, KnownOne, Depth);
756 if (NewVal == 0) return false;
757 U.set(NewVal);
758 return true;
759}
760
761
762/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
763/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000764/// that only the bits set in DemandedMask of the result of V are ever used
765/// downstream. Consequently, depending on the mask and V, it may be possible
766/// to replace V with a constant or one of its operands. In such cases, this
767/// function does the replacement and returns true. In all other cases, it
768/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000769/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770/// to be zero in the expression. These are provided to potentially allow the
771/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
772/// the expression. KnownOne and KnownZero always follow the invariant that
773/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
774/// the bits in KnownOne and KnownZero may only be accurate for those bits set
775/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
776/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000777///
778/// This returns null if it did not change anything and it permits no
779/// simplification. This returns V itself if it did some simplification of V's
780/// operands based on the information about what bits are demanded. This returns
781/// some other non-null value if it found out that V is equal to another value
782/// in the context where the specified bits are demanded, but not for all users.
783Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
784 APInt &KnownZero, APInt &KnownOne,
785 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786 assert(V != 0 && "Null pointer of Value???");
787 assert(Depth <= 6 && "Limit Search Depth");
788 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000789 const Type *VTy = V->getType();
790 assert((TD || !isa<PointerType>(VTy)) &&
791 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000792 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
793 (!VTy->isIntOrIntVector() ||
794 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000795 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000796 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000797 "Value *V, DemandedMask, KnownZero and KnownOne "
798 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000799 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
800 // We know all of the bits for a constant!
801 KnownOne = CI->getValue() & DemandedMask;
802 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000803 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804 }
Dan Gohman7934d592009-04-25 17:12:48 +0000805 if (isa<ConstantPointerNull>(V)) {
806 // We know all of the bits for a constant!
807 KnownOne.clear();
808 KnownZero = DemandedMask;
809 return 0;
810 }
811
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000812 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000813 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000814 if (DemandedMask == 0) { // Not demanding any bits from V.
815 if (isa<UndefValue>(V))
816 return 0;
Owen Andersonb99ecca2009-07-30 23:03:37 +0000817 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000818 }
819
Chris Lattner08817332009-01-31 08:24:16 +0000820 if (Depth == 6) // Limit search depth.
821 return 0;
822
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000823 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
824 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
825
Dan Gohman7934d592009-04-25 17:12:48 +0000826 Instruction *I = dyn_cast<Instruction>(V);
827 if (!I) {
828 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
829 return 0; // Only analyze instructions.
830 }
831
Chris Lattner08817332009-01-31 08:24:16 +0000832 // If there are multiple uses of this value and we aren't at the root, then
833 // we can't do any simplifications of the operands, because DemandedMask
834 // only reflects the bits demanded by *one* of the users.
835 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000836 // Despite the fact that we can't simplify this instruction in all User's
837 // context, we can at least compute the knownzero/knownone bits, and we can
838 // do simplifications that apply to *just* the one user if we know that
839 // this instruction has a simpler value in that context.
840 if (I->getOpcode() == Instruction::And) {
841 // If either the LHS or the RHS are Zero, the result is zero.
842 ComputeMaskedBits(I->getOperand(1), DemandedMask,
843 RHSKnownZero, RHSKnownOne, Depth+1);
844 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
845 LHSKnownZero, LHSKnownOne, Depth+1);
846
847 // If all of the demanded bits are known 1 on one side, return the other.
848 // These bits cannot contribute to the result of the 'and' in this
849 // context.
850 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
851 (DemandedMask & ~LHSKnownZero))
852 return I->getOperand(0);
853 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
854 (DemandedMask & ~RHSKnownZero))
855 return I->getOperand(1);
856
857 // If all of the demanded bits in the inputs are known zeros, return zero.
858 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000859 return Constant::getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000860
861 } else if (I->getOpcode() == Instruction::Or) {
862 // We can simplify (X|Y) -> X or Y in the user's context if we know that
863 // only bits from X or Y are demanded.
864
865 // If either the LHS or the RHS are One, the result is One.
866 ComputeMaskedBits(I->getOperand(1), DemandedMask,
867 RHSKnownZero, RHSKnownOne, Depth+1);
868 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
869 LHSKnownZero, LHSKnownOne, Depth+1);
870
871 // If all of the demanded bits are known zero on one side, return the
872 // other. These bits cannot contribute to the result of the 'or' in this
873 // context.
874 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
875 (DemandedMask & ~LHSKnownOne))
876 return I->getOperand(0);
877 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
878 (DemandedMask & ~RHSKnownOne))
879 return I->getOperand(1);
880
881 // If all of the potentially set bits on one side are known to be set on
882 // the other side, just use the 'other' side.
883 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
884 (DemandedMask & (~RHSKnownZero)))
885 return I->getOperand(0);
886 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
887 (DemandedMask & (~LHSKnownZero)))
888 return I->getOperand(1);
889 }
890
Chris Lattner08817332009-01-31 08:24:16 +0000891 // Compute the KnownZero/KnownOne bits to simplify things downstream.
892 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
893 return 0;
894 }
895
896 // If this is the root being simplified, allow it to have multiple uses,
897 // just set the DemandedMask to all bits so that we can try to simplify the
898 // operands. This allows visitTruncInst (for example) to simplify the
899 // operand of a trunc without duplicating all the logic below.
900 if (Depth == 0 && !V->hasOneUse())
901 DemandedMask = APInt::getAllOnesValue(BitWidth);
902
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000904 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000905 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000906 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000907 case Instruction::And:
908 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000909 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
910 RHSKnownZero, RHSKnownOne, Depth+1) ||
911 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000913 return I;
914 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
915 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916
917 // If all of the demanded bits are known 1 on one side, return the other.
918 // These bits cannot contribute to the result of the 'and'.
919 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
920 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000921 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000922 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
923 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000924 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000925
926 // If all of the demanded bits in the inputs are known zeros, return zero.
927 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000928 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929
930 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000931 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000932 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000933
934 // Output known-1 bits are only known if set in both the LHS & RHS.
935 RHSKnownOne &= LHSKnownOne;
936 // Output known-0 are known to be clear if zero in either the LHS | RHS.
937 RHSKnownZero |= LHSKnownZero;
938 break;
939 case Instruction::Or:
940 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +0000941 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
942 RHSKnownZero, RHSKnownOne, Depth+1) ||
943 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000944 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000945 return I;
946 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
947 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948
949 // If all of the demanded bits are known zero on one side, return the other.
950 // These bits cannot contribute to the result of the 'or'.
951 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
952 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000953 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000954 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
955 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000956 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000957
958 // If all of the potentially set bits on one side are known to be set on
959 // the other side, just use the 'other' side.
960 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
961 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000962 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000963 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
964 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000965 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966
967 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000968 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +0000969 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000970
971 // Output known-0 bits are only known if clear in both the LHS & RHS.
972 RHSKnownZero &= LHSKnownZero;
973 // Output known-1 are known to be set if set in either the LHS | RHS.
974 RHSKnownOne |= LHSKnownOne;
975 break;
976 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +0000977 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
978 RHSKnownZero, RHSKnownOne, Depth+1) ||
979 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000980 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000981 return I;
982 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
983 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000984
985 // If all of the demanded bits are known zero on one side, return the other.
986 // These bits cannot contribute to the result of the 'xor'.
987 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000988 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000990 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991
992 // Output known-0 bits are known if clear or set in both the LHS & RHS.
993 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
994 (RHSKnownOne & LHSKnownOne);
995 // Output known-1 are known to be set if set in only one of the LHS, RHS.
996 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
997 (RHSKnownOne & LHSKnownZero);
998
999 // If all of the demanded bits are known to be zero on one side or the
1000 // other, turn this into an *inclusive* or.
1001 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1002 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1003 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001004 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001006 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001007 }
1008
1009 // If all of the demanded bits on one side are known, and all of the set
1010 // bits on that side are also known to be set on the other side, turn this
1011 // into an AND, as we know the bits will be cleared.
1012 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1013 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1014 // all known
1015 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohmancf2c9982009-08-03 22:07:33 +00001016 Constant *AndC = Constant::getIntegerValue(VTy,
1017 ~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001018 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001019 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001020 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021 }
1022 }
1023
1024 // If the RHS is a constant, see if we can simplify it.
1025 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001026 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001027 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028
1029 RHSKnownZero = KnownZeroOut;
1030 RHSKnownOne = KnownOneOut;
1031 break;
1032 }
1033 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001034 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1035 RHSKnownZero, RHSKnownOne, Depth+1) ||
1036 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001037 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001038 return I;
1039 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1040 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041
1042 // If the operands are constants, see if we can simplify them.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001043 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1044 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001045 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046
1047 // Only known if known in both the LHS and RHS.
1048 RHSKnownOne &= LHSKnownOne;
1049 RHSKnownZero &= LHSKnownZero;
1050 break;
1051 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001052 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053 DemandedMask.zext(truncBf);
1054 RHSKnownZero.zext(truncBf);
1055 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001056 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001058 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 DemandedMask.trunc(BitWidth);
1060 RHSKnownZero.trunc(BitWidth);
1061 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001062 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001063 break;
1064 }
1065 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001066 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001067 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001068
1069 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1070 if (const VectorType *SrcVTy =
1071 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1072 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1073 // Don't touch a bitcast between vectors of different element counts.
1074 return false;
1075 } else
1076 // Don't touch a scalar-to-vector bitcast.
1077 return false;
1078 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1079 // Don't touch a vector-to-scalar bitcast.
1080 return false;
1081
Chris Lattner676c78e2009-01-31 08:15:18 +00001082 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001083 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001084 return I;
1085 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086 break;
1087 case Instruction::ZExt: {
1088 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001089 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090
1091 DemandedMask.trunc(SrcBitWidth);
1092 RHSKnownZero.trunc(SrcBitWidth);
1093 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001094 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001095 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001096 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 DemandedMask.zext(BitWidth);
1098 RHSKnownZero.zext(BitWidth);
1099 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001100 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001101 // The top bits are known to be zero.
1102 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1103 break;
1104 }
1105 case Instruction::SExt: {
1106 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001107 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108
1109 APInt InputDemandedBits = DemandedMask &
1110 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1111
1112 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1113 // If any of the sign extended bits are demanded, we know that the sign
1114 // bit is demanded.
1115 if ((NewBits & DemandedMask) != 0)
1116 InputDemandedBits.set(SrcBitWidth-1);
1117
1118 InputDemandedBits.trunc(SrcBitWidth);
1119 RHSKnownZero.trunc(SrcBitWidth);
1120 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001121 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001122 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001123 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124 InputDemandedBits.zext(BitWidth);
1125 RHSKnownZero.zext(BitWidth);
1126 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001127 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128
1129 // If the sign bit of the input is known set or clear, then we know the
1130 // top bits of the result.
1131
1132 // If the input sign bit is known zero, or if the NewBits are not demanded
1133 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001134 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001136 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1137 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1139 RHSKnownOne |= NewBits;
1140 }
1141 break;
1142 }
1143 case Instruction::Add: {
1144 // Figure out what the input bits are. If the top bits of the and result
1145 // are not demanded, then the add doesn't demand them from its input
1146 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001147 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148
1149 // If there is a constant on the RHS, there are a variety of xformations
1150 // we can do.
1151 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1152 // If null, this should be simplified elsewhere. Some of the xforms here
1153 // won't work if the RHS is zero.
1154 if (RHS->isZero())
1155 break;
1156
1157 // If the top bit of the output is demanded, demand everything from the
1158 // input. Otherwise, we demand all the input bits except NLZ top bits.
1159 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1160
1161 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001162 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001164 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165
1166 // If the RHS of the add has bits set that can't affect the input, reduce
1167 // the constant.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001168 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001169 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001170
1171 // Avoid excess work.
1172 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1173 break;
1174
1175 // Turn it into OR if input bits are zero.
1176 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1177 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001178 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001179 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001180 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001181 }
1182
1183 // We can say something about the output known-zero and known-one bits,
1184 // depending on potential carries from the input constant and the
1185 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1186 // bits set and the RHS constant is 0x01001, then we know we have a known
1187 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1188
1189 // To compute this, we first compute the potential carry bits. These are
1190 // the bits which may be modified. I'm not aware of a better way to do
1191 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001192 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001193 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1194
1195 // Now that we know which bits have carries, compute the known-1/0 sets.
1196
1197 // Bits are known one if they are known zero in one operand and one in the
1198 // other, and there is no input carry.
1199 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1200 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1201
1202 // Bits are known zero if they are known zero in both operands and there
1203 // is no input carry.
1204 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1205 } else {
1206 // If the high-bits of this ADD are not demanded, then it does not demand
1207 // the high bits of its LHS or RHS.
1208 if (DemandedMask[BitWidth-1] == 0) {
1209 // Right fill the mask of bits for this ADD to demand the most
1210 // significant bit and all those below it.
1211 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001212 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1213 LHSKnownZero, LHSKnownOne, Depth+1) ||
1214 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001215 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001216 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001217 }
1218 }
1219 break;
1220 }
1221 case Instruction::Sub:
1222 // If the high-bits of this SUB are not demanded, then it does not demand
1223 // the high bits of its LHS or RHS.
1224 if (DemandedMask[BitWidth-1] == 0) {
1225 // Right fill the mask of bits for this SUB to demand the most
1226 // significant bit and all those below it.
1227 uint32_t NLZ = DemandedMask.countLeadingZeros();
1228 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001229 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1230 LHSKnownZero, LHSKnownOne, Depth+1) ||
1231 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001232 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001233 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001234 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001235 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1236 // the known zeros and ones.
1237 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001238 break;
1239 case Instruction::Shl:
1240 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1241 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1242 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001243 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001244 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001245 return I;
1246 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001247 RHSKnownZero <<= ShiftAmt;
1248 RHSKnownOne <<= ShiftAmt;
1249 // low bits known zero.
1250 if (ShiftAmt)
1251 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1252 }
1253 break;
1254 case Instruction::LShr:
1255 // For a logical shift right
1256 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1257 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1258
1259 // Unsigned shift right.
1260 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001261 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001262 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001263 return I;
1264 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1266 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1267 if (ShiftAmt) {
1268 // Compute the new bits that are at the top now.
1269 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1270 RHSKnownZero |= HighBits; // high bits known zero.
1271 }
1272 }
1273 break;
1274 case Instruction::AShr:
1275 // If this is an arithmetic shift right and only the low-bit is set, we can
1276 // always convert this into a logical shr, even if the shift amount is
1277 // variable. The low bit of the shift cannot be an input sign bit unless
1278 // the shift amount is >= the size of the datatype, which is undefined.
1279 if (DemandedMask == 1) {
1280 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001281 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001282 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001283 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284 }
1285
1286 // If the sign bit is the only bit demanded by this ashr, then there is no
1287 // need to do it, the shift doesn't change the high bit.
1288 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001289 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001290
1291 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1292 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1293
1294 // Signed shift right.
1295 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1296 // If any of the "high bits" are demanded, we should set the sign bit as
1297 // demanded.
1298 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1299 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001300 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001301 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001302 return I;
1303 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001304 // Compute the new bits that are at the top now.
1305 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1306 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1307 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1308
1309 // Handle the sign bits.
1310 APInt SignBit(APInt::getSignBit(BitWidth));
1311 // Adjust to where it is now in the mask.
1312 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1313
1314 // If the input sign bit is known to be zero, or if none of the top bits
1315 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001316 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001317 (HighBits & ~DemandedMask) == HighBits) {
1318 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001319 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001320 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001321 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1323 RHSKnownOne |= HighBits;
1324 }
1325 }
1326 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001327 case Instruction::SRem:
1328 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001329 APInt RA = Rem->getValue().abs();
1330 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001331 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001332 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001333
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001334 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001335 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001336 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001337 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001338 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001339
1340 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1341 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001342
1343 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001344
Chris Lattner676c78e2009-01-31 08:15:18 +00001345 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001346 }
1347 }
1348 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001349 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001350 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1351 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001352 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1353 KnownZero2, KnownOne2, Depth+1) ||
1354 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001355 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001356 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001357
Chris Lattneree5417c2009-01-21 18:09:24 +00001358 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001359 Leaders = std::max(Leaders,
1360 KnownZero2.countLeadingOnes());
1361 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001362 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363 }
Chris Lattner989ba312008-06-18 04:33:20 +00001364 case Instruction::Call:
1365 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1366 switch (II->getIntrinsicID()) {
1367 default: break;
1368 case Intrinsic::bswap: {
1369 // If the only bits demanded come from one byte of the bswap result,
1370 // just shift the input byte into position to eliminate the bswap.
1371 unsigned NLZ = DemandedMask.countLeadingZeros();
1372 unsigned NTZ = DemandedMask.countTrailingZeros();
1373
1374 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1375 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1376 // have 14 leading zeros, round to 8.
1377 NLZ &= ~7;
1378 NTZ &= ~7;
1379 // If we need exactly one byte, we can do this transformation.
1380 if (BitWidth-NLZ-NTZ == 8) {
1381 unsigned ResultBit = NTZ;
1382 unsigned InputBit = BitWidth-NTZ-8;
1383
1384 // Replace this with either a left or right shift to get the byte into
1385 // the right place.
1386 Instruction *NewVal;
1387 if (InputBit > ResultBit)
1388 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001389 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001390 else
1391 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001392 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001393 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001394 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001395 }
1396
1397 // TODO: Could compute known zero/one bits based on the input.
1398 break;
1399 }
1400 }
1401 }
Chris Lattner4946e222008-06-18 18:11:55 +00001402 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001403 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001404 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001405
1406 // If the client is only demanding bits that we know, return the known
1407 // constant.
Dan Gohmancf2c9982009-08-03 22:07:33 +00001408 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1409 return Constant::getIntegerValue(VTy, RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001410 return false;
1411}
1412
1413
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001414/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001415/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001416/// actually used by the caller. This method analyzes which elements of the
1417/// operand are undef and returns that information in UndefElts.
1418///
1419/// If the information about demanded elements can be used to simplify the
1420/// operation, the operation is simplified, then the resultant value is
1421/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001422Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1423 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001424 unsigned Depth) {
1425 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001426 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001427 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001428
1429 if (isa<UndefValue>(V)) {
1430 // If the entire vector is undefined, just return this info.
1431 UndefElts = EltMask;
1432 return 0;
1433 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1434 UndefElts = EltMask;
Owen Andersonb99ecca2009-07-30 23:03:37 +00001435 return UndefValue::get(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001436 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001437
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001438 UndefElts = 0;
1439 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1440 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb99ecca2009-07-30 23:03:37 +00001441 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001442
1443 std::vector<Constant*> Elts;
1444 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001445 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001446 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001447 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001448 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1449 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001450 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001451 } else { // Otherwise, defined.
1452 Elts.push_back(CP->getOperand(i));
1453 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001454
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455 // If we changed the constant, return it.
Owen Anderson2f422e02009-07-28 21:19:26 +00001456 Constant *NewCP = ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001457 return NewCP != CP ? NewCP : 0;
1458 } else if (isa<ConstantAggregateZero>(V)) {
1459 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1460 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001461
1462 // Check if this is identity. If so, return 0 since we are not simplifying
1463 // anything.
1464 if (DemandedElts == ((1ULL << VWidth) -1))
1465 return 0;
1466
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001467 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonaac28372009-07-31 20:28:14 +00001468 Constant *Zero = Constant::getNullValue(EltTy);
Owen Andersonb99ecca2009-07-30 23:03:37 +00001469 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001470 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001471 for (unsigned i = 0; i != VWidth; ++i) {
1472 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1473 Elts.push_back(Elt);
1474 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001475 UndefElts = DemandedElts ^ EltMask;
Owen Anderson2f422e02009-07-28 21:19:26 +00001476 return ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001477 }
1478
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001479 // Limit search depth.
1480 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001481 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001482
1483 // If multiple users are using the root value, procede with
1484 // simplification conservatively assuming that all elements
1485 // are needed.
1486 if (!V->hasOneUse()) {
1487 // Quit if we find multiple users of a non-root value though.
1488 // They'll be handled when it's their turn to be visited by
1489 // the main instcombine process.
1490 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001491 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001492 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001493
1494 // Conservatively assume that all elements are needed.
1495 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001496 }
1497
1498 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001499 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001500
1501 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001502 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001503 Value *TmpV;
1504 switch (I->getOpcode()) {
1505 default: break;
1506
1507 case Instruction::InsertElement: {
1508 // If this is a variable index, we don't know which element it overwrites.
1509 // demand exactly the same input as we produce.
1510 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1511 if (Idx == 0) {
1512 // Note that we can't propagate undef elt info, because we don't know
1513 // which elt is getting updated.
1514 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1515 UndefElts2, Depth+1);
1516 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1517 break;
1518 }
1519
1520 // If this is inserting an element that isn't demanded, remove this
1521 // insertelement.
1522 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng63295ab2009-02-03 10:05:09 +00001523 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001524 return AddSoonDeadInstToWorklist(*I, 0);
1525
1526 // Otherwise, the element inserted overwrites whatever was there, so the
1527 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001528 APInt DemandedElts2 = DemandedElts;
1529 DemandedElts2.clear(IdxNo);
1530 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001531 UndefElts, Depth+1);
1532 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1533
1534 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001535 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001536 break;
1537 }
1538 case Instruction::ShuffleVector: {
1539 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001540 uint64_t LHSVWidth =
1541 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001542 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001543 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001544 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001545 unsigned MaskVal = Shuffle->getMaskValue(i);
1546 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001547 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001548 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001549 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001550 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001551 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001552 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001553 }
1554 }
1555 }
1556
Nate Begemanb4d176f2009-02-11 22:36:25 +00001557 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001558 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001559 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001560 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1561
Nate Begemanb4d176f2009-02-11 22:36:25 +00001562 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001563 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1564 UndefElts3, Depth+1);
1565 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1566
1567 bool NewUndefElts = false;
1568 for (unsigned i = 0; i < VWidth; i++) {
1569 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001570 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001571 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001572 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001573 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001574 NewUndefElts = true;
1575 UndefElts.set(i);
1576 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001577 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001578 if (UndefElts3[MaskVal - LHSVWidth]) {
1579 NewUndefElts = true;
1580 UndefElts.set(i);
1581 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001582 }
1583 }
1584
1585 if (NewUndefElts) {
1586 // Add additional discovered undefs.
1587 std::vector<Constant*> Elts;
1588 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001589 if (UndefElts[i])
Owen Andersonb99ecca2009-07-30 23:03:37 +00001590 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001591 else
Owen Andersoneacb44d2009-07-24 23:12:02 +00001592 Elts.push_back(ConstantInt::get(Type::Int32Ty,
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001593 Shuffle->getMaskValue(i)));
1594 }
Owen Anderson2f422e02009-07-28 21:19:26 +00001595 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001596 MadeChange = true;
1597 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001598 break;
1599 }
1600 case Instruction::BitCast: {
1601 // Vector->vector casts only.
1602 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1603 if (!VTy) break;
1604 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001605 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001606 unsigned Ratio;
1607
1608 if (VWidth == InVWidth) {
1609 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1610 // elements as are demanded of us.
1611 Ratio = 1;
1612 InputDemandedElts = DemandedElts;
1613 } else if (VWidth > InVWidth) {
1614 // Untested so far.
1615 break;
1616
1617 // If there are more elements in the result than there are in the source,
1618 // then an input element is live if any of the corresponding output
1619 // elements are live.
1620 Ratio = VWidth/InVWidth;
1621 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001622 if (DemandedElts[OutIdx])
1623 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001624 }
1625 } else {
1626 // Untested so far.
1627 break;
1628
1629 // If there are more elements in the source than there are in the result,
1630 // then an input element is live if the corresponding output element is
1631 // live.
1632 Ratio = InVWidth/VWidth;
1633 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001634 if (DemandedElts[InIdx/Ratio])
1635 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001636 }
1637
1638 // div/rem demand all inputs, because they don't want divide by zero.
1639 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1640 UndefElts2, Depth+1);
1641 if (TmpV) {
1642 I->setOperand(0, TmpV);
1643 MadeChange = true;
1644 }
1645
1646 UndefElts = UndefElts2;
1647 if (VWidth > InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001648 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001649 // If there are more elements in the result than there are in the source,
1650 // then an output element is undef if the corresponding input element is
1651 // undef.
1652 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001653 if (UndefElts2[OutIdx/Ratio])
1654 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001655 } else if (VWidth < InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001656 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001657 // If there are more elements in the source than there are in the result,
1658 // then a result element is undef if all of the corresponding input
1659 // elements are undef.
1660 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1661 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001662 if (!UndefElts2[InIdx]) // Not undef?
1663 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001664 }
1665 break;
1666 }
1667 case Instruction::And:
1668 case Instruction::Or:
1669 case Instruction::Xor:
1670 case Instruction::Add:
1671 case Instruction::Sub:
1672 case Instruction::Mul:
1673 // div/rem demand all inputs, because they don't want divide by zero.
1674 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1675 UndefElts, Depth+1);
1676 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1677 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1678 UndefElts2, Depth+1);
1679 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1680
1681 // Output elements are undefined if both are undefined. Consider things
1682 // like undef&0. The result is known zero, not undef.
1683 UndefElts &= UndefElts2;
1684 break;
1685
1686 case Instruction::Call: {
1687 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1688 if (!II) break;
1689 switch (II->getIntrinsicID()) {
1690 default: break;
1691
1692 // Binary vector operations that work column-wise. A dest element is a
1693 // function of the corresponding input elements from the two inputs.
1694 case Intrinsic::x86_sse_sub_ss:
1695 case Intrinsic::x86_sse_mul_ss:
1696 case Intrinsic::x86_sse_min_ss:
1697 case Intrinsic::x86_sse_max_ss:
1698 case Intrinsic::x86_sse2_sub_sd:
1699 case Intrinsic::x86_sse2_mul_sd:
1700 case Intrinsic::x86_sse2_min_sd:
1701 case Intrinsic::x86_sse2_max_sd:
1702 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1703 UndefElts, Depth+1);
1704 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1705 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1706 UndefElts2, Depth+1);
1707 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1708
1709 // If only the low elt is demanded and this is a scalarizable intrinsic,
1710 // scalarize it now.
1711 if (DemandedElts == 1) {
1712 switch (II->getIntrinsicID()) {
1713 default: break;
1714 case Intrinsic::x86_sse_sub_ss:
1715 case Intrinsic::x86_sse_mul_ss:
1716 case Intrinsic::x86_sse2_sub_sd:
1717 case Intrinsic::x86_sse2_mul_sd:
1718 // TODO: Lower MIN/MAX/ABS/etc
1719 Value *LHS = II->getOperand(1);
1720 Value *RHS = II->getOperand(2);
1721 // Extract the element as scalars.
Eric Christopher1ba36872009-07-25 02:28:41 +00001722 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Andersoneacb44d2009-07-24 23:12:02 +00001723 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Eric Christopher1ba36872009-07-25 02:28:41 +00001724 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Andersoneacb44d2009-07-24 23:12:02 +00001725 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001726
1727 switch (II->getIntrinsicID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001728 default: llvm_unreachable("Case stmts out of sync!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001729 case Intrinsic::x86_sse_sub_ss:
1730 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001731 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001732 II->getName()), *II);
1733 break;
1734 case Intrinsic::x86_sse_mul_ss:
1735 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001736 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001737 II->getName()), *II);
1738 break;
1739 }
1740
1741 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001742 InsertElementInst::Create(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001743 UndefValue::get(II->getType()), TmpV,
Owen Andersoneacb44d2009-07-24 23:12:02 +00001744 ConstantInt::get(Type::Int32Ty, 0U, false), II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001745 InsertNewInstBefore(New, *II);
1746 AddSoonDeadInstToWorklist(*II, 0);
1747 return New;
1748 }
1749 }
1750
1751 // Output elements are undefined if both are undefined. Consider things
1752 // like undef&0. The result is known zero, not undef.
1753 UndefElts &= UndefElts2;
1754 break;
1755 }
1756 break;
1757 }
1758 }
1759 return MadeChange ? I : 0;
1760}
1761
Dan Gohman5d56fd42008-05-19 22:14:15 +00001762
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001763/// AssociativeOpt - Perform an optimization on an associative operator. This
1764/// function is designed to check a chain of associative operators for a
1765/// potential to apply a certain optimization. Since the optimization may be
1766/// applicable if the expression was reassociated, this checks the chain, then
1767/// reassociates the expression as necessary to expose the optimization
1768/// opportunity. This makes use of a special Functor, which must define
1769/// 'shouldApply' and 'apply' methods.
1770///
1771template<typename Functor>
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001772static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001773 unsigned Opcode = Root.getOpcode();
1774 Value *LHS = Root.getOperand(0);
1775
1776 // Quick check, see if the immediate LHS matches...
1777 if (F.shouldApply(LHS))
1778 return F.apply(Root);
1779
1780 // Otherwise, if the LHS is not of the same opcode as the root, return.
1781 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1782 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1783 // Should we apply this transform to the RHS?
1784 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1785
1786 // If not to the RHS, check to see if we should apply to the LHS...
1787 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1788 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1789 ShouldApply = true;
1790 }
1791
1792 // If the functor wants to apply the optimization to the RHS of LHSI,
1793 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1794 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001795 // Now all of the instructions are in the current basic block, go ahead
1796 // and perform the reassociation.
1797 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1798
1799 // First move the selected RHS to the LHS of the root...
1800 Root.setOperand(0, LHSI->getOperand(1));
1801
1802 // Make what used to be the LHS of the root be the user of the root...
1803 Value *ExtraOperand = TmpLHSI->getOperand(1);
1804 if (&Root == TmpLHSI) {
Owen Andersonaac28372009-07-31 20:28:14 +00001805 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001806 return 0;
1807 }
1808 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1809 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001810 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001811 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001812 ARI = Root;
1813
1814 // Now propagate the ExtraOperand down the chain of instructions until we
1815 // get to LHSI.
1816 while (TmpLHSI != LHSI) {
1817 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1818 // Move the instruction to immediately before the chain we are
1819 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001820 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001821 ARI = NextLHSI;
1822
1823 Value *NextOp = NextLHSI->getOperand(1);
1824 NextLHSI->setOperand(1, ExtraOperand);
1825 TmpLHSI = NextLHSI;
1826 ExtraOperand = NextOp;
1827 }
1828
1829 // Now that the instructions are reassociated, have the functor perform
1830 // the transformation...
1831 return F.apply(Root);
1832 }
1833
1834 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1835 }
1836 return 0;
1837}
1838
Dan Gohman089efff2008-05-13 00:00:25 +00001839namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001840
Nick Lewycky27f6c132008-05-23 04:34:58 +00001841// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001842struct AddRHS {
1843 Value *RHS;
Dan Gohmancdff2122009-08-12 16:23:25 +00001844 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001845 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1846 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001847 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001848 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001849 }
1850};
1851
1852// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1853// iff C1&C2 == 0
1854struct AddMaskingAnd {
1855 Constant *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00001856 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001857 bool shouldApply(Value *LHS) const {
1858 ConstantInt *C1;
Dan Gohmancdff2122009-08-12 16:23:25 +00001859 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Anderson02b48c32009-07-29 18:55:55 +00001860 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001861 }
1862 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001863 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001864 }
1865};
1866
Dan Gohman089efff2008-05-13 00:00:25 +00001867}
1868
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001869static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1870 InstCombiner *IC) {
Owen Anderson5349f052009-07-06 23:00:19 +00001871 LLVMContext *Context = IC->getContext();
Owen Anderson24be4c12009-07-03 00:17:18 +00001872
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001873 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedman722b4792008-11-30 21:09:11 +00001874 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001875 }
1876
1877 // Figure out if the constant is the left or the right argument.
1878 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1879 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1880
1881 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1882 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +00001883 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1884 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001885 }
1886
1887 Value *Op0 = SO, *Op1 = ConstOperand;
1888 if (!ConstIsRHS)
1889 std::swap(Op0, Op1);
1890 Instruction *New;
1891 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001892 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001893 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson6601fcd2009-07-09 23:48:35 +00001894 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1895 Op0, Op1, SO->getName()+".cmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001896 else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001897 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001898 }
1899 return IC->InsertNewInstBefore(New, I);
1900}
1901
1902// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1903// constant as the other operand, try to fold the binary operator into the
1904// select arguments. This also works for Cast instructions, which obviously do
1905// not have a second operand.
1906static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1907 InstCombiner *IC) {
1908 // Don't modify shared select instructions
1909 if (!SI->hasOneUse()) return 0;
1910 Value *TV = SI->getOperand(1);
1911 Value *FV = SI->getOperand(2);
1912
1913 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1914 // Bool selects with constant operands can be folded to logical ops.
1915 if (SI->getType() == Type::Int1Ty) return 0;
1916
1917 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1918 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1919
Gabor Greifd6da1d02008-04-06 20:25:17 +00001920 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1921 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001922 }
1923 return 0;
1924}
1925
1926
1927/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1928/// node as operand #0, see if we can fold the instruction into the PHI (which
1929/// is only possible if all operands to the PHI are constants).
1930Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1931 PHINode *PN = cast<PHINode>(I.getOperand(0));
1932 unsigned NumPHIValues = PN->getNumIncomingValues();
1933 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1934
1935 // Check to see if all of the operands of the PHI are constants. If there is
1936 // one non-constant value, remember the BB it is. If there is more than one
1937 // or if *it* is a PHI, bail out.
1938 BasicBlock *NonConstBB = 0;
1939 for (unsigned i = 0; i != NumPHIValues; ++i)
1940 if (!isa<Constant>(PN->getIncomingValue(i))) {
1941 if (NonConstBB) return 0; // More than one non-const value.
1942 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1943 NonConstBB = PN->getIncomingBlock(i);
1944
1945 // If the incoming non-constant value is in I's block, we have an infinite
1946 // loop.
1947 if (NonConstBB == I.getParent())
1948 return 0;
1949 }
1950
1951 // If there is exactly one non-constant value, we can insert a copy of the
1952 // operation in that block. However, if this is a critical edge, we would be
1953 // inserting the computation one some other paths (e.g. inside a loop). Only
1954 // do this if the pred block is unconditionally branching into the phi block.
1955 if (NonConstBB) {
1956 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1957 if (!BI || !BI->isUnconditional()) return 0;
1958 }
1959
1960 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001961 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001962 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1963 InsertNewInstBefore(NewPN, *PN);
1964 NewPN->takeName(PN);
1965
1966 // Next, add all of the operands to the PHI.
1967 if (I.getNumOperands() == 2) {
1968 Constant *C = cast<Constant>(I.getOperand(1));
1969 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001970 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001971 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1972 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +00001973 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001974 else
Owen Anderson02b48c32009-07-29 18:55:55 +00001975 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001976 } else {
1977 assert(PN->getIncomingBlock(i) == NonConstBB);
1978 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001979 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001980 PN->getIncomingValue(i), C, "phitmp",
1981 NonConstBB->getTerminator());
1982 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson6601fcd2009-07-09 23:48:35 +00001983 InV = CmpInst::Create(*Context, CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001984 CI->getPredicate(),
1985 PN->getIncomingValue(i), C, "phitmp",
1986 NonConstBB->getTerminator());
1987 else
Edwin Törökbd448e32009-07-14 16:55:14 +00001988 llvm_unreachable("Unknown binop!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001989
1990 AddToWorkList(cast<Instruction>(InV));
1991 }
1992 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1993 }
1994 } else {
1995 CastInst *CI = cast<CastInst>(&I);
1996 const Type *RetTy = CI->getType();
1997 for (unsigned i = 0; i != NumPHIValues; ++i) {
1998 Value *InV;
1999 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002000 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002001 } else {
2002 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002003 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002004 I.getType(), "phitmp",
2005 NonConstBB->getTerminator());
2006 AddToWorkList(cast<Instruction>(InV));
2007 }
2008 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2009 }
2010 }
2011 return ReplaceInstUsesWith(I, NewPN);
2012}
2013
Chris Lattner55476162008-01-29 06:52:45 +00002014
Chris Lattner3554f972008-05-20 05:46:13 +00002015/// WillNotOverflowSignedAdd - Return true if we can prove that:
2016/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2017/// This basically requires proving that the add in the original type would not
2018/// overflow to change the sign bit or have a carry out.
2019bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2020 // There are different heuristics we can use for this. Here are some simple
2021 // ones.
2022
2023 // Add has the property that adding any two 2's complement numbers can only
2024 // have one carry bit which can change a sign. As such, if LHS and RHS each
2025 // have at least two sign bits, we know that the addition of the two values will
2026 // sign extend fine.
2027 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2028 return true;
2029
2030
2031 // If one of the operands only has one non-zero bit, and if the other operand
2032 // has a known-zero bit in a more significant place than it (not including the
2033 // sign bit) the ripple may go up to and fill the zero, but won't change the
2034 // sign. For example, (X & ~4) + 1.
2035
2036 // TODO: Implement.
2037
2038 return false;
2039}
2040
Chris Lattner55476162008-01-29 06:52:45 +00002041
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002042Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2043 bool Changed = SimplifyCommutative(I);
2044 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2045
2046 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2047 // X + undef -> undef
2048 if (isa<UndefValue>(RHS))
2049 return ReplaceInstUsesWith(I, RHS);
2050
2051 // X + 0 --> X
Dan Gohman7ce405e2009-06-04 22:49:04 +00002052 if (RHSC->isNullValue())
2053 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002054
2055 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2056 // X + (signbit) --> X ^ signbit
2057 const APInt& Val = CI->getValue();
2058 uint32_t BitWidth = Val.getBitWidth();
2059 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002060 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002061
2062 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2063 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002064 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002065 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002066
Eli Friedmana21526d2009-07-13 22:27:52 +00002067 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +00002068 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Eli Friedmana21526d2009-07-13 22:27:52 +00002069 if (ZI->getSrcTy() == Type::Int1Ty)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002070 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002071 }
2072
2073 if (isa<PHINode>(LHS))
2074 if (Instruction *NV = FoldOpIntoPhi(I))
2075 return NV;
2076
2077 ConstantInt *XorRHS = 0;
2078 Value *XorLHS = 0;
2079 if (isa<ConstantInt>(RHSC) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002080 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002081 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002082 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2083
2084 uint32_t Size = TySizeBits / 2;
2085 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2086 APInt CFF80Val(-C0080Val);
2087 do {
2088 if (TySizeBits > Size) {
2089 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2090 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2091 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2092 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2093 // This is a sign extend if the top bits are known zero.
2094 if (!MaskedValueIsZero(XorLHS,
2095 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2096 Size = 0; // Not a sign ext, but can't be any others either.
2097 break;
2098 }
2099 }
2100 Size >>= 1;
2101 C0080Val = APIntOps::lshr(C0080Val, Size);
2102 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2103 } while (Size >= 1);
2104
2105 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002106 // with funny bit widths then this switch statement should be removed. It
2107 // is just here to get the size of the "middle" type back up to something
2108 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002109 const Type *MiddleType = 0;
2110 switch (Size) {
2111 default: break;
2112 case 32: MiddleType = Type::Int32Ty; break;
2113 case 16: MiddleType = Type::Int16Ty; break;
2114 case 8: MiddleType = Type::Int8Ty; break;
2115 }
2116 if (MiddleType) {
2117 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2118 InsertNewInstBefore(NewTrunc, I);
2119 return new SExtInst(NewTrunc, I.getType(), I.getName());
2120 }
2121 }
2122 }
2123
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002124 if (I.getType() == Type::Int1Ty)
2125 return BinaryOperator::CreateXor(LHS, RHS);
2126
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002127 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002128 if (I.getType()->isInteger()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00002129 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Anderson24be4c12009-07-03 00:17:18 +00002130 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002131
2132 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2133 if (RHSI->getOpcode() == Instruction::Sub)
2134 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2135 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2136 }
2137 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2138 if (LHSI->getOpcode() == Instruction::Sub)
2139 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2140 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2141 }
2142 }
2143
2144 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002145 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002146 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002147 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002148 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002149 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002150 InsertNewInstBefore(NewAdd, I);
Dan Gohmancdff2122009-08-12 16:23:25 +00002151 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002152 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002153 }
2154
Gabor Greifa645dd32008-05-16 19:29:10 +00002155 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002156 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002157
2158 // A + -B --> A - B
2159 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002160 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002161 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002162
2163
2164 ConstantInt *C2;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002165 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002166 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002167 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002168
2169 // X*C1 + X*C2 --> X * (C1+C2)
2170 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002171 if (X == dyn_castFoldableMul(RHS, C1))
Owen Anderson02b48c32009-07-29 18:55:55 +00002172 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002173 }
2174
2175 // X + X*C --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002176 if (dyn_castFoldableMul(RHS, C2) == LHS)
2177 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002178
2179 // X + ~X --> -1 since ~X = -X-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002180 if (dyn_castNotVal(LHS) == RHS ||
2181 dyn_castNotVal(RHS) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +00002182 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002183
2184
2185 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00002186 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2187 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002188 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002189
2190 // A+B --> A|B iff A and B have no bits set in common.
2191 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2192 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2193 APInt LHSKnownOne(IT->getBitWidth(), 0);
2194 APInt LHSKnownZero(IT->getBitWidth(), 0);
2195 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2196 if (LHSKnownZero != 0) {
2197 APInt RHSKnownOne(IT->getBitWidth(), 0);
2198 APInt RHSKnownZero(IT->getBitWidth(), 0);
2199 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2200
2201 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002202 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002203 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002204 }
2205 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002206
Nick Lewycky83598a72008-02-03 07:42:09 +00002207 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002208 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002209 Value *W, *X, *Y, *Z;
Dan Gohmancdff2122009-08-12 16:23:25 +00002210 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2211 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002212 if (W != Y) {
2213 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002214 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002215 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002216 std::swap(W, X);
2217 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002218 std::swap(Y, Z);
2219 std::swap(W, X);
2220 }
2221 }
2222
2223 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002224 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002225 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002226 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002227 }
2228 }
2229 }
2230
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002231 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2232 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002233 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002234 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235
2236 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002237 if (LHS->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002238 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002239 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002240 if (Anded == CRHS) {
2241 // See if all bits from the first bit set in the Add RHS up are included
2242 // in the mask. First, get the rightmost bit.
2243 const APInt& AddRHSV = CRHS->getValue();
2244
2245 // Form a mask of all bits from the lowest bit added through the top.
2246 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2247
2248 // See if the and mask includes all of these bits.
2249 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2250
2251 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2252 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002253 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002254 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002255 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002256 }
2257 }
2258 }
2259
2260 // Try to fold constant add into select arguments.
2261 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2262 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2263 return R;
2264 }
2265
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002266 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002267 {
2268 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002269 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002270 if (!SI) {
2271 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002272 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002273 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002274 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002275 Value *TV = SI->getTrueValue();
2276 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002277 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002278
2279 // Can we fold the add into the argument of the select?
2280 // We check both true and false select arguments for a matching subtract.
Dan Gohmancdff2122009-08-12 16:23:25 +00002281 if (match(FV, m_Zero()) &&
2282 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002283 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002284 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohmancdff2122009-08-12 16:23:25 +00002285 if (match(TV, m_Zero()) &&
2286 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002287 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002288 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002289 }
2290 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002291
Chris Lattner3554f972008-05-20 05:46:13 +00002292 // Check for (add (sext x), y), see if we can merge this into an
2293 // integer add followed by a sext.
2294 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2295 // (add (sext x), cst) --> (sext (add x, cst'))
2296 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2297 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002298 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002299 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002300 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002301 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2302 // Insert the new, smaller add.
2303 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2304 CI, "addconv");
2305 InsertNewInstBefore(NewAdd, I);
2306 return new SExtInst(NewAdd, I.getType());
2307 }
2308 }
2309
2310 // (add (sext x), (sext y)) --> (sext (add int x, y))
2311 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2312 // Only do this if x/y have the same type, if at last one of them has a
2313 // single use (so we don't increase the number of sexts), and if the
2314 // integer add will not overflow.
2315 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2316 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2317 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2318 RHSConv->getOperand(0))) {
2319 // Insert the new integer add.
2320 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2321 RHSConv->getOperand(0),
2322 "addconv");
2323 InsertNewInstBefore(NewAdd, I);
2324 return new SExtInst(NewAdd, I.getType());
2325 }
2326 }
2327 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002328
2329 return Changed ? &I : 0;
2330}
2331
2332Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2333 bool Changed = SimplifyCommutative(I);
2334 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2335
2336 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2337 // X + 0 --> X
2338 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +00002339 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002340 (I.getType())->getValueAPF()))
2341 return ReplaceInstUsesWith(I, LHS);
2342 }
2343
2344 if (isa<PHINode>(LHS))
2345 if (Instruction *NV = FoldOpIntoPhi(I))
2346 return NV;
2347 }
2348
2349 // -A + B --> B - A
2350 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002351 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002352 return BinaryOperator::CreateFSub(RHS, LHSV);
2353
2354 // A + -B --> A - B
2355 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002356 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002357 return BinaryOperator::CreateFSub(LHS, V);
2358
2359 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2360 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2361 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2362 return ReplaceInstUsesWith(I, LHS);
2363
Chris Lattner3554f972008-05-20 05:46:13 +00002364 // Check for (add double (sitofp x), y), see if we can merge this into an
2365 // integer add followed by a promotion.
2366 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2367 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2368 // ... if the constant fits in the integer value. This is useful for things
2369 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2370 // requires a constant pool load, and generally allows the add to be better
2371 // instcombined.
2372 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2373 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002374 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002375 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002376 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002377 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2378 // Insert the new integer add.
2379 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2380 CI, "addconv");
2381 InsertNewInstBefore(NewAdd, I);
2382 return new SIToFPInst(NewAdd, I.getType());
2383 }
2384 }
2385
2386 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2387 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2388 // Only do this if x/y have the same type, if at last one of them has a
2389 // single use (so we don't increase the number of int->fp conversions),
2390 // and if the integer add will not overflow.
2391 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2392 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2393 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2394 RHSConv->getOperand(0))) {
2395 // Insert the new integer add.
2396 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2397 RHSConv->getOperand(0),
2398 "addconv");
2399 InsertNewInstBefore(NewAdd, I);
2400 return new SIToFPInst(NewAdd, I.getType());
2401 }
2402 }
2403 }
2404
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002405 return Changed ? &I : 0;
2406}
2407
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002408Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2410
Dan Gohman7ce405e2009-06-04 22:49:04 +00002411 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002412 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002413
2414 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002415 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002416 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002417
2418 if (isa<UndefValue>(Op0))
2419 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2420 if (isa<UndefValue>(Op1))
2421 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2422
2423 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2424 // Replace (-1 - A) with (~A)...
2425 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00002426 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002427
2428 // C - ~X == X + (1+C)
2429 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002430 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002431 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002432
2433 // -(X >>u 31) -> (X >>s 31)
2434 // -(X >>s 31) -> (X >>u 31)
2435 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002436 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002437 if (SI->getOpcode() == Instruction::LShr) {
2438 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2439 // Check to see if we are shifting out everything but the sign bit.
2440 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2441 SI->getType()->getPrimitiveSizeInBits()-1) {
2442 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002443 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002444 SI->getOperand(0), CU, SI->getName());
2445 }
2446 }
2447 }
2448 else if (SI->getOpcode() == Instruction::AShr) {
2449 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2450 // Check to see if we are shifting out everything but the sign bit.
2451 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2452 SI->getType()->getPrimitiveSizeInBits()-1) {
2453 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002454 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002455 SI->getOperand(0), CU, SI->getName());
2456 }
2457 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002458 }
2459 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002460 }
2461
2462 // Try to fold constant sub into select arguments.
2463 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2464 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2465 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002466
2467 // C - zext(bool) -> bool ? C - 1 : C
2468 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2469 if (ZI->getSrcTy() == Type::Int1Ty)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002470 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002471 }
2472
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002473 if (I.getType() == Type::Int1Ty)
2474 return BinaryOperator::CreateXor(Op0, Op1);
2475
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002476 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002477 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002478 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002479 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002480 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002481 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002482 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002483 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002484 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2485 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2486 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002487 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002488 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002489 }
2490 }
2491
2492 if (Op1I->hasOneUse()) {
2493 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2494 // is not used by anyone else...
2495 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002496 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002497 // Swap the two operands of the subexpr...
2498 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2499 Op1I->setOperand(0, IIOp1);
2500 Op1I->setOperand(1, IIOp0);
2501
2502 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002503 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002504 }
2505
2506 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2507 //
2508 if (Op1I->getOpcode() == Instruction::And &&
2509 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2510 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2511
2512 Value *NewNot =
Dan Gohmancdff2122009-08-12 16:23:25 +00002513 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002514 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002515 }
2516
2517 // 0 - (X sdiv C) -> (X sdiv -C)
2518 if (Op1I->getOpcode() == Instruction::SDiv)
2519 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2520 if (CSI->isZero())
2521 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002522 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002523 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002524
2525 // X - X*C --> X * (1-C)
2526 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002527 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002528 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00002529 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002530 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002531 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002532 }
2533 }
2534 }
2535
Dan Gohman7ce405e2009-06-04 22:49:04 +00002536 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2537 if (Op0I->getOpcode() == Instruction::Add) {
2538 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2539 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2540 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2541 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2542 } else if (Op0I->getOpcode() == Instruction::Sub) {
2543 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002544 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002545 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002546 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002547 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002548
2549 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002550 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002551 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002552 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002553
2554 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002555 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00002556 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002557 }
2558 return 0;
2559}
2560
Dan Gohman7ce405e2009-06-04 22:49:04 +00002561Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2562 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2563
2564 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002565 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002566 return BinaryOperator::CreateFAdd(Op0, V);
2567
2568 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2569 if (Op1I->getOpcode() == Instruction::FAdd) {
2570 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002571 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002572 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002573 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002574 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002575 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002576 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002577 }
2578
2579 return 0;
2580}
2581
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002582/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2583/// comparison only checks the sign bit. If it only checks the sign bit, set
2584/// TrueIfSigned if the result of the comparison is true when the input value is
2585/// signed.
2586static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2587 bool &TrueIfSigned) {
2588 switch (pred) {
2589 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2590 TrueIfSigned = true;
2591 return RHS->isZero();
2592 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2593 TrueIfSigned = true;
2594 return RHS->isAllOnesValue();
2595 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2596 TrueIfSigned = false;
2597 return RHS->isAllOnesValue();
2598 case ICmpInst::ICMP_UGT:
2599 // True if LHS u> RHS and RHS == high-bit-mask - 1
2600 TrueIfSigned = true;
2601 return RHS->getValue() ==
2602 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2603 case ICmpInst::ICMP_UGE:
2604 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2605 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002606 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002607 default:
2608 return false;
2609 }
2610}
2611
2612Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2613 bool Changed = SimplifyCommutative(I);
2614 Value *Op0 = I.getOperand(0);
2615
Eli Friedmane426ded2009-07-18 09:12:15 +00002616 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002617 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002618
2619 // Simplify mul instructions with a constant RHS...
2620 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2621 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2622
2623 // ((X << C1)*C2) == (X * (C2 << C1))
2624 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2625 if (SI->getOpcode() == Instruction::Shl)
2626 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002627 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002628 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002629
2630 if (CI->isZero())
2631 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2632 if (CI->equalsInt(1)) // X * 1 == X
2633 return ReplaceInstUsesWith(I, Op0);
2634 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002635 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002636
2637 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2638 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002639 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002640 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002641 }
Chris Lattner6297fc72008-08-11 22:06:05 +00002642 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedman6e058402009-07-14 02:01:53 +00002643 if (Op1->isNullValue())
2644 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky94418732008-11-27 20:21:08 +00002645
2646 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2647 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002648 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00002649
2650 // As above, vector X*splat(1.0) -> X in all defined cases.
2651 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002652 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2653 if (CI->equalsInt(1))
2654 return ReplaceInstUsesWith(I, Op0);
2655 }
2656 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002657 }
2658
2659 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2660 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002661 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002662 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002663 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002664 Op1, "tmp");
2665 InsertNewInstBefore(Add, I);
Owen Anderson02b48c32009-07-29 18:55:55 +00002666 Value *C1C2 = ConstantExpr::getMul(Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002667 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002668 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669
2670 }
2671
2672 // Try to fold constant mul into select arguments.
2673 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2674 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2675 return R;
2676
2677 if (isa<PHINode>(Op0))
2678 if (Instruction *NV = FoldOpIntoPhi(I))
2679 return NV;
2680 }
2681
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002682 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2683 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002684 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002685
Nick Lewycky1c246402008-11-21 07:33:58 +00002686 // (X / Y) * Y = X - (X % Y)
2687 // (X / Y) * -Y = (X % Y) - X
2688 {
2689 Value *Op1 = I.getOperand(1);
2690 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2691 if (!BO ||
2692 (BO->getOpcode() != Instruction::UDiv &&
2693 BO->getOpcode() != Instruction::SDiv)) {
2694 Op1 = Op0;
2695 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2696 }
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002697 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00002698 if (BO && BO->hasOneUse() &&
2699 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2700 (BO->getOpcode() == Instruction::UDiv ||
2701 BO->getOpcode() == Instruction::SDiv)) {
2702 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2703
2704 Instruction *Rem;
2705 if (BO->getOpcode() == Instruction::UDiv)
2706 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2707 else
2708 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2709
2710 InsertNewInstBefore(Rem, I);
2711 Rem->takeName(BO);
2712
2713 if (Op1BO == Op1)
2714 return BinaryOperator::CreateSub(Op0BO, Rem);
2715 else
2716 return BinaryOperator::CreateSub(Rem, Op0BO);
2717 }
2718 }
2719
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002720 if (I.getType() == Type::Int1Ty)
2721 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2722
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002723 // If one of the operands of the multiply is a cast from a boolean value, then
2724 // we know the bool is either zero or one, so this is a 'masking' multiply.
2725 // See if we can simplify things based on how the boolean was originally
2726 // formed.
2727 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002728 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002729 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2730 BoolCast = CI;
2731 if (!BoolCast)
2732 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2733 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2734 BoolCast = CI;
2735 if (BoolCast) {
2736 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2737 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2738 const Type *SCOpTy = SCIOp0->getType();
2739 bool TIS = false;
2740
2741 // If the icmp is true iff the sign bit of X is set, then convert this
2742 // multiply into a shift/and combination.
2743 if (isa<ConstantInt>(SCIOp1) &&
2744 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2745 TIS) {
2746 // Shift the X value right to turn it into "all signbits".
Owen Andersoneacb44d2009-07-24 23:12:02 +00002747 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002748 SCOpTy->getPrimitiveSizeInBits()-1);
2749 Value *V =
2750 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002751 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002752 BoolCast->getOperand(0)->getName()+
2753 ".mask"), I);
2754
2755 // If the multiply type is not the same as the source type, sign extend
2756 // or truncate to the multiply type.
2757 if (I.getType() != V->getType()) {
2758 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2759 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2760 Instruction::CastOps opcode =
2761 (SrcBits == DstBits ? Instruction::BitCast :
2762 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2763 V = InsertCastBefore(opcode, V, I.getType(), I);
2764 }
2765
2766 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002767 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002768 }
2769 }
2770 }
2771
2772 return Changed ? &I : 0;
2773}
2774
Dan Gohman7ce405e2009-06-04 22:49:04 +00002775Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2776 bool Changed = SimplifyCommutative(I);
2777 Value *Op0 = I.getOperand(0);
2778
2779 // Simplify mul instructions with a constant RHS...
2780 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2781 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2782 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2783 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2784 if (Op1F->isExactlyValue(1.0))
2785 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2786 } else if (isa<VectorType>(Op1->getType())) {
2787 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2788 // As above, vector X*splat(1.0) -> X in all defined cases.
2789 if (Constant *Splat = Op1V->getSplatValue()) {
2790 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2791 if (F->isExactlyValue(1.0))
2792 return ReplaceInstUsesWith(I, Op0);
2793 }
2794 }
2795 }
2796
2797 // Try to fold constant mul into select arguments.
2798 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2799 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2800 return R;
2801
2802 if (isa<PHINode>(Op0))
2803 if (Instruction *NV = FoldOpIntoPhi(I))
2804 return NV;
2805 }
2806
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002807 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2808 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002809 return BinaryOperator::CreateFMul(Op0v, Op1v);
2810
2811 return Changed ? &I : 0;
2812}
2813
Chris Lattner76972db2008-07-14 00:15:52 +00002814/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2815/// instruction.
2816bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2817 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2818
2819 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2820 int NonNullOperand = -1;
2821 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2822 if (ST->isNullValue())
2823 NonNullOperand = 2;
2824 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2825 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2826 if (ST->isNullValue())
2827 NonNullOperand = 1;
2828
2829 if (NonNullOperand == -1)
2830 return false;
2831
2832 Value *SelectCond = SI->getOperand(0);
2833
2834 // Change the div/rem to use 'Y' instead of the select.
2835 I.setOperand(1, SI->getOperand(NonNullOperand));
2836
2837 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2838 // problem. However, the select, or the condition of the select may have
2839 // multiple uses. Based on our knowledge that the operand must be non-zero,
2840 // propagate the known value for the select into other uses of it, and
2841 // propagate a known value of the condition into its other users.
2842
2843 // If the select and condition only have a single use, don't bother with this,
2844 // early exit.
2845 if (SI->use_empty() && SelectCond->hasOneUse())
2846 return true;
2847
2848 // Scan the current block backward, looking for other uses of SI.
2849 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2850
2851 while (BBI != BBFront) {
2852 --BBI;
2853 // If we found a call to a function, we can't assume it will return, so
2854 // information from below it cannot be propagated above it.
2855 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2856 break;
2857
2858 // Replace uses of the select or its condition with the known values.
2859 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2860 I != E; ++I) {
2861 if (*I == SI) {
2862 *I = SI->getOperand(NonNullOperand);
2863 AddToWorkList(BBI);
2864 } else if (*I == SelectCond) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00002865 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2866 ConstantInt::getFalse(*Context);
Chris Lattner76972db2008-07-14 00:15:52 +00002867 AddToWorkList(BBI);
2868 }
2869 }
2870
2871 // If we past the instruction, quit looking for it.
2872 if (&*BBI == SI)
2873 SI = 0;
2874 if (&*BBI == SelectCond)
2875 SelectCond = 0;
2876
2877 // If we ran out of things to eliminate, break out of the loop.
2878 if (SelectCond == 0 && SI == 0)
2879 break;
2880
2881 }
2882 return true;
2883}
2884
2885
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886/// This function implements the transforms on div instructions that work
2887/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2888/// used by the visitors to those instructions.
2889/// @brief Transforms common to all three div instructions
2890Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2891 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2892
Chris Lattner653ef3c2008-02-19 06:12:18 +00002893 // undef / X -> 0 for integer.
2894 // undef / X -> undef for FP (the undef could be a snan).
2895 if (isa<UndefValue>(Op0)) {
2896 if (Op0->getType()->isFPOrFPVector())
2897 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00002898 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002899 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002900
2901 // X / undef -> undef
2902 if (isa<UndefValue>(Op1))
2903 return ReplaceInstUsesWith(I, Op1);
2904
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002905 return 0;
2906}
2907
2908/// This function implements the transforms common to both integer division
2909/// instructions (udiv and sdiv). It is called by the visitors to those integer
2910/// division instructions.
2911/// @brief Common integer divide transforms
2912Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2913 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2914
Chris Lattnercefb36c2008-05-16 02:59:42 +00002915 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002916 if (Op0 == Op1) {
2917 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00002918 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002919 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00002920 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00002921 }
2922
Owen Andersoneacb44d2009-07-24 23:12:02 +00002923 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002924 return ReplaceInstUsesWith(I, CI);
2925 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002926
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002927 if (Instruction *Common = commonDivTransforms(I))
2928 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002929
2930 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2931 // This does not apply for fdiv.
2932 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2933 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002934
2935 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2936 // div X, 1 == X
2937 if (RHS->equalsInt(1))
2938 return ReplaceInstUsesWith(I, Op0);
2939
2940 // (X / C1) / C2 -> X / (C1*C2)
2941 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2942 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2943 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002944 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002945 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00002946 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00002947 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002948 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002949 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002950 }
2951
2952 if (!RHS->isZero()) { // avoid X udiv 0
2953 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2954 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2955 return R;
2956 if (isa<PHINode>(Op0))
2957 if (Instruction *NV = FoldOpIntoPhi(I))
2958 return NV;
2959 }
2960 }
2961
2962 // 0 / X == 0, we don't need to preserve faults!
2963 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2964 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00002965 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002966
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002967 // It can't be division by zero, hence it must be division by one.
2968 if (I.getType() == Type::Int1Ty)
2969 return ReplaceInstUsesWith(I, Op0);
2970
Nick Lewycky94418732008-11-27 20:21:08 +00002971 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2972 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2973 // div X, 1 == X
2974 if (X->isOne())
2975 return ReplaceInstUsesWith(I, Op0);
2976 }
2977
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002978 return 0;
2979}
2980
2981Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2982 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2983
2984 // Handle the integer div common cases
2985 if (Instruction *Common = commonIDivTransforms(I))
2986 return Common;
2987
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002988 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00002989 // X udiv C^2 -> X >> C
2990 // Check to see if this is an unsigned division with an exact power of 2,
2991 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002992 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00002993 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002994 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00002995
2996 // X udiv C, where C >= signbit
2997 if (C->getValue().isNegative()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00002998 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
2999 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky240182a2008-11-27 22:41:10 +00003000 I);
Owen Andersonaac28372009-07-31 20:28:14 +00003001 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003002 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003003 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003004 }
3005
3006 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3007 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3008 if (RHSI->getOpcode() == Instruction::Shl &&
3009 isa<ConstantInt>(RHSI->getOperand(0))) {
3010 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3011 if (C1.isPowerOf2()) {
3012 Value *N = RHSI->getOperand(1);
3013 const Type *NTy = N->getType();
3014 if (uint32_t C2 = C1.logBase2()) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00003015 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00003016 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003017 }
Gabor Greifa645dd32008-05-16 19:29:10 +00003018 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003019 }
3020 }
3021 }
3022
3023 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3024 // where C1&C2 are powers of two.
3025 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3026 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3027 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3028 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3029 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3030 // Compute the shift amounts
3031 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3032 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003033 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003034 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003035 Op0, TC, SI->getName()+".t");
3036 TSI = InsertNewInstBefore(TSI, I);
3037
3038 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003039 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003040 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003041 Op0, FC, SI->getName()+".f");
3042 FSI = InsertNewInstBefore(FSI, I);
3043
3044 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003045 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003046 }
3047 }
3048 return 0;
3049}
3050
3051Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3052 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3053
3054 // Handle the integer div common cases
3055 if (Instruction *Common = commonIDivTransforms(I))
3056 return Common;
3057
3058 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3059 // sdiv X, -1 == -X
3060 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00003061 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00003062
3063 // sdiv X, C --> ashr X, log2(C)
3064 if (cast<SDivOperator>(&I)->isExact() &&
3065 RHS->getValue().isNonNegative() &&
3066 RHS->getValue().isPowerOf2()) {
3067 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3068 RHS->getValue().exactLogBase2());
3069 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3070 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003071 }
3072
3073 // If the sign bits of both operands are zero (i.e. we can prove they are
3074 // unsigned inputs), turn this into a udiv.
3075 if (I.getType()->isInteger()) {
3076 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003077 if (MaskedValueIsZero(Op0, Mask)) {
3078 if (MaskedValueIsZero(Op1, Mask)) {
3079 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3080 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3081 }
3082 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00003083 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00003084 ShiftedInt->getValue().isPowerOf2()) {
3085 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3086 // Safe because the only negative value (1 << Y) can take on is
3087 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3088 // the sign bit set.
3089 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3090 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003091 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003092 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003093
3094 return 0;
3095}
3096
3097Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3098 return commonDivTransforms(I);
3099}
3100
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003101/// This function implements the transforms on rem instructions that work
3102/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3103/// is used by the visitors to those instructions.
3104/// @brief Transforms common to all three rem instructions
3105Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3106 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3107
Chris Lattner653ef3c2008-02-19 06:12:18 +00003108 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3109 if (I.getType()->isFPOrFPVector())
3110 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00003111 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003112 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003113 if (isa<UndefValue>(Op1))
3114 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3115
3116 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003117 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3118 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003119
3120 return 0;
3121}
3122
3123/// This function implements the transforms common to both integer remainder
3124/// instructions (urem and srem). It is called by the visitors to those integer
3125/// remainder instructions.
3126/// @brief Common integer remainder transforms
3127Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3128 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3129
3130 if (Instruction *common = commonRemTransforms(I))
3131 return common;
3132
Dale Johannesena51f7372009-01-21 00:35:19 +00003133 // 0 % X == 0 for integer, we don't need to preserve faults!
3134 if (Constant *LHS = dyn_cast<Constant>(Op0))
3135 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00003136 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003137
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003138 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3139 // X % 0 == undef, we don't need to preserve faults!
3140 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003141 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003142
3143 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003144 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003145
3146 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3147 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3148 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3149 return R;
3150 } else if (isa<PHINode>(Op0I)) {
3151 if (Instruction *NV = FoldOpIntoPhi(I))
3152 return NV;
3153 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003154
3155 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003156 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003157 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003158 }
3159 }
3160
3161 return 0;
3162}
3163
3164Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3165 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3166
3167 if (Instruction *common = commonIRemTransforms(I))
3168 return common;
3169
3170 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3171 // X urem C^2 -> X and C
3172 // Check to see if this is an unsigned remainder with an exact power of 2,
3173 // if so, convert to a bitwise and.
3174 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3175 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003176 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003177 }
3178
3179 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3180 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3181 if (RHSI->getOpcode() == Instruction::Shl &&
3182 isa<ConstantInt>(RHSI->getOperand(0))) {
3183 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00003184 Constant *N1 = Constant::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003185 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003186 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003187 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003188 }
3189 }
3190 }
3191
3192 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3193 // where C1&C2 are powers of two.
3194 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3195 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3196 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3197 // STO == 0 and SFO == 0 handled above.
3198 if ((STO->getValue().isPowerOf2()) &&
3199 (SFO->getValue().isPowerOf2())) {
3200 Value *TrueAnd = InsertNewInstBefore(
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003201 BinaryOperator::CreateAnd(Op0, SubOne(STO),
Owen Anderson24be4c12009-07-03 00:17:18 +00003202 SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003203 Value *FalseAnd = InsertNewInstBefore(
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003204 BinaryOperator::CreateAnd(Op0, SubOne(SFO),
Owen Anderson24be4c12009-07-03 00:17:18 +00003205 SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003206 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003207 }
3208 }
3209 }
3210
3211 return 0;
3212}
3213
3214Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3215 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3216
Dan Gohmandb3dd962007-11-05 23:16:33 +00003217 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003218 if (Instruction *common = commonIRemTransforms(I))
3219 return common;
3220
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003221 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003222 if (!isa<Constant>(RHSNeg) ||
3223 (isa<ConstantInt>(RHSNeg) &&
3224 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003225 // X % -Y -> X % Y
3226 AddUsesToWorkList(I);
3227 I.setOperand(1, RHSNeg);
3228 return &I;
3229 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003230
Dan Gohmandb3dd962007-11-05 23:16:33 +00003231 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003232 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003233 if (I.getType()->isInteger()) {
3234 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3235 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3236 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003237 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003238 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003239 }
3240
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003241 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003242 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3243 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003244
Nick Lewyckyfd746832008-12-20 16:48:00 +00003245 bool hasNegative = false;
3246 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3247 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3248 if (RHS->getValue().isNegative())
3249 hasNegative = true;
3250
3251 if (hasNegative) {
3252 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003253 for (unsigned i = 0; i != VWidth; ++i) {
3254 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3255 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00003256 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003257 else
3258 Elts[i] = RHS;
3259 }
3260 }
3261
Owen Anderson2f422e02009-07-28 21:19:26 +00003262 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003263 if (NewRHSV != RHSV) {
Nick Lewycky338ecd52008-12-18 06:42:28 +00003264 AddUsesToWorkList(I);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003265 I.setOperand(1, NewRHSV);
3266 return &I;
3267 }
3268 }
3269 }
3270
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003271 return 0;
3272}
3273
3274Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3275 return commonRemTransforms(I);
3276}
3277
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003278// isOneBitSet - Return true if there is exactly one bit set in the specified
3279// constant.
3280static bool isOneBitSet(const ConstantInt *CI) {
3281 return CI->getValue().isPowerOf2();
3282}
3283
3284// isHighOnes - Return true if the constant is of the form 1+0+.
3285// This is the same as lowones(~X).
3286static bool isHighOnes(const ConstantInt *CI) {
3287 return (~CI->getValue() + 1).isPowerOf2();
3288}
3289
3290/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3291/// are carefully arranged to allow folding of expressions such as:
3292///
3293/// (A < B) | (A > B) --> (A != B)
3294///
3295/// Note that this is only valid if the first and second predicates have the
3296/// same sign. Is illegal to do: (A u< B) | (A s> B)
3297///
3298/// Three bits are used to represent the condition, as follows:
3299/// 0 A > B
3300/// 1 A == B
3301/// 2 A < B
3302///
3303/// <=> Value Definition
3304/// 000 0 Always false
3305/// 001 1 A > B
3306/// 010 2 A == B
3307/// 011 3 A >= B
3308/// 100 4 A < B
3309/// 101 5 A != B
3310/// 110 6 A <= B
3311/// 111 7 Always true
3312///
3313static unsigned getICmpCode(const ICmpInst *ICI) {
3314 switch (ICI->getPredicate()) {
3315 // False -> 0
3316 case ICmpInst::ICMP_UGT: return 1; // 001
3317 case ICmpInst::ICMP_SGT: return 1; // 001
3318 case ICmpInst::ICMP_EQ: return 2; // 010
3319 case ICmpInst::ICMP_UGE: return 3; // 011
3320 case ICmpInst::ICMP_SGE: return 3; // 011
3321 case ICmpInst::ICMP_ULT: return 4; // 100
3322 case ICmpInst::ICMP_SLT: return 4; // 100
3323 case ICmpInst::ICMP_NE: return 5; // 101
3324 case ICmpInst::ICMP_ULE: return 6; // 110
3325 case ICmpInst::ICMP_SLE: return 6; // 110
3326 // True -> 7
3327 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003328 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003329 return 0;
3330 }
3331}
3332
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003333/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3334/// predicate into a three bit mask. It also returns whether it is an ordered
3335/// predicate by reference.
3336static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3337 isOrdered = false;
3338 switch (CC) {
3339 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3340 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003341 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3342 case FCmpInst::FCMP_UGT: return 1; // 001
3343 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3344 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003345 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3346 case FCmpInst::FCMP_UGE: return 3; // 011
3347 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3348 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003349 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3350 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003351 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3352 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003353 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003354 default:
3355 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003356 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003357 return 0;
3358 }
3359}
3360
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003361/// getICmpValue - This is the complement of getICmpCode, which turns an
3362/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003363/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003364/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003365static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003366 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003367 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003368 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson4f720fa2009-07-31 17:39:07 +00003369 case 0: return ConstantInt::getFalse(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003370 case 1:
3371 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003372 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003373 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003374 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3375 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003376 case 3:
3377 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003378 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003379 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003380 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003381 case 4:
3382 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003383 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003384 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003385 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3386 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003387 case 6:
3388 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003389 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003390 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003391 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003392 case 7: return ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003393 }
3394}
3395
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003396/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3397/// opcode and two operands into either a FCmp instruction. isordered is passed
3398/// in to determine which kind of predicate to use in the new fcmp instruction.
3399static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003400 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003401 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003402 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003403 case 0:
3404 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003405 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003406 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003407 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003408 case 1:
3409 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003410 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003411 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003412 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003413 case 2:
3414 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003415 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003416 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003417 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003418 case 3:
3419 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003420 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003421 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003422 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003423 case 4:
3424 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003425 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003426 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003427 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003428 case 5:
3429 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003430 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003431 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003432 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003433 case 6:
3434 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003435 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003436 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003437 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003438 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003439 }
3440}
3441
Chris Lattner2972b822008-11-16 04:55:20 +00003442/// PredicatesFoldable - Return true if both predicates match sign or if at
3443/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003444static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3445 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattner2972b822008-11-16 04:55:20 +00003446 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3447 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003448}
3449
3450namespace {
3451// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3452struct FoldICmpLogical {
3453 InstCombiner &IC;
3454 Value *LHS, *RHS;
3455 ICmpInst::Predicate pred;
3456 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3457 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3458 pred(ICI->getPredicate()) {}
3459 bool shouldApply(Value *V) const {
3460 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3461 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003462 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3463 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003464 return false;
3465 }
3466 Instruction *apply(Instruction &Log) const {
3467 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3468 if (ICI->getOperand(0) != LHS) {
3469 assert(ICI->getOperand(1) == LHS);
3470 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3471 }
3472
3473 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3474 unsigned LHSCode = getICmpCode(ICI);
3475 unsigned RHSCode = getICmpCode(RHSICI);
3476 unsigned Code;
3477 switch (Log.getOpcode()) {
3478 case Instruction::And: Code = LHSCode & RHSCode; break;
3479 case Instruction::Or: Code = LHSCode | RHSCode; break;
3480 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003481 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003482 }
3483
3484 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3485 ICmpInst::isSignedPredicate(ICI->getPredicate());
3486
Owen Anderson24be4c12009-07-03 00:17:18 +00003487 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003488 if (Instruction *I = dyn_cast<Instruction>(RV))
3489 return I;
3490 // Otherwise, it's a constant boolean value...
3491 return IC.ReplaceInstUsesWith(Log, RV);
3492 }
3493};
3494} // end anonymous namespace
3495
3496// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3497// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3498// guaranteed to be a binary operator.
3499Instruction *InstCombiner::OptAndOp(Instruction *Op,
3500 ConstantInt *OpRHS,
3501 ConstantInt *AndRHS,
3502 BinaryOperator &TheAnd) {
3503 Value *X = Op->getOperand(0);
3504 Constant *Together = 0;
3505 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00003506 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003507
3508 switch (Op->getOpcode()) {
3509 case Instruction::Xor:
3510 if (Op->hasOneUse()) {
3511 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003512 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003513 InsertNewInstBefore(And, TheAnd);
3514 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003515 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003516 }
3517 break;
3518 case Instruction::Or:
3519 if (Together == AndRHS) // (X | C) & C --> C
3520 return ReplaceInstUsesWith(TheAnd, AndRHS);
3521
3522 if (Op->hasOneUse() && Together != OpRHS) {
3523 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003524 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003525 InsertNewInstBefore(Or, TheAnd);
3526 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003527 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003528 }
3529 break;
3530 case Instruction::Add:
3531 if (Op->hasOneUse()) {
3532 // Adding a one to a single bit bit-field should be turned into an XOR
3533 // of the bit. First thing to check is to see if this AND is with a
3534 // single bit constant.
3535 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3536
3537 // If there is only one bit set...
3538 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3539 // Ok, at this point, we know that we are masking the result of the
3540 // ADD down to exactly one bit. If the constant we are adding has
3541 // no bits set below this bit, then we can eliminate the ADD.
3542 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3543
3544 // Check to see if any bits below the one bit set in AndRHSV are set.
3545 if ((AddRHS & (AndRHSV-1)) == 0) {
3546 // If not, the only thing that can effect the output of the AND is
3547 // the bit specified by AndRHSV. If that bit is set, the effect of
3548 // the XOR is to toggle the bit. If it is clear, then the ADD has
3549 // no effect.
3550 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3551 TheAnd.setOperand(0, X);
3552 return &TheAnd;
3553 } else {
3554 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003555 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003556 InsertNewInstBefore(NewAnd, TheAnd);
3557 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003558 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003559 }
3560 }
3561 }
3562 }
3563 break;
3564
3565 case Instruction::Shl: {
3566 // We know that the AND will not produce any of the bits shifted in, so if
3567 // the anded constant includes them, clear them now!
3568 //
3569 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3570 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3571 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003572 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003573
3574 if (CI->getValue() == ShlMask) {
3575 // Masking out bits that the shift already masks
3576 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3577 } else if (CI != AndRHS) { // Reducing bits set in and.
3578 TheAnd.setOperand(1, CI);
3579 return &TheAnd;
3580 }
3581 break;
3582 }
3583 case Instruction::LShr:
3584 {
3585 // We know that the AND will not produce any of the bits shifted in, so if
3586 // the anded constant includes them, clear them now! This only applies to
3587 // unsigned shifts, because a signed shr may bring in set bits!
3588 //
3589 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3590 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3591 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003592 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003593
3594 if (CI->getValue() == ShrMask) {
3595 // Masking out bits that the shift already masks.
3596 return ReplaceInstUsesWith(TheAnd, Op);
3597 } else if (CI != AndRHS) {
3598 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3599 return &TheAnd;
3600 }
3601 break;
3602 }
3603 case Instruction::AShr:
3604 // Signed shr.
3605 // See if this is shifting in some sign extension, then masking it out
3606 // with an and.
3607 if (Op->hasOneUse()) {
3608 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3609 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3610 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003611 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003612 if (C == AndRHS) { // Masking out bits shifted in.
3613 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3614 // Make the argument unsigned.
3615 Value *ShVal = Op->getOperand(0);
3616 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003617 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003618 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003619 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003620 }
3621 }
3622 break;
3623 }
3624 return 0;
3625}
3626
3627
3628/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3629/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3630/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3631/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3632/// insert new instructions.
3633Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3634 bool isSigned, bool Inside,
3635 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003636 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003637 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3638 "Lo is not <= Hi in range emission code!");
3639
3640 if (Inside) {
3641 if (Lo == Hi) // Trivially false.
Owen Anderson6601fcd2009-07-09 23:48:35 +00003642 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003643
3644 // V >= Min && V < Hi --> V < Hi
3645 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3646 ICmpInst::Predicate pred = (isSigned ?
3647 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003648 return new ICmpInst(*Context, pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003649 }
3650
3651 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00003652 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003653 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003654 InsertNewInstBefore(Add, IB);
Owen Anderson02b48c32009-07-29 18:55:55 +00003655 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003656 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003657 }
3658
3659 if (Lo == Hi) // Trivially true.
Owen Anderson6601fcd2009-07-09 23:48:35 +00003660 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003661
3662 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003663 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003664 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3665 ICmpInst::Predicate pred = (isSigned ?
3666 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003667 return new ICmpInst(*Context, pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003668 }
3669
3670 // Emit V-Lo >u Hi-1-Lo
3671 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00003672 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003673 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003674 InsertNewInstBefore(Add, IB);
Owen Anderson02b48c32009-07-29 18:55:55 +00003675 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003676 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003677}
3678
3679// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3680// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3681// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3682// not, since all 1s are not contiguous.
3683static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3684 const APInt& V = Val->getValue();
3685 uint32_t BitWidth = Val->getType()->getBitWidth();
3686 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3687
3688 // look for the first zero bit after the run of ones
3689 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3690 // look for the first non-zero bit
3691 ME = V.getActiveBits();
3692 return true;
3693}
3694
3695/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3696/// where isSub determines whether the operator is a sub. If we can fold one of
3697/// the following xforms:
3698///
3699/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3700/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3701/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3702///
3703/// return (A +/- B).
3704///
3705Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3706 ConstantInt *Mask, bool isSub,
3707 Instruction &I) {
3708 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3709 if (!LHSI || LHSI->getNumOperands() != 2 ||
3710 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3711
3712 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3713
3714 switch (LHSI->getOpcode()) {
3715 default: return 0;
3716 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00003717 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003718 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3719 if ((Mask->getValue().countLeadingZeros() +
3720 Mask->getValue().countPopulation()) ==
3721 Mask->getValue().getBitWidth())
3722 break;
3723
3724 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3725 // part, we don't need any explicit masks to take them out of A. If that
3726 // is all N is, ignore it.
3727 uint32_t MB = 0, ME = 0;
3728 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3729 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3730 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3731 if (MaskedValueIsZero(RHS, Mask))
3732 break;
3733 }
3734 }
3735 return 0;
3736 case Instruction::Or:
3737 case Instruction::Xor:
3738 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3739 if ((Mask->getValue().countLeadingZeros() +
3740 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00003741 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003742 break;
3743 return 0;
3744 }
3745
3746 Instruction *New;
3747 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003748 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003749 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003750 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003751 return InsertNewInstBefore(New, I);
3752}
3753
Chris Lattner0631ea72008-11-16 05:06:21 +00003754/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3755Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3756 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00003757 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00003758 ConstantInt *LHSCst, *RHSCst;
3759 ICmpInst::Predicate LHSCC, RHSCC;
3760
Chris Lattnerf3803482008-11-16 05:10:52 +00003761 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00003762 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00003763 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00003764 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00003765 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00003766 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003767
3768 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3769 // where C is a power of 2
3770 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3771 LHSCst->getValue().isPowerOf2()) {
3772 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3773 InsertNewInstBefore(NewOr, I);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003774 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerf3803482008-11-16 05:10:52 +00003775 }
3776
3777 // From here on, we only handle:
3778 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3779 if (Val != Val2) return 0;
3780
Chris Lattner0631ea72008-11-16 05:06:21 +00003781 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3782 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3783 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3784 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3785 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3786 return 0;
3787
3788 // We can't fold (ugt x, C) & (sgt x, C2).
3789 if (!PredicatesFoldable(LHSCC, RHSCC))
3790 return 0;
3791
3792 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003793 bool ShouldSwap;
Chris Lattner0631ea72008-11-16 05:06:21 +00003794 if (ICmpInst::isSignedPredicate(LHSCC) ||
3795 (ICmpInst::isEquality(LHSCC) &&
3796 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003797 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003798 else
Chris Lattner665298f2008-11-16 05:14:43 +00003799 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3800
3801 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003802 std::swap(LHS, RHS);
3803 std::swap(LHSCst, RHSCst);
3804 std::swap(LHSCC, RHSCC);
3805 }
3806
3807 // At this point, we know we have have two icmp instructions
3808 // comparing a value against two constants and and'ing the result
3809 // together. Because of the above check, we know that we only have
3810 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3811 // (from the FoldICmpLogical check above), that the two constants
3812 // are not equal and that the larger constant is on the RHS
3813 assert(LHSCst != RHSCst && "Compares not folded above?");
3814
3815 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003816 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003817 case ICmpInst::ICMP_EQ:
3818 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003819 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003820 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3821 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3822 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003823 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003824 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3825 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3826 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3827 return ReplaceInstUsesWith(I, LHS);
3828 }
3829 case ICmpInst::ICMP_NE:
3830 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003831 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003832 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003833 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson6601fcd2009-07-09 23:48:35 +00003834 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003835 break; // (X != 13 & X u< 15) -> no change
3836 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003837 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson6601fcd2009-07-09 23:48:35 +00003838 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003839 break; // (X != 13 & X s< 15) -> no change
3840 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3841 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3842 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3843 return ReplaceInstUsesWith(I, RHS);
3844 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003845 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00003846 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003847 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3848 Val->getName()+".off");
3849 InsertNewInstBefore(Add, I);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003850 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003851 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00003852 }
3853 break; // (X != 13 & X != 15) -> no change
3854 }
3855 break;
3856 case ICmpInst::ICMP_ULT:
3857 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003858 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003859 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3860 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003861 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003862 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3863 break;
3864 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3865 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3866 return ReplaceInstUsesWith(I, LHS);
3867 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3868 break;
3869 }
3870 break;
3871 case ICmpInst::ICMP_SLT:
3872 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003873 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003874 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3875 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003876 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003877 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3878 break;
3879 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3880 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3881 return ReplaceInstUsesWith(I, LHS);
3882 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3883 break;
3884 }
3885 break;
3886 case ICmpInst::ICMP_UGT:
3887 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003888 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003889 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3890 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3891 return ReplaceInstUsesWith(I, RHS);
3892 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3893 break;
3894 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003895 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson6601fcd2009-07-09 23:48:35 +00003896 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003897 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003898 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003899 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003900 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003901 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3902 break;
3903 }
3904 break;
3905 case ICmpInst::ICMP_SGT:
3906 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003907 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003908 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3909 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3910 return ReplaceInstUsesWith(I, RHS);
3911 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3912 break;
3913 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003914 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson6601fcd2009-07-09 23:48:35 +00003915 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003916 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003917 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003918 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003919 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003920 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3921 break;
3922 }
3923 break;
3924 }
Chris Lattner0631ea72008-11-16 05:06:21 +00003925
3926 return 0;
3927}
3928
Chris Lattner93a359a2009-07-23 05:14:02 +00003929Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3930 FCmpInst *RHS) {
3931
3932 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3933 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3934 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3935 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3936 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3937 // If either of the constants are nans, then the whole thing returns
3938 // false.
3939 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00003940 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00003941 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3942 LHS->getOperand(0), RHS->getOperand(0));
3943 }
Chris Lattnercf373552009-07-23 05:32:17 +00003944
3945 // Handle vector zeros. This occurs because the canonical form of
3946 // "fcmp ord x,x" is "fcmp ord x, 0".
3947 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3948 isa<ConstantAggregateZero>(RHS->getOperand(1)))
3949 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3950 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00003951 return 0;
3952 }
3953
3954 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3955 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3956 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3957
3958
3959 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3960 // Swap RHS operands to match LHS.
3961 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3962 std::swap(Op1LHS, Op1RHS);
3963 }
3964
3965 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3966 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3967 if (Op0CC == Op1CC)
3968 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3969
3970 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00003971 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00003972 if (Op0CC == FCmpInst::FCMP_TRUE)
3973 return ReplaceInstUsesWith(I, RHS);
3974 if (Op1CC == FCmpInst::FCMP_TRUE)
3975 return ReplaceInstUsesWith(I, LHS);
3976
3977 bool Op0Ordered;
3978 bool Op1Ordered;
3979 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3980 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3981 if (Op1Pred == 0) {
3982 std::swap(LHS, RHS);
3983 std::swap(Op0Pred, Op1Pred);
3984 std::swap(Op0Ordered, Op1Ordered);
3985 }
3986 if (Op0Pred == 0) {
3987 // uno && ueq -> uno && (uno || eq) -> ueq
3988 // ord && olt -> ord && (ord && lt) -> olt
3989 if (Op0Ordered == Op1Ordered)
3990 return ReplaceInstUsesWith(I, RHS);
3991
3992 // uno && oeq -> uno && (ord && eq) -> false
3993 // uno && ord -> false
3994 if (!Op0Ordered)
Owen Anderson4f720fa2009-07-31 17:39:07 +00003995 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00003996 // ord && ueq -> ord && (uno || eq) -> oeq
3997 return cast<Instruction>(getFCmpValue(true, Op1Pred,
3998 Op0LHS, Op0RHS, Context));
3999 }
4000 }
4001
4002 return 0;
4003}
4004
Chris Lattner0631ea72008-11-16 05:06:21 +00004005
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004006Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4007 bool Changed = SimplifyCommutative(I);
4008 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4009
4010 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00004011 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004012
4013 // and X, X = X
4014 if (Op0 == Op1)
4015 return ReplaceInstUsesWith(I, Op1);
4016
4017 // See if we can simplify any instructions used by the instruction whose sole
4018 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004019 if (SimplifyDemandedInstructionBits(I))
4020 return &I;
4021 if (isa<VectorType>(I.getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004022 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4023 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4024 return ReplaceInstUsesWith(I, I.getOperand(0));
4025 } else if (isa<ConstantAggregateZero>(Op1)) {
4026 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4027 }
4028 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00004029
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004030 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4031 const APInt& AndRHSMask = AndRHS->getValue();
4032 APInt NotAndRHS(~AndRHSMask);
4033
4034 // Optimize a variety of ((val OP C1) & C2) combinations...
4035 if (isa<BinaryOperator>(Op0)) {
4036 Instruction *Op0I = cast<Instruction>(Op0);
4037 Value *Op0LHS = Op0I->getOperand(0);
4038 Value *Op0RHS = Op0I->getOperand(1);
4039 switch (Op0I->getOpcode()) {
4040 case Instruction::Xor:
4041 case Instruction::Or:
4042 // If the mask is only needed on one incoming arm, push it up.
4043 if (Op0I->hasOneUse()) {
4044 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4045 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00004046 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004047 Op0RHS->getName()+".masked");
4048 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004049 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004050 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4051 }
4052 if (!isa<Constant>(Op0RHS) &&
4053 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4054 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00004055 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004056 Op0LHS->getName()+".masked");
4057 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004058 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004059 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4060 }
4061 }
4062
4063 break;
4064 case Instruction::Add:
4065 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4066 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4067 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4068 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004069 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004070 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004071 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004072 break;
4073
4074 case Instruction::Sub:
4075 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4076 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4077 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4078 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004079 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004080
Nick Lewyckya349ba42008-07-10 05:51:40 +00004081 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4082 // has 1's for all bits that the subtraction with A might affect.
4083 if (Op0I->hasOneUse()) {
4084 uint32_t BitWidth = AndRHSMask.getBitWidth();
4085 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4086 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4087
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004088 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004089 if (!(A && A->isZero()) && // avoid infinite recursion.
4090 MaskedValueIsZero(Op0LHS, Mask)) {
Dan Gohmancdff2122009-08-12 16:23:25 +00004091 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004092 InsertNewInstBefore(NewNeg, I);
4093 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4094 }
4095 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004096 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004097
4098 case Instruction::Shl:
4099 case Instruction::LShr:
4100 // (1 << x) & 1 --> zext(x == 0)
4101 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004102 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00004103 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00004104 Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004105 InsertNewInstBefore(NewICmp, I);
4106 return new ZExtInst(NewICmp, I.getType());
4107 }
4108 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004109 }
4110
4111 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4112 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4113 return Res;
4114 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4115 // If this is an integer truncation or change from signed-to-unsigned, and
4116 // if the source is an and/or with immediate, transform it. This
4117 // frequently occurs for bitfield accesses.
4118 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4119 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4120 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004121 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004122 if (CastOp->getOpcode() == Instruction::And) {
4123 // Change: and (cast (and X, C1) to T), C2
4124 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4125 // This will fold the two constants together, which may allow
4126 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00004127 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004128 CastOp->getOperand(0), I.getType(),
4129 CastOp->getName()+".shrunk");
4130 NewCast = InsertNewInstBefore(NewCast, I);
4131 // trunc_or_bitcast(C1)&C2
Owen Anderson24be4c12009-07-03 00:17:18 +00004132 Constant *C3 =
Owen Anderson02b48c32009-07-29 18:55:55 +00004133 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4134 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004135 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004136 } else if (CastOp->getOpcode() == Instruction::Or) {
4137 // Change: and (cast (or X, C1) to T), C2
4138 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Anderson24be4c12009-07-03 00:17:18 +00004139 Constant *C3 =
Owen Anderson02b48c32009-07-29 18:55:55 +00004140 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4141 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00004142 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004143 return ReplaceInstUsesWith(I, AndRHS);
4144 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004145 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004146 }
4147 }
4148
4149 // Try to fold constant and into select arguments.
4150 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4151 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4152 return R;
4153 if (isa<PHINode>(Op0))
4154 if (Instruction *NV = FoldOpIntoPhi(I))
4155 return NV;
4156 }
4157
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004158 Value *Op0NotVal = dyn_castNotVal(Op0);
4159 Value *Op1NotVal = dyn_castNotVal(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004160
4161 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersonaac28372009-07-31 20:28:14 +00004162 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004163
4164 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4165 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004166 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004167 I.getName()+".demorgan");
4168 InsertNewInstBefore(Or, I);
Dan Gohmancdff2122009-08-12 16:23:25 +00004169 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004170 }
4171
4172 {
4173 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004174 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004175 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4176 return ReplaceInstUsesWith(I, Op1);
4177
4178 // (A|B) & ~(A&B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004179 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004180 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004181 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004182 }
4183 }
4184
Dan Gohmancdff2122009-08-12 16:23:25 +00004185 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004186 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4187 return ReplaceInstUsesWith(I, Op0);
4188
4189 // ~(A&B) & (A|B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004190 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004191 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004192 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004193 }
4194 }
4195
4196 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004197 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004198 if (A == Op1) { // (A^B)&A -> A&(A^B)
4199 I.swapOperands(); // Simplify below
4200 std::swap(Op0, Op1);
4201 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4202 cast<BinaryOperator>(Op0)->swapOperands();
4203 I.swapOperands(); // Simplify below
4204 std::swap(Op0, Op1);
4205 }
4206 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004207
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004208 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004209 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004210 if (B == Op0) { // B&(A^B) -> B&(B^A)
4211 cast<BinaryOperator>(Op1)->swapOperands();
4212 std::swap(A, B);
4213 }
4214 if (A == Op0) { // A&(A^B) -> A & ~B
Dan Gohmancdff2122009-08-12 16:23:25 +00004215 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004216 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004217 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004218 }
4219 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004220
4221 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00004222 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4223 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004224 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004225 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4226 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004227 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004228 }
4229
4230 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4231 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004232 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004233 return R;
4234
Chris Lattner0631ea72008-11-16 05:06:21 +00004235 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4236 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4237 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004238 }
4239
4240 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4241 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4242 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4243 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4244 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004245 if (SrcTy == Op1C->getOperand(0)->getType() &&
4246 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004247 // Only do this if the casts both really cause code to be generated.
4248 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4249 I.getType(), TD) &&
4250 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4251 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004252 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004253 Op1C->getOperand(0),
4254 I.getName());
4255 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004256 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004257 }
4258 }
4259
4260 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4261 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4262 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4263 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4264 SI0->getOperand(1) == SI1->getOperand(1) &&
4265 (SI0->hasOneUse() || SI1->hasOneUse())) {
4266 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004267 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004268 SI1->getOperand(0),
4269 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004270 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004271 SI1->getOperand(1));
4272 }
4273 }
4274
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004275 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004276 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004277 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4278 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4279 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004280 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004281
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004282 return Changed ? &I : 0;
4283}
4284
Chris Lattner567f5112008-10-05 02:13:19 +00004285/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4286/// capable of providing pieces of a bswap. The subexpression provides pieces
4287/// of a bswap if it is proven that each of the non-zero bytes in the output of
4288/// the expression came from the corresponding "byte swapped" byte in some other
4289/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4290/// we know that the expression deposits the low byte of %X into the high byte
4291/// of the bswap result and that all other bytes are zero. This expression is
4292/// accepted, the high byte of ByteValues is set to X to indicate a correct
4293/// match.
4294///
4295/// This function returns true if the match was unsuccessful and false if so.
4296/// On entry to the function the "OverallLeftShift" is a signed integer value
4297/// indicating the number of bytes that the subexpression is later shifted. For
4298/// example, if the expression is later right shifted by 16 bits, the
4299/// OverallLeftShift value would be -2 on entry. This is used to specify which
4300/// byte of ByteValues is actually being set.
4301///
4302/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4303/// byte is masked to zero by a user. For example, in (X & 255), X will be
4304/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4305/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4306/// always in the local (OverallLeftShift) coordinate space.
4307///
4308static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4309 SmallVector<Value*, 8> &ByteValues) {
4310 if (Instruction *I = dyn_cast<Instruction>(V)) {
4311 // If this is an or instruction, it may be an inner node of the bswap.
4312 if (I->getOpcode() == Instruction::Or) {
4313 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4314 ByteValues) ||
4315 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4316 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004317 }
Chris Lattner567f5112008-10-05 02:13:19 +00004318
4319 // If this is a logical shift by a constant multiple of 8, recurse with
4320 // OverallLeftShift and ByteMask adjusted.
4321 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4322 unsigned ShAmt =
4323 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4324 // Ensure the shift amount is defined and of a byte value.
4325 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4326 return true;
4327
4328 unsigned ByteShift = ShAmt >> 3;
4329 if (I->getOpcode() == Instruction::Shl) {
4330 // X << 2 -> collect(X, +2)
4331 OverallLeftShift += ByteShift;
4332 ByteMask >>= ByteShift;
4333 } else {
4334 // X >>u 2 -> collect(X, -2)
4335 OverallLeftShift -= ByteShift;
4336 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004337 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004338 }
4339
4340 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4341 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4342
4343 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4344 ByteValues);
4345 }
4346
4347 // If this is a logical 'and' with a mask that clears bytes, clear the
4348 // corresponding bytes in ByteMask.
4349 if (I->getOpcode() == Instruction::And &&
4350 isa<ConstantInt>(I->getOperand(1))) {
4351 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4352 unsigned NumBytes = ByteValues.size();
4353 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4354 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4355
4356 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4357 // If this byte is masked out by a later operation, we don't care what
4358 // the and mask is.
4359 if ((ByteMask & (1 << i)) == 0)
4360 continue;
4361
4362 // If the AndMask is all zeros for this byte, clear the bit.
4363 APInt MaskB = AndMask & Byte;
4364 if (MaskB == 0) {
4365 ByteMask &= ~(1U << i);
4366 continue;
4367 }
4368
4369 // If the AndMask is not all ones for this byte, it's not a bytezap.
4370 if (MaskB != Byte)
4371 return true;
4372
4373 // Otherwise, this byte is kept.
4374 }
4375
4376 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4377 ByteValues);
4378 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004379 }
4380
Chris Lattner567f5112008-10-05 02:13:19 +00004381 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4382 // the input value to the bswap. Some observations: 1) if more than one byte
4383 // is demanded from this input, then it could not be successfully assembled
4384 // into a byteswap. At least one of the two bytes would not be aligned with
4385 // their ultimate destination.
4386 if (!isPowerOf2_32(ByteMask)) return true;
4387 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004388
Chris Lattner567f5112008-10-05 02:13:19 +00004389 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4390 // is demanded, it needs to go into byte 0 of the result. This means that the
4391 // byte needs to be shifted until it lands in the right byte bucket. The
4392 // shift amount depends on the position: if the byte is coming from the high
4393 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4394 // low part, it must be shifted left.
4395 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4396 if (InputByteNo < ByteValues.size()/2) {
4397 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4398 return true;
4399 } else {
4400 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4401 return true;
4402 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004403
4404 // If the destination byte value is already defined, the values are or'd
4405 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004406 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004407 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004408 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004409 return false;
4410}
4411
4412/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4413/// If so, insert the new bswap intrinsic and return it.
4414Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4415 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004416 if (!ITy || ITy->getBitWidth() % 16 ||
4417 // ByteMask only allows up to 32-byte values.
4418 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004419 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4420
4421 /// ByteValues - For each byte of the result, we keep track of which value
4422 /// defines each byte.
4423 SmallVector<Value*, 8> ByteValues;
4424 ByteValues.resize(ITy->getBitWidth()/8);
4425
4426 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004427 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4428 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004429 return 0;
4430
4431 // Check to see if all of the bytes come from the same value.
4432 Value *V = ByteValues[0];
4433 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4434
4435 // Check to make sure that all of the bytes come from the same value.
4436 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4437 if (ByteValues[i] != V)
4438 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004439 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004440 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004441 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004442 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004443}
4444
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004445/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4446/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4447/// we can simplify this expression to "cond ? C : D or B".
4448static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004449 Value *C, Value *D,
4450 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004451 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004452 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004453 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004454 return 0;
4455
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004456 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00004457 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004458 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00004459 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004460 return SelectInst::Create(Cond, C, B);
4461 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00004462 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004463 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00004464 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004465 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004466 return 0;
4467}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004468
Chris Lattner0c678e52008-11-16 05:20:07 +00004469/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4470Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4471 ICmpInst *LHS, ICmpInst *RHS) {
4472 Value *Val, *Val2;
4473 ConstantInt *LHSCst, *RHSCst;
4474 ICmpInst::Predicate LHSCC, RHSCC;
4475
4476 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004477 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004478 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004479 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004480 m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00004481 return 0;
4482
4483 // From here on, we only handle:
4484 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4485 if (Val != Val2) return 0;
4486
4487 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4488 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4489 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4490 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4491 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4492 return 0;
4493
4494 // We can't fold (ugt x, C) | (sgt x, C2).
4495 if (!PredicatesFoldable(LHSCC, RHSCC))
4496 return 0;
4497
4498 // Ensure that the larger constant is on the RHS.
4499 bool ShouldSwap;
4500 if (ICmpInst::isSignedPredicate(LHSCC) ||
4501 (ICmpInst::isEquality(LHSCC) &&
4502 ICmpInst::isSignedPredicate(RHSCC)))
4503 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4504 else
4505 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4506
4507 if (ShouldSwap) {
4508 std::swap(LHS, RHS);
4509 std::swap(LHSCst, RHSCst);
4510 std::swap(LHSCC, RHSCC);
4511 }
4512
4513 // At this point, we know we have have two icmp instructions
4514 // comparing a value against two constants and or'ing the result
4515 // together. Because of the above check, we know that we only have
4516 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4517 // FoldICmpLogical check above), that the two constants are not
4518 // equal.
4519 assert(LHSCst != RHSCst && "Compares not folded above?");
4520
4521 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004522 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004523 case ICmpInst::ICMP_EQ:
4524 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004525 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004526 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004527 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004528 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00004529 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner0c678e52008-11-16 05:20:07 +00004530 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4531 Val->getName()+".off");
4532 InsertNewInstBefore(Add, I);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004533 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Owen Anderson6601fcd2009-07-09 23:48:35 +00004534 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004535 }
4536 break; // (X == 13 | X == 15) -> no change
4537 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4538 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4539 break;
4540 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4541 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4542 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4543 return ReplaceInstUsesWith(I, RHS);
4544 }
4545 break;
4546 case ICmpInst::ICMP_NE:
4547 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004548 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004549 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4550 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4551 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4552 return ReplaceInstUsesWith(I, LHS);
4553 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4554 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4555 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004556 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004557 }
4558 break;
4559 case ICmpInst::ICMP_ULT:
4560 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004561 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004562 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4563 break;
4564 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4565 // If RHSCst is [us]MAXINT, it is always false. Not handling
4566 // this can cause overflow.
4567 if (RHSCst->isMaxValue(false))
4568 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004569 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004570 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004571 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4572 break;
4573 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4574 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4575 return ReplaceInstUsesWith(I, RHS);
4576 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4577 break;
4578 }
4579 break;
4580 case ICmpInst::ICMP_SLT:
4581 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004582 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004583 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4584 break;
4585 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4586 // If RHSCst is [us]MAXINT, it is always false. Not handling
4587 // this can cause overflow.
4588 if (RHSCst->isMaxValue(true))
4589 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004590 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004591 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004592 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4593 break;
4594 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4595 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4596 return ReplaceInstUsesWith(I, RHS);
4597 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4598 break;
4599 }
4600 break;
4601 case ICmpInst::ICMP_UGT:
4602 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004603 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004604 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4605 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4606 return ReplaceInstUsesWith(I, LHS);
4607 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4608 break;
4609 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4610 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004611 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004612 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4613 break;
4614 }
4615 break;
4616 case ICmpInst::ICMP_SGT:
4617 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004618 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004619 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4620 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4621 return ReplaceInstUsesWith(I, LHS);
4622 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4623 break;
4624 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4625 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004626 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004627 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4628 break;
4629 }
4630 break;
4631 }
4632 return 0;
4633}
4634
Chris Lattner57e66fa2009-07-23 05:46:22 +00004635Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4636 FCmpInst *RHS) {
4637 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4638 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4639 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4640 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4641 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4642 // If either of the constants are nans, then the whole thing returns
4643 // true.
4644 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004645 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004646
4647 // Otherwise, no need to compare the two constants, compare the
4648 // rest.
4649 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4650 LHS->getOperand(0), RHS->getOperand(0));
4651 }
4652
4653 // Handle vector zeros. This occurs because the canonical form of
4654 // "fcmp uno x,x" is "fcmp uno x, 0".
4655 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4656 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4657 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4658 LHS->getOperand(0), RHS->getOperand(0));
4659
4660 return 0;
4661 }
4662
4663 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4664 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4665 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4666
4667 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4668 // Swap RHS operands to match LHS.
4669 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4670 std::swap(Op1LHS, Op1RHS);
4671 }
4672 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4673 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4674 if (Op0CC == Op1CC)
4675 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4676 Op0LHS, Op0RHS);
4677 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004678 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004679 if (Op0CC == FCmpInst::FCMP_FALSE)
4680 return ReplaceInstUsesWith(I, RHS);
4681 if (Op1CC == FCmpInst::FCMP_FALSE)
4682 return ReplaceInstUsesWith(I, LHS);
4683 bool Op0Ordered;
4684 bool Op1Ordered;
4685 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4686 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4687 if (Op0Ordered == Op1Ordered) {
4688 // If both are ordered or unordered, return a new fcmp with
4689 // or'ed predicates.
4690 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4691 Op0LHS, Op0RHS, Context);
4692 if (Instruction *I = dyn_cast<Instruction>(RV))
4693 return I;
4694 // Otherwise, it's a constant boolean value...
4695 return ReplaceInstUsesWith(I, RV);
4696 }
4697 }
4698 return 0;
4699}
4700
Bill Wendlingdae376a2008-12-01 08:23:25 +00004701/// FoldOrWithConstants - This helper function folds:
4702///
Bill Wendling236a1192008-12-02 05:09:00 +00004703/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004704///
4705/// into:
4706///
Bill Wendling236a1192008-12-02 05:09:00 +00004707/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004708///
Bill Wendling236a1192008-12-02 05:09:00 +00004709/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004710Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004711 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004712 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4713 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004714
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004715 Value *V1 = 0;
4716 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004717 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004718
Bill Wendling86ee3162008-12-02 06:18:11 +00004719 APInt Xor = CI1->getValue() ^ CI2->getValue();
4720 if (!Xor.isAllOnesValue()) return 0;
4721
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004722 if (V1 == A || V1 == B) {
Bill Wendling86ee3162008-12-02 06:18:11 +00004723 Instruction *NewOp =
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004724 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4725 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004726 }
4727
4728 return 0;
4729}
4730
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004731Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4732 bool Changed = SimplifyCommutative(I);
4733 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4734
4735 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersonaac28372009-07-31 20:28:14 +00004736 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004737
4738 // or X, X = X
4739 if (Op0 == Op1)
4740 return ReplaceInstUsesWith(I, Op0);
4741
4742 // See if we can simplify any instructions used by the instruction whose sole
4743 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004744 if (SimplifyDemandedInstructionBits(I))
4745 return &I;
4746 if (isa<VectorType>(I.getType())) {
4747 if (isa<ConstantAggregateZero>(Op1)) {
4748 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4749 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4750 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4751 return ReplaceInstUsesWith(I, I.getOperand(1));
4752 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004753 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004754
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004755 // or X, -1 == -1
4756 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4757 ConstantInt *C1 = 0; Value *X = 0;
4758 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004759 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004760 isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004761 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004762 InsertNewInstBefore(Or, I);
4763 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004764 return BinaryOperator::CreateAnd(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004765 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004766 }
4767
4768 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004769 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004770 isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004771 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004772 InsertNewInstBefore(Or, I);
4773 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004774 return BinaryOperator::CreateXor(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004775 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004776 }
4777
4778 // Try to fold constant and into select arguments.
4779 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4780 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4781 return R;
4782 if (isa<PHINode>(Op0))
4783 if (Instruction *NV = FoldOpIntoPhi(I))
4784 return NV;
4785 }
4786
4787 Value *A = 0, *B = 0;
4788 ConstantInt *C1 = 0, *C2 = 0;
4789
Dan Gohmancdff2122009-08-12 16:23:25 +00004790 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004791 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4792 return ReplaceInstUsesWith(I, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004793 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004794 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4795 return ReplaceInstUsesWith(I, Op0);
4796
4797 // (A | B) | C and A | (B | C) -> bswap if possible.
4798 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00004799 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4800 match(Op1, m_Or(m_Value(), m_Value())) ||
4801 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4802 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004803 if (Instruction *BSwap = MatchBSwap(I))
4804 return BSwap;
4805 }
4806
4807 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004808 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004809 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004810 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004811 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004812 InsertNewInstBefore(NOr, I);
4813 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004814 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004815 }
4816
4817 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004818 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004819 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004820 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004821 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004822 InsertNewInstBefore(NOr, I);
4823 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) {
4873 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004874 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4875 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004876 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004877 }
Dan Gohman279952c2008-10-28 22:38:57 +00004878
Dan Gohman35b76162008-10-30 20:40:10 +00004879 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00004880 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004881 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004882 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004883 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004884 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004885 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004886 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004887 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004888
Bill Wendling22ca8352008-11-30 13:52:49 +00004889 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004890 if ((match(C, m_Not(m_Specific(D))) &&
4891 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004892 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004893 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004894 if ((match(A, m_Not(m_Specific(D))) &&
4895 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004896 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004897 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004898 if ((match(C, m_Not(m_Specific(B))) &&
4899 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004900 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004901 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004902 if ((match(A, m_Not(m_Specific(B))) &&
4903 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004904 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004905 }
4906
4907 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4908 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4909 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4910 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4911 SI0->getOperand(1) == SI1->getOperand(1) &&
4912 (SI0->hasOneUse() || SI1->hasOneUse())) {
4913 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004914 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004915 SI1->getOperand(0),
4916 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004917 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004918 SI1->getOperand(1));
4919 }
4920 }
4921
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004922 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004923 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4924 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004925 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004926 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004927 }
4928 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004929 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4930 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004931 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004932 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004933 }
4934
Dan Gohmancdff2122009-08-12 16:23:25 +00004935 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004936 if (A == Op1) // ~A | A == -1
Owen Andersonaac28372009-07-31 20:28:14 +00004937 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004938 } else {
4939 A = 0;
4940 }
4941 // Note, A is still live here!
Dan Gohmancdff2122009-08-12 16:23:25 +00004942 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004943 if (Op0 == B)
Owen Andersonaac28372009-07-31 20:28:14 +00004944 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004945
4946 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4947 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004948 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004949 I.getName()+".demorgan"), I);
Dan Gohmancdff2122009-08-12 16:23:25 +00004950 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004951 }
4952 }
4953
4954 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4955 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004956 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004957 return R;
4958
Chris Lattner0c678e52008-11-16 05:20:07 +00004959 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4960 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4961 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004962 }
4963
4964 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004965 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004966 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4967 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004968 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4969 !isa<ICmpInst>(Op1C->getOperand(0))) {
4970 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004971 if (SrcTy == Op1C->getOperand(0)->getType() &&
4972 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00004973 // Only do this if the casts both really cause code to be
4974 // generated.
4975 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4976 I.getType(), TD) &&
4977 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4978 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004979 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004980 Op1C->getOperand(0),
4981 I.getName());
4982 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004983 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004984 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004985 }
4986 }
Chris Lattner91882432007-10-24 05:38:08 +00004987 }
4988
4989
4990 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4991 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00004992 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4993 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4994 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004995 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004996
4997 return Changed ? &I : 0;
4998}
4999
Dan Gohman089efff2008-05-13 00:00:25 +00005000namespace {
5001
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005002// XorSelf - Implements: X ^ X --> 0
5003struct XorSelf {
5004 Value *RHS;
5005 XorSelf(Value *rhs) : RHS(rhs) {}
5006 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5007 Instruction *apply(BinaryOperator &Xor) const {
5008 return &Xor;
5009 }
5010};
5011
Dan Gohman089efff2008-05-13 00:00:25 +00005012}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005013
5014Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5015 bool Changed = SimplifyCommutative(I);
5016 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5017
Evan Chenge5cd8032008-03-25 20:07:13 +00005018 if (isa<UndefValue>(Op1)) {
5019 if (isa<UndefValue>(Op0))
5020 // Handle undef ^ undef -> 0 special case. This is a common
5021 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00005022 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005023 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005024 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005025
5026 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005027 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005028 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00005029 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005030 }
5031
5032 // See if we can simplify any instructions used by the instruction whose sole
5033 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005034 if (SimplifyDemandedInstructionBits(I))
5035 return &I;
5036 if (isa<VectorType>(I.getType()))
5037 if (isa<ConstantAggregateZero>(Op1))
5038 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005039
5040 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005041 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005042 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5043 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5044 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5045 if (Op0I->getOpcode() == Instruction::And ||
5046 Op0I->getOpcode() == Instruction::Or) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005047 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5048 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005049 Instruction *NotY =
Dan Gohmancdff2122009-08-12 16:23:25 +00005050 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005051 Op0I->getOperand(1)->getName()+".not");
5052 InsertNewInstBefore(NotY, I);
5053 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005054 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005055 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005056 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005057 }
5058 }
5059 }
5060 }
5061
5062
5063 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00005064 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005065 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005066 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson6601fcd2009-07-09 23:48:35 +00005067 return new ICmpInst(*Context, ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005068 ICI->getOperand(0), ICI->getOperand(1));
5069
Nick Lewycky1405e922007-08-06 20:04:16 +00005070 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson6601fcd2009-07-09 23:48:35 +00005071 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005072 FCI->getOperand(0), FCI->getOperand(1));
5073 }
5074
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005075 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5076 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5077 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5078 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5079 Instruction::CastOps Opcode = Op0C->getOpcode();
5080 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005081 if (RHS == ConstantExpr::getCast(Opcode,
Owen Anderson4f720fa2009-07-31 17:39:07 +00005082 ConstantInt::getTrue(*Context),
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005083 Op0C->getDestTy())) {
5084 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson6601fcd2009-07-09 23:48:35 +00005085 *Context,
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005086 CI->getOpcode(), CI->getInversePredicate(),
5087 CI->getOperand(0), CI->getOperand(1)), I);
5088 NewCI->takeName(CI);
5089 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5090 }
5091 }
5092 }
5093 }
5094 }
5095
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005096 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5097 // ~(c-X) == X-c-1 == X+(-c-1)
5098 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5099 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005100 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5101 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005102 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005103 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005104 }
5105
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005106 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005107 if (Op0I->getOpcode() == Instruction::Add) {
5108 // ~(X-c) --> (-c-1)-X
5109 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005110 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005111 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00005112 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005113 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00005114 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005115 } else if (RHS->getValue().isSignBit()) {
5116 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005117 Constant *C = ConstantInt::get(*Context,
5118 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005119 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005120
5121 }
5122 } else if (Op0I->getOpcode() == Instruction::Or) {
5123 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5124 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005125 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005126 // Anything in both C1 and C2 is known to be zero, remove it from
5127 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00005128 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5129 NewRHS = ConstantExpr::getAnd(NewRHS,
5130 ConstantExpr::getNot(CommonBits));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005131 AddToWorkList(Op0I);
5132 I.setOperand(0, Op0I->getOperand(0));
5133 I.setOperand(1, NewRHS);
5134 return &I;
5135 }
5136 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005137 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005138 }
5139
5140 // Try to fold constant and into select arguments.
5141 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5142 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5143 return R;
5144 if (isa<PHINode>(Op0))
5145 if (Instruction *NV = FoldOpIntoPhi(I))
5146 return NV;
5147 }
5148
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005149 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005150 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00005151 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005152
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005153 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005154 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00005155 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005156
5157
5158 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5159 if (Op1I) {
5160 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005161 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005162 if (A == Op0) { // B^(B|A) == (A|B)^B
5163 Op1I->swapOperands();
5164 I.swapOperands();
5165 std::swap(Op0, Op1);
5166 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5167 I.swapOperands(); // Simplified below.
5168 std::swap(Op0, Op1);
5169 }
Dan Gohmancdff2122009-08-12 16:23:25 +00005170 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005171 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005172 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005173 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005174 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005175 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005176 if (A == Op0) { // A^(A&B) -> A^(B&A)
5177 Op1I->swapOperands();
5178 std::swap(A, B);
5179 }
5180 if (B == Op0) { // A^(B&A) -> (B&A)^A
5181 I.swapOperands(); // Simplified below.
5182 std::swap(Op0, Op1);
5183 }
5184 }
5185 }
5186
5187 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5188 if (Op0I) {
5189 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005190 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005191 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005192 if (A == Op1) // (B|A)^B == (A|B)^B
5193 std::swap(A, B);
5194 if (B == Op1) { // (A|B)^B == A & ~B
5195 Instruction *NotB =
Dan Gohmancdff2122009-08-12 16:23:25 +00005196 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005197 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005198 }
Dan Gohmancdff2122009-08-12 16:23:25 +00005199 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005200 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005201 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005202 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005203 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005204 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005205 if (A == Op1) // (A&B)^A -> (B&A)^A
5206 std::swap(A, B);
5207 if (B == Op1 && // (B&A)^A == ~B & A
5208 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5209 Instruction *N =
Dan Gohmancdff2122009-08-12 16:23:25 +00005210 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005211 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005212 }
5213 }
5214 }
5215
5216 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5217 if (Op0I && Op1I && Op0I->isShift() &&
5218 Op0I->getOpcode() == Op1I->getOpcode() &&
5219 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5220 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5221 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005222 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005223 Op1I->getOperand(0),
5224 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005225 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005226 Op1I->getOperand(1));
5227 }
5228
5229 if (Op0I && Op1I) {
5230 Value *A, *B, *C, *D;
5231 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005232 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5233 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005234 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005235 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005236 }
5237 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005238 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5239 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005240 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005241 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005242 }
5243
5244 // (A & B)^(C & D)
5245 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005246 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5247 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005248 // (X & Y)^(X & Y) -> (Y^Z) & X
5249 Value *X = 0, *Y = 0, *Z = 0;
5250 if (A == C)
5251 X = A, Y = B, Z = D;
5252 else if (A == D)
5253 X = A, Y = B, Z = C;
5254 else if (B == C)
5255 X = B, Y = A, Z = D;
5256 else if (B == D)
5257 X = B, Y = A, Z = C;
5258
5259 if (X) {
5260 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005261 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5262 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005263 }
5264 }
5265 }
5266
5267 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5268 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005269 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005270 return R;
5271
5272 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005273 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005274 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5275 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5276 const Type *SrcTy = Op0C->getOperand(0)->getType();
5277 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5278 // Only do this if the casts both really cause code to be generated.
5279 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5280 I.getType(), TD) &&
5281 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5282 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00005283 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005284 Op1C->getOperand(0),
5285 I.getName());
5286 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005287 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005288 }
5289 }
Chris Lattner91882432007-10-24 05:38:08 +00005290 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005291
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005292 return Changed ? &I : 0;
5293}
5294
Owen Anderson24be4c12009-07-03 00:17:18 +00005295static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005296 LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005297 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005298}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005299
Dan Gohman8fd520a2009-06-15 22:12:54 +00005300static bool HasAddOverflow(ConstantInt *Result,
5301 ConstantInt *In1, ConstantInt *In2,
5302 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005303 if (IsSigned)
5304 if (In2->getValue().isNegative())
5305 return Result->getValue().sgt(In1->getValue());
5306 else
5307 return Result->getValue().slt(In1->getValue());
5308 else
5309 return Result->getValue().ult(In1->getValue());
5310}
5311
Dan Gohman8fd520a2009-06-15 22:12:54 +00005312/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005313/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005314static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005315 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005316 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005317 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005318
Dan Gohman8fd520a2009-06-15 22:12:54 +00005319 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5320 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005321 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005322 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5323 ExtractElement(In1, Idx, Context),
5324 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005325 IsSigned))
5326 return true;
5327 }
5328 return false;
5329 }
5330
5331 return HasAddOverflow(cast<ConstantInt>(Result),
5332 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5333 IsSigned);
5334}
5335
5336static bool HasSubOverflow(ConstantInt *Result,
5337 ConstantInt *In1, ConstantInt *In2,
5338 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005339 if (IsSigned)
5340 if (In2->getValue().isNegative())
5341 return Result->getValue().slt(In1->getValue());
5342 else
5343 return Result->getValue().sgt(In1->getValue());
5344 else
5345 return Result->getValue().ugt(In1->getValue());
5346}
5347
Dan Gohman8fd520a2009-06-15 22:12:54 +00005348/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5349/// overflowed for this type.
5350static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005351 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005352 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005353 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005354
5355 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5356 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005357 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005358 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5359 ExtractElement(In1, Idx, Context),
5360 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005361 IsSigned))
5362 return true;
5363 }
5364 return false;
5365 }
5366
5367 return HasSubOverflow(cast<ConstantInt>(Result),
5368 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5369 IsSigned);
5370}
5371
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005372/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5373/// code necessary to compute the offset from the base pointer (without adding
5374/// in the base pointer). Return the result as a signed integer of intptr size.
5375static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005376 TargetData &TD = *IC.getTargetData();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005377 gep_type_iterator GTI = gep_type_begin(GEP);
5378 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson5349f052009-07-06 23:00:19 +00005379 LLVMContext *Context = IC.getContext();
Owen Andersonaac28372009-07-31 20:28:14 +00005380 Value *Result = Constant::getNullValue(IntPtrTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005381
5382 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005383 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005384 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5385
Gabor Greif17396002008-06-12 21:37:33 +00005386 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5387 ++i, ++GTI) {
5388 Value *Op = *i;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005389 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005390 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5391 if (OpC->isZero()) continue;
5392
5393 // Handle a struct index, which adds its field offset to the pointer.
5394 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5395 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5396
5397 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Anderson24be4c12009-07-03 00:17:18 +00005398 Result =
Owen Andersoneacb44d2009-07-24 23:12:02 +00005399 ConstantInt::get(*Context,
5400 RC->getValue() + APInt(IntPtrWidth, Size));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005401 else
5402 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005403 BinaryOperator::CreateAdd(Result,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005404 ConstantInt::get(IntPtrTy, Size),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005405 GEP->getName()+".offs"), I);
5406 continue;
5407 }
5408
Owen Andersoneacb44d2009-07-24 23:12:02 +00005409 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Anderson24be4c12009-07-03 00:17:18 +00005410 Constant *OC =
Owen Anderson02b48c32009-07-29 18:55:55 +00005411 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5412 Scale = ConstantExpr::getMul(OC, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005413 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00005414 Result = ConstantExpr::getAdd(RC, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005415 else {
5416 // Emit an add instruction.
5417 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005418 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005419 GEP->getName()+".offs"), I);
5420 }
5421 continue;
5422 }
5423 // Convert to correct type.
5424 if (Op->getType() != IntPtrTy) {
5425 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Anderson02b48c32009-07-29 18:55:55 +00005426 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005427 else
Chris Lattner2941a652009-04-07 05:03:34 +00005428 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5429 true,
5430 Op->getName()+".c"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005431 }
5432 if (Size != 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005433 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005434 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Anderson02b48c32009-07-29 18:55:55 +00005435 Op = ConstantExpr::getMul(OpC, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005436 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00005437 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005438 GEP->getName()+".idx"), I);
5439 }
5440
5441 // Emit an add instruction.
5442 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00005443 Result = ConstantExpr::getAdd(cast<Constant>(Op),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005444 cast<Constant>(Result));
5445 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005446 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005447 GEP->getName()+".offs"), I);
5448 }
5449 return Result;
5450}
5451
Chris Lattnereba75862008-04-22 02:53:33 +00005452
Dan Gohmanff9b4732009-07-17 22:16:21 +00005453/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5454/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5455/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5456/// be complex, and scales are involved. The above expression would also be
5457/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5458/// This later form is less amenable to optimization though, and we are allowed
5459/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattnereba75862008-04-22 02:53:33 +00005460///
5461/// If we can't emit an optimized form for this expression, this returns null.
5462///
5463static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5464 InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005465 TargetData &TD = *IC.getTargetData();
Chris Lattnereba75862008-04-22 02:53:33 +00005466 gep_type_iterator GTI = gep_type_begin(GEP);
5467
5468 // Check to see if this gep only has a single variable index. If so, and if
5469 // any constant indices are a multiple of its scale, then we can compute this
5470 // in terms of the scale of the variable index. For example, if the GEP
5471 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5472 // because the expression will cross zero at the same point.
5473 unsigned i, e = GEP->getNumOperands();
5474 int64_t Offset = 0;
5475 for (i = 1; i != e; ++i, ++GTI) {
5476 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5477 // Compute the aggregate offset of constant indices.
5478 if (CI->isZero()) continue;
5479
5480 // Handle a struct index, which adds its field offset to the pointer.
5481 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5482 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5483 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005484 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005485 Offset += Size*CI->getSExtValue();
5486 }
5487 } else {
5488 // Found our variable index.
5489 break;
5490 }
5491 }
5492
5493 // If there are no variable indices, we must have a constant offset, just
5494 // evaluate it the general way.
5495 if (i == e) return 0;
5496
5497 Value *VariableIdx = GEP->getOperand(i);
5498 // Determine the scale factor of the variable element. For example, this is
5499 // 4 if the variable index is into an array of i32.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005500 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005501
5502 // Verify that there are no other variable indices. If so, emit the hard way.
5503 for (++i, ++GTI; i != e; ++i, ++GTI) {
5504 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5505 if (!CI) return 0;
5506
5507 // Compute the aggregate offset of constant indices.
5508 if (CI->isZero()) continue;
5509
5510 // Handle a struct index, which adds its field offset to the pointer.
5511 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5512 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5513 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005514 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005515 Offset += Size*CI->getSExtValue();
5516 }
5517 }
5518
5519 // Okay, we know we have a single variable index, which must be a
5520 // pointer/array/vector index. If there is no offset, life is simple, return
5521 // the index.
5522 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5523 if (Offset == 0) {
5524 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5525 // we don't need to bother extending: the extension won't affect where the
5526 // computation crosses zero.
5527 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5528 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005529 VariableIdx->getName(), &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005530 return VariableIdx;
5531 }
5532
5533 // Otherwise, there is an index. The computation we will do will be modulo
5534 // the pointer size, so get it.
5535 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5536
5537 Offset &= PtrSizeMask;
5538 VariableScale &= PtrSizeMask;
5539
5540 // To do this transformation, any constant index must be a multiple of the
5541 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5542 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5543 // multiple of the variable scale.
5544 int64_t NewOffs = Offset / (int64_t)VariableScale;
5545 if (Offset != NewOffs*(int64_t)VariableScale)
5546 return 0;
5547
5548 // Okay, we can do this evaluation. Start by converting the index to intptr.
5549 const Type *IntPtrTy = TD.getIntPtrType();
5550 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005551 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005552 true /*SExt*/,
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005553 VariableIdx->getName(), &I);
Owen Andersoneacb44d2009-07-24 23:12:02 +00005554 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005555 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005556}
5557
5558
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005559/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5560/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohman17f46f72009-07-28 01:40:03 +00005561Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005562 ICmpInst::Predicate Cond,
5563 Instruction &I) {
Chris Lattnereba75862008-04-22 02:53:33 +00005564 // Look through bitcasts.
5565 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5566 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005567
5568 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohman17f46f72009-07-28 01:40:03 +00005569 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005570 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005571 // This transformation (ignoring the base and scales) is valid because we
Dan Gohman17f46f72009-07-28 01:40:03 +00005572 // know pointers can't overflow since the gep is inbounds. See if we can
5573 // output an optimized form.
Chris Lattnereba75862008-04-22 02:53:33 +00005574 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5575
5576 // If not, synthesize the offset the hard way.
5577 if (Offset == 0)
5578 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson6601fcd2009-07-09 23:48:35 +00005579 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonaac28372009-07-31 20:28:14 +00005580 Constant::getNullValue(Offset->getType()));
Dan Gohman17f46f72009-07-28 01:40:03 +00005581 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005582 // If the base pointers are different, but the indices are the same, just
5583 // compare the base pointer.
5584 if (PtrBase != GEPRHS->getOperand(0)) {
5585 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5586 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5587 GEPRHS->getOperand(0)->getType();
5588 if (IndicesTheSame)
5589 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5590 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5591 IndicesTheSame = false;
5592 break;
5593 }
5594
5595 // If all indices are the same, just compare the base pointers.
5596 if (IndicesTheSame)
Owen Anderson6601fcd2009-07-09 23:48:35 +00005597 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005598 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5599
5600 // Otherwise, the base pointers are different and the indices are
5601 // different, bail out.
5602 return 0;
5603 }
5604
5605 // If one of the GEPs has all zero indices, recurse.
5606 bool AllZeros = true;
5607 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5608 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5609 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5610 AllZeros = false;
5611 break;
5612 }
5613 if (AllZeros)
5614 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5615 ICmpInst::getSwappedPredicate(Cond), I);
5616
5617 // If the other GEP has all zero indices, recurse.
5618 AllZeros = true;
5619 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5620 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5621 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5622 AllZeros = false;
5623 break;
5624 }
5625 if (AllZeros)
5626 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5627
5628 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5629 // If the GEPs only differ by one index, compare it.
5630 unsigned NumDifferences = 0; // Keep track of # differences.
5631 unsigned DiffOperand = 0; // The operand that differs.
5632 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5633 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5634 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5635 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5636 // Irreconcilable differences.
5637 NumDifferences = 2;
5638 break;
5639 } else {
5640 if (NumDifferences++) break;
5641 DiffOperand = i;
5642 }
5643 }
5644
5645 if (NumDifferences == 0) // SAME GEP?
5646 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersoneacb44d2009-07-24 23:12:02 +00005647 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005648 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005649
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005650 else if (NumDifferences == 1) {
5651 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5652 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5653 // Make sure we do a signed comparison here.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005654 return new ICmpInst(*Context,
5655 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005656 }
5657 }
5658
5659 // Only lower this if the icmp is the only user of the GEP or if we expect
5660 // the result to fold to a constant!
Dan Gohmana80e2712009-07-21 23:21:54 +00005661 if (TD &&
5662 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005663 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5664 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5665 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5666 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson6601fcd2009-07-09 23:48:35 +00005667 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005668 }
5669 }
5670 return 0;
5671}
5672
Chris Lattnere6b62d92008-05-19 20:18:56 +00005673/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5674///
5675Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5676 Instruction *LHSI,
5677 Constant *RHSC) {
5678 if (!isa<ConstantFP>(RHSC)) return 0;
5679 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5680
5681 // Get the width of the mantissa. We don't want to hack on conversions that
5682 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005683 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005684 if (MantissaWidth == -1) return 0; // Unknown.
5685
5686 // Check to see that the input is converted from an integer type that is small
5687 // enough that preserves all bits. TODO: check here for "known" sign bits.
5688 // 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 +00005689 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005690
5691 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005692 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5693 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005694 ++InputSize;
5695
5696 // If the conversion would lose info, don't hack on this.
5697 if ((int)InputSize > MantissaWidth)
5698 return 0;
5699
5700 // Otherwise, we can potentially simplify the comparison. We know that it
5701 // will always come through as an integer value and we know the constant is
5702 // not a NAN (it would have been previously simplified).
5703 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5704
5705 ICmpInst::Predicate Pred;
5706 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005707 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnere6b62d92008-05-19 20:18:56 +00005708 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005709 case FCmpInst::FCMP_OEQ:
5710 Pred = ICmpInst::ICMP_EQ;
5711 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005712 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005713 case FCmpInst::FCMP_OGT:
5714 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5715 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005716 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005717 case FCmpInst::FCMP_OGE:
5718 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5719 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005720 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005721 case FCmpInst::FCMP_OLT:
5722 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5723 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005724 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005725 case FCmpInst::FCMP_OLE:
5726 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5727 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005728 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005729 case FCmpInst::FCMP_ONE:
5730 Pred = ICmpInst::ICMP_NE;
5731 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005732 case FCmpInst::FCMP_ORD:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005733 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005734 case FCmpInst::FCMP_UNO:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005735 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005736 }
5737
5738 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5739
5740 // Now we know that the APFloat is a normal number, zero or inf.
5741
Chris Lattnerf13ff492008-05-20 03:50:52 +00005742 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005743 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005744 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005745
Bill Wendling20636df2008-11-09 04:26:50 +00005746 if (!LHSUnsigned) {
5747 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5748 // and large values.
5749 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5750 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5751 APFloat::rmNearestTiesToEven);
5752 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5753 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5754 Pred == ICmpInst::ICMP_SLE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005755 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5756 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005757 }
5758 } else {
5759 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5760 // +INF and large values.
5761 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5762 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5763 APFloat::rmNearestTiesToEven);
5764 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5765 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5766 Pred == ICmpInst::ICMP_ULE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005767 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5768 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005769 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005770 }
5771
Bill Wendling20636df2008-11-09 04:26:50 +00005772 if (!LHSUnsigned) {
5773 // See if the RHS value is < SignedMin.
5774 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5775 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5776 APFloat::rmNearestTiesToEven);
5777 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5778 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5779 Pred == ICmpInst::ICMP_SGE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005780 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5781 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005782 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005783 }
5784
Bill Wendling20636df2008-11-09 04:26:50 +00005785 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5786 // [0, UMAX], but it may still be fractional. See if it is fractional by
5787 // casting the FP value to the integer value and back, checking for equality.
5788 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005789 Constant *RHSInt = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005790 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5791 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005792 if (!RHS.isZero()) {
5793 bool Equal = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005794 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5795 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005796 if (!Equal) {
5797 // If we had a comparison against a fractional value, we have to adjust
5798 // the compare predicate and sometimes the value. RHSC is rounded towards
5799 // zero at this point.
5800 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005801 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng14118132009-05-22 23:10:53 +00005802 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005803 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005804 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00005805 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005806 case ICmpInst::ICMP_ULE:
5807 // (float)int <= 4.4 --> int <= 4
5808 // (float)int <= -4.4 --> false
5809 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005810 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005811 break;
5812 case ICmpInst::ICMP_SLE:
5813 // (float)int <= 4.4 --> int <= 4
5814 // (float)int <= -4.4 --> int < -4
5815 if (RHS.isNegative())
5816 Pred = ICmpInst::ICMP_SLT;
5817 break;
5818 case ICmpInst::ICMP_ULT:
5819 // (float)int < -4.4 --> false
5820 // (float)int < 4.4 --> int <= 4
5821 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005822 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005823 Pred = ICmpInst::ICMP_ULE;
5824 break;
5825 case ICmpInst::ICMP_SLT:
5826 // (float)int < -4.4 --> int < -4
5827 // (float)int < 4.4 --> int <= 4
5828 if (!RHS.isNegative())
5829 Pred = ICmpInst::ICMP_SLE;
5830 break;
5831 case ICmpInst::ICMP_UGT:
5832 // (float)int > 4.4 --> int > 4
5833 // (float)int > -4.4 --> true
5834 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005835 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005836 break;
5837 case ICmpInst::ICMP_SGT:
5838 // (float)int > 4.4 --> int > 4
5839 // (float)int > -4.4 --> int >= -4
5840 if (RHS.isNegative())
5841 Pred = ICmpInst::ICMP_SGE;
5842 break;
5843 case ICmpInst::ICMP_UGE:
5844 // (float)int >= -4.4 --> true
5845 // (float)int >= 4.4 --> int > 4
5846 if (!RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005847 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005848 Pred = ICmpInst::ICMP_UGT;
5849 break;
5850 case ICmpInst::ICMP_SGE:
5851 // (float)int >= -4.4 --> int >= -4
5852 // (float)int >= 4.4 --> int > 4
5853 if (!RHS.isNegative())
5854 Pred = ICmpInst::ICMP_SGT;
5855 break;
5856 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005857 }
5858 }
5859
5860 // Lower this FP comparison into an appropriate integer version of the
5861 // comparison.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005862 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00005863}
5864
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005865Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5866 bool Changed = SimplifyCompare(I);
5867 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5868
5869 // Fold trivial predicates.
5870 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005871 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005872 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005873 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005874
5875 // Simplify 'fcmp pred X, X'
5876 if (Op0 == Op1) {
5877 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005878 default: llvm_unreachable("Unknown predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005879 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5880 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5881 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson4f720fa2009-07-31 17:39:07 +00005882 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005883 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5884 case FCmpInst::FCMP_OLT: // True if ordered and less than
5885 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson4f720fa2009-07-31 17:39:07 +00005886 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005887
5888 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5889 case FCmpInst::FCMP_ULT: // True if unordered or less than
5890 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5891 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5892 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5893 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersonaac28372009-07-31 20:28:14 +00005894 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005895 return &I;
5896
5897 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5898 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5899 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5900 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5901 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5902 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersonaac28372009-07-31 20:28:14 +00005903 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005904 return &I;
5905 }
5906 }
5907
5908 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersonb99ecca2009-07-30 23:03:37 +00005909 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005910
5911 // Handle fcmp with constant RHS
5912 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005913 // If the constant is a nan, see if we can fold the comparison based on it.
5914 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5915 if (CFP->getValueAPF().isNaN()) {
5916 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson4f720fa2009-07-31 17:39:07 +00005917 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnerf13ff492008-05-20 03:50:52 +00005918 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5919 "Comparison must be either ordered or unordered!");
5920 // True if unordered.
Owen Anderson4f720fa2009-07-31 17:39:07 +00005921 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005922 }
5923 }
5924
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005925 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5926 switch (LHSI->getOpcode()) {
5927 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005928 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5929 // block. If in the same block, we're encouraging jump threading. If
5930 // not, we are just pessimizing the code by making an i1 phi.
5931 if (LHSI->getParent() == I.getParent())
5932 if (Instruction *NV = FoldOpIntoPhi(I))
5933 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005934 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005935 case Instruction::SIToFP:
5936 case Instruction::UIToFP:
5937 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5938 return NV;
5939 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005940 case Instruction::Select:
5941 // If either operand of the select is a constant, we can fold the
5942 // comparison into the select arms, which will cause one to be
5943 // constant folded and the select turned into a bitwise or.
5944 Value *Op1 = 0, *Op2 = 0;
5945 if (LHSI->hasOneUse()) {
5946 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5947 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005948 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005949 // Insert a new FCmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005950 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005951 LHSI->getOperand(2), RHSC,
5952 I.getName()), I);
5953 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5954 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005955 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005956 // Insert a new FCmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005957 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005958 LHSI->getOperand(1), RHSC,
5959 I.getName()), I);
5960 }
5961 }
5962
5963 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005964 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005965 break;
5966 }
5967 }
5968
5969 return Changed ? &I : 0;
5970}
5971
5972Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5973 bool Changed = SimplifyCompare(I);
5974 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5975 const Type *Ty = Op0->getType();
5976
5977 // icmp X, X
5978 if (Op0 == Op1)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005979 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005980 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005981
5982 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersonb99ecca2009-07-30 23:03:37 +00005983 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005984
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005985 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5986 // addresses never equal each other! We already know that Op0 != Op1.
5987 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5988 isa<ConstantPointerNull>(Op0)) &&
5989 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5990 isa<ConstantPointerNull>(Op1)))
Owen Andersoneacb44d2009-07-24 23:12:02 +00005991 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005992 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005993
5994 // icmp's with boolean values can always be turned into bitwise operations
5995 if (Ty == Type::Int1Ty) {
5996 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005997 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00005998 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005999 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006000 InsertNewInstBefore(Xor, I);
Dan Gohmancdff2122009-08-12 16:23:25 +00006001 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006002 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006003 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00006004 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006005
6006 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00006007 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006008 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006009 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Dan Gohmancdff2122009-08-12 16:23:25 +00006010 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006011 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00006012 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006013 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006014 case ICmpInst::ICMP_SGT:
6015 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006016 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006017 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Dan Gohmancdff2122009-08-12 16:23:25 +00006018 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006019 InsertNewInstBefore(Not, I);
6020 return BinaryOperator::CreateAnd(Not, Op0);
6021 }
6022 case ICmpInst::ICMP_UGE:
6023 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6024 // FALL THROUGH
6025 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Dan Gohmancdff2122009-08-12 16:23:25 +00006026 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006027 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00006028 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006029 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006030 case ICmpInst::ICMP_SGE:
6031 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6032 // FALL THROUGH
6033 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Dan Gohmancdff2122009-08-12 16:23:25 +00006034 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006035 InsertNewInstBefore(Not, I);
6036 return BinaryOperator::CreateOr(Not, Op0);
6037 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006038 }
6039 }
6040
Dan Gohman7934d592009-04-25 17:12:48 +00006041 unsigned BitWidth = 0;
6042 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00006043 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6044 else if (Ty->isIntOrIntVector())
6045 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00006046
6047 bool isSignBit = false;
6048
Dan Gohman58c09632008-09-16 18:46:06 +00006049 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006050 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00006051 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00006052
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006053 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6054 if (I.isEquality() && CI->isNullValue() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006055 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006056 // (icmp cond A B) if cond is equality
Owen Anderson6601fcd2009-07-09 23:48:35 +00006057 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00006058 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006059
Dan Gohman58c09632008-09-16 18:46:06 +00006060 // If we have an icmp le or icmp ge instruction, turn it into the
6061 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6062 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00006063 switch (I.getPredicate()) {
6064 default: break;
6065 case ICmpInst::ICMP_ULE:
6066 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006067 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson6601fcd2009-07-09 23:48:35 +00006068 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006069 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006070 case ICmpInst::ICMP_SLE:
6071 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006072 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson6601fcd2009-07-09 23:48:35 +00006073 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006074 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006075 case ICmpInst::ICMP_UGE:
6076 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006077 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson6601fcd2009-07-09 23:48:35 +00006078 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006079 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006080 case ICmpInst::ICMP_SGE:
6081 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006082 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson6601fcd2009-07-09 23:48:35 +00006083 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006084 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006085 }
6086
Chris Lattnera1308652008-07-11 05:40:05 +00006087 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006088 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006089 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006090 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6091 }
6092
6093 // See if we can fold the comparison based on range information we can get
6094 // by checking whether bits are known to be zero or one in the input.
6095 if (BitWidth != 0) {
6096 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6097 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6098
6099 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006100 isSignBit ? APInt::getSignBit(BitWidth)
6101 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006102 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006103 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006104 if (SimplifyDemandedBits(I.getOperandUse(1),
6105 APInt::getAllOnesValue(BitWidth),
6106 Op1KnownZero, Op1KnownOne, 0))
6107 return &I;
6108
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006109 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006110 // in. Compute the Min, Max and RHS values based on the known bits. For the
6111 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006112 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6113 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6114 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6115 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6116 Op0Min, Op0Max);
6117 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6118 Op1Min, Op1Max);
6119 } else {
6120 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6121 Op0Min, Op0Max);
6122 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6123 Op1Min, Op1Max);
6124 }
6125
Chris Lattnera1308652008-07-11 05:40:05 +00006126 // If Min and Max are known to be the same, then SimplifyDemandedBits
6127 // figured out that the LHS is a constant. Just constant fold this now so
6128 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006129 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006130 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006131 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006132 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006133 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006134 ConstantInt::get(*Context, Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006135
Chris Lattnera1308652008-07-11 05:40:05 +00006136 // Based on the range information we know about the LHS, see if we can
6137 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006138 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006139 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner62d0f232008-07-11 05:08:55 +00006140 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006141 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006142 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006143 break;
6144 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006145 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006146 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006147 break;
6148 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006149 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006150 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006151 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006152 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006153 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006154 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006155 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6156 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006157 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006158 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006159
6160 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6161 if (CI->isMinValue(true))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006162 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006163 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006164 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006165 break;
6166 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006167 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006168 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006169 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006170 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006171
6172 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006173 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006174 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6175 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006176 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006177 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006178
6179 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6180 if (CI->isMaxValue(true))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006181 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006182 Constant::getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006183 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006184 break;
6185 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006186 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006187 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006188 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006189 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006190 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006191 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006192 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6193 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006194 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006195 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006196 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006197 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006198 case ICmpInst::ICMP_SGT:
6199 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006200 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006201 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006202 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006203
6204 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006205 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006206 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6207 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006208 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006209 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006210 }
6211 break;
6212 case ICmpInst::ICMP_SGE:
6213 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6214 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006215 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006216 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006217 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006218 break;
6219 case ICmpInst::ICMP_SLE:
6220 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6221 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006222 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006223 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006224 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006225 break;
6226 case ICmpInst::ICMP_UGE:
6227 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6228 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006229 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006230 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006231 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006232 break;
6233 case ICmpInst::ICMP_ULE:
6234 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6235 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006236 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006237 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006238 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006239 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006240 }
Dan Gohman7934d592009-04-25 17:12:48 +00006241
6242 // Turn a signed comparison into an unsigned one if both operands
6243 // are known to have the same sign.
6244 if (I.isSignedPredicate() &&
6245 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6246 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006247 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006248 }
6249
6250 // Test if the ICmpInst instruction is used exclusively by a select as
6251 // part of a minimum or maximum operation. If so, refrain from doing
6252 // any other folding. This helps out other analyses which understand
6253 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6254 // and CodeGen. And in this case, at least one of the comparison
6255 // operands has at least one user besides the compare (the select),
6256 // which would often largely negate the benefit of folding anyway.
6257 if (I.hasOneUse())
6258 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6259 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6260 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6261 return 0;
6262
6263 // See if we are doing a comparison between a constant and an instruction that
6264 // can be folded into the comparison.
6265 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006266 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6267 // instruction, see if that instruction also has constants so that the
6268 // instruction can be folded into the icmp
6269 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6270 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6271 return Res;
6272 }
6273
6274 // Handle icmp with constant (but not simple integer constant) RHS
6275 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6276 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6277 switch (LHSI->getOpcode()) {
6278 case Instruction::GetElementPtr:
6279 if (RHSC->isNullValue()) {
6280 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6281 bool isAllZeros = true;
6282 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6283 if (!isa<Constant>(LHSI->getOperand(i)) ||
6284 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6285 isAllZeros = false;
6286 break;
6287 }
6288 if (isAllZeros)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006289 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersonaac28372009-07-31 20:28:14 +00006290 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006291 }
6292 break;
6293
6294 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00006295 // Only fold icmp into the PHI if the phi and fcmp are in the same
6296 // block. If in the same block, we're encouraging jump threading. If
6297 // not, we are just pessimizing the code by making an i1 phi.
6298 if (LHSI->getParent() == I.getParent())
6299 if (Instruction *NV = FoldOpIntoPhi(I))
6300 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006301 break;
6302 case Instruction::Select: {
6303 // If either operand of the select is a constant, we can fold the
6304 // comparison into the select arms, which will cause one to be
6305 // constant folded and the select turned into a bitwise or.
6306 Value *Op1 = 0, *Op2 = 0;
6307 if (LHSI->hasOneUse()) {
6308 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6309 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006310 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006311 // Insert a new ICmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00006312 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006313 LHSI->getOperand(2), RHSC,
6314 I.getName()), I);
6315 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6316 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006317 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006318 // Insert a new ICmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00006319 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006320 LHSI->getOperand(1), RHSC,
6321 I.getName()), I);
6322 }
6323 }
6324
6325 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006326 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006327 break;
6328 }
6329 case Instruction::Malloc:
6330 // If we have (malloc != null), and if the malloc has a single use, we
6331 // can assume it is successful and remove the malloc.
6332 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6333 AddToWorkList(LHSI);
Owen Andersoneacb44d2009-07-24 23:12:02 +00006334 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00006335 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006336 }
6337 break;
6338 }
6339 }
6340
6341 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohman17f46f72009-07-28 01:40:03 +00006342 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006343 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6344 return NI;
Dan Gohman17f46f72009-07-28 01:40:03 +00006345 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006346 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6347 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6348 return NI;
6349
6350 // Test to see if the operands of the icmp are casted versions of other
6351 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6352 // now.
6353 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6354 if (isa<PointerType>(Op0->getType()) &&
6355 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6356 // We keep moving the cast from the left operand over to the right
6357 // operand, where it can often be eliminated completely.
6358 Op0 = CI->getOperand(0);
6359
6360 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6361 // so eliminate it as well.
6362 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6363 Op1 = CI2->getOperand(0);
6364
6365 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006366 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006367 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00006368 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006369 } else {
6370 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006371 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006372 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006373 }
Owen Anderson6601fcd2009-07-09 23:48:35 +00006374 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006375 }
6376 }
6377
6378 if (isa<CastInst>(Op0)) {
6379 // Handle the special case of: icmp (cast bool to X), <cst>
6380 // This comes up when you have code like
6381 // int X = A < B;
6382 // if (X) ...
6383 // For generality, we handle any zero-extension of any operand comparison
6384 // with a constant or another cast from the same type.
6385 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6386 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6387 return R;
6388 }
6389
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006390 // See if it's the same type of instruction on the left and right.
6391 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6392 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006393 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006394 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006395 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006396 default: break;
6397 case Instruction::Add:
6398 case Instruction::Sub:
6399 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006400 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson6601fcd2009-07-09 23:48:35 +00006401 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006402 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006403 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6404 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6405 if (CI->getValue().isSignBit()) {
6406 ICmpInst::Predicate Pred = I.isSignedPredicate()
6407 ? I.getUnsignedPredicate()
6408 : I.getSignedPredicate();
Owen Anderson6601fcd2009-07-09 23:48:35 +00006409 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006410 Op1I->getOperand(0));
6411 }
6412
6413 if (CI->getValue().isMaxSignedValue()) {
6414 ICmpInst::Predicate Pred = I.isSignedPredicate()
6415 ? I.getUnsignedPredicate()
6416 : I.getSignedPredicate();
6417 Pred = I.getSwappedPredicate(Pred);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006418 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006419 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006420 }
6421 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006422 break;
6423 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006424 if (!I.isEquality())
6425 break;
6426
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006427 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6428 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6429 // Mask = -1 >> count-trailing-zeros(Cst).
6430 if (!CI->isZero() && !CI->isOne()) {
6431 const APInt &AP = CI->getValue();
Owen Andersoneacb44d2009-07-24 23:12:02 +00006432 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006433 APInt::getLowBitsSet(AP.getBitWidth(),
6434 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006435 AP.countTrailingZeros()));
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006436 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6437 Mask);
6438 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6439 Mask);
6440 InsertNewInstBefore(And1, I);
6441 InsertNewInstBefore(And2, I);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006442 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006443 }
6444 }
6445 break;
6446 }
6447 }
6448 }
6449 }
6450
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006451 // ~x < ~y --> y < x
6452 { Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00006453 if (match(Op0, m_Not(m_Value(A))) &&
6454 match(Op1, m_Not(m_Value(B))))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006455 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006456 }
6457
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006458 if (I.isEquality()) {
6459 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006460
6461 // -x == -y --> x == y
Dan Gohmancdff2122009-08-12 16:23:25 +00006462 if (match(Op0, m_Neg(m_Value(A))) &&
6463 match(Op1, m_Neg(m_Value(B))))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006464 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006465
Dan Gohmancdff2122009-08-12 16:23:25 +00006466 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006467 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6468 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson6601fcd2009-07-09 23:48:35 +00006469 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006470 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006471 }
6472
Dan Gohmancdff2122009-08-12 16:23:25 +00006473 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006474 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006475 ConstantInt *C1, *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00006476 if (match(B, m_ConstantInt(C1)) &&
6477 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006478 Constant *NC =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006479 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner3b874082008-11-16 05:38:51 +00006480 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson6601fcd2009-07-09 23:48:35 +00006481 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattner3b874082008-11-16 05:38:51 +00006482 InsertNewInstBefore(Xor, I));
6483 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006484
6485 // A^B == A^D -> B == D
Owen Anderson6601fcd2009-07-09 23:48:35 +00006486 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6487 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6488 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6489 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006490 }
6491 }
6492
Dan Gohmancdff2122009-08-12 16:23:25 +00006493 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006494 (A == Op0 || B == Op0)) {
6495 // A == (A^B) -> B == 0
6496 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson6601fcd2009-07-09 23:48:35 +00006497 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006498 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006499 }
Chris Lattner3b874082008-11-16 05:38:51 +00006500
6501 // (A-B) == A -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006502 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006503 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006504 Constant::getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006505
6506 // A == (A-B) -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006507 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006508 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006509 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006510
6511 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6512 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006513 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6514 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006515 Value *X = 0, *Y = 0, *Z = 0;
6516
6517 if (A == C) {
6518 X = B; Y = D; Z = A;
6519 } else if (A == D) {
6520 X = B; Y = C; Z = A;
6521 } else if (B == C) {
6522 X = A; Y = D; Z = B;
6523 } else if (B == D) {
6524 X = A; Y = C; Z = B;
6525 }
6526
6527 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00006528 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6529 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006530 I.setOperand(0, Op1);
Owen Andersonaac28372009-07-31 20:28:14 +00006531 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006532 return &I;
6533 }
6534 }
6535 }
6536 return Changed ? &I : 0;
6537}
6538
6539
6540/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6541/// and CmpRHS are both known to be integer constants.
6542Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6543 ConstantInt *DivRHS) {
6544 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6545 const APInt &CmpRHSV = CmpRHS->getValue();
6546
6547 // FIXME: If the operand types don't match the type of the divide
6548 // then don't attempt this transform. The code below doesn't have the
6549 // logic to deal with a signed divide and an unsigned compare (and
6550 // vice versa). This is because (x /s C1) <s C2 produces different
6551 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6552 // (x /u C1) <u C2. Simply casting the operands and result won't
6553 // work. :( The if statement below tests that condition and bails
6554 // if it finds it.
6555 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6556 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6557 return 0;
6558 if (DivRHS->isZero())
6559 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006560 if (DivIsSigned && DivRHS->isAllOnesValue())
6561 return 0; // The overflow computation also screws up here
6562 if (DivRHS->isOne())
6563 return 0; // Not worth bothering, and eliminates some funny cases
6564 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006565
6566 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6567 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6568 // C2 (CI). By solving for X we can turn this into a range check
6569 // instead of computing a divide.
Owen Anderson02b48c32009-07-29 18:55:55 +00006570 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006571
6572 // Determine if the product overflows by seeing if the product is
6573 // not equal to the divide. Make sure we do the same kind of divide
6574 // as in the LHS instruction that we're folding.
Owen Anderson02b48c32009-07-29 18:55:55 +00006575 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6576 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006577
6578 // Get the ICmp opcode
6579 ICmpInst::Predicate Pred = ICI.getPredicate();
6580
6581 // Figure out the interval that is being checked. For example, a comparison
6582 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6583 // Compute this interval based on the constants involved and the signedness of
6584 // the compare/divide. This computes a half-open interval, keeping track of
6585 // whether either value in the interval overflows. After analysis each
6586 // overflow variable is set to 0 if it's corresponding bound variable is valid
6587 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6588 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006589 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006590
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006591 if (!DivIsSigned) { // udiv
6592 // e.g. X/5 op 3 --> [15, 20)
6593 LoBound = Prod;
6594 HiOverflow = LoOverflow = ProdOV;
6595 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006596 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006597 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006598 if (CmpRHSV == 0) { // (X / pos) op 0
6599 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006600 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006601 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006602 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006603 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6604 HiOverflow = LoOverflow = ProdOV;
6605 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006606 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006607 } else { // (X / pos) op neg
6608 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006609 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006610 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6611 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006612 ConstantInt* DivNeg =
Owen Anderson02b48c32009-07-29 18:55:55 +00006613 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Anderson24be4c12009-07-03 00:17:18 +00006614 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006615 true) ? -1 : 0;
6616 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006617 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006618 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006619 if (CmpRHSV == 0) { // (X / neg) op 0
6620 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006621 LoBound = AddOne(DivRHS);
Owen Anderson02b48c32009-07-29 18:55:55 +00006622 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006623 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6624 HiOverflow = 1; // [INTMIN+1, overflow)
6625 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6626 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006627 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006628 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006629 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006630 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6631 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006632 LoOverflow = AddWithOverflow(LoBound, HiBound,
6633 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006634 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006635 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6636 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006637 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006638 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006639 }
6640
6641 // Dividing by a negative swaps the condition. LT <-> GT
6642 Pred = ICmpInst::getSwappedPredicate(Pred);
6643 }
6644
6645 Value *X = DivI->getOperand(0);
6646 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006647 default: llvm_unreachable("Unhandled icmp opcode!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006648 case ICmpInst::ICMP_EQ:
6649 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006650 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006651 else if (HiOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006652 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006653 ICmpInst::ICMP_UGE, X, LoBound);
6654 else if (LoOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006655 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006656 ICmpInst::ICMP_ULT, X, HiBound);
6657 else
6658 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6659 case ICmpInst::ICMP_NE:
6660 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006661 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006662 else if (HiOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006663 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006664 ICmpInst::ICMP_ULT, X, LoBound);
6665 else if (LoOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006666 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006667 ICmpInst::ICMP_UGE, X, HiBound);
6668 else
6669 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6670 case ICmpInst::ICMP_ULT:
6671 case ICmpInst::ICMP_SLT:
6672 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006673 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006674 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006675 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Owen Anderson6601fcd2009-07-09 23:48:35 +00006676 return new ICmpInst(*Context, Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006677 case ICmpInst::ICMP_UGT:
6678 case ICmpInst::ICMP_SGT:
6679 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006680 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006681 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006682 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006683 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006684 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006685 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00006686 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006687 }
6688}
6689
6690
6691/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6692///
6693Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6694 Instruction *LHSI,
6695 ConstantInt *RHS) {
6696 const APInt &RHSV = RHS->getValue();
6697
6698 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006699 case Instruction::Trunc:
6700 if (ICI.isEquality() && LHSI->hasOneUse()) {
6701 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6702 // of the high bits truncated out of x are known.
6703 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6704 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6705 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6706 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6707 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6708
6709 // If all the high bits are known, we can do this xform.
6710 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6711 // Pull in the high bits from known-ones set.
6712 APInt NewRHS(RHS->getValue());
6713 NewRHS.zext(SrcBits);
6714 NewRHS |= KnownOne;
Owen Anderson6601fcd2009-07-09 23:48:35 +00006715 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006716 ConstantInt::get(*Context, NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00006717 }
6718 }
6719 break;
6720
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006721 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6722 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6723 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6724 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006725 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6726 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006727 Value *CompareVal = LHSI->getOperand(0);
6728
6729 // If the sign bit of the XorCST is not set, there is no change to
6730 // the operation, just stop using the Xor.
6731 if (!XorCST->getValue().isNegative()) {
6732 ICI.setOperand(0, CompareVal);
6733 AddToWorkList(LHSI);
6734 return &ICI;
6735 }
6736
6737 // Was the old condition true if the operand is positive?
6738 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6739
6740 // If so, the new one isn't.
6741 isTrueIfPositive ^= true;
6742
6743 if (isTrueIfPositive)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006744 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006745 SubOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006746 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00006747 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006748 AddOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006749 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006750
6751 if (LHSI->hasOneUse()) {
6752 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6753 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6754 const APInt &SignBit = XorCST->getValue();
6755 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6756 ? ICI.getUnsignedPredicate()
6757 : ICI.getSignedPredicate();
Owen Anderson6601fcd2009-07-09 23:48:35 +00006758 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006759 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006760 }
6761
6762 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006763 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006764 const APInt &NotSignBit = XorCST->getValue();
6765 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6766 ? ICI.getUnsignedPredicate()
6767 : ICI.getSignedPredicate();
6768 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006769 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006770 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006771 }
6772 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006773 }
6774 break;
6775 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6776 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6777 LHSI->getOperand(0)->hasOneUse()) {
6778 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6779
6780 // If the LHS is an AND of a truncating cast, we can widen the
6781 // and/compare to be the input width without changing the value
6782 // produced, eliminating a cast.
6783 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6784 // We can do this transformation if either the AND constant does not
6785 // have its sign bit set or if it is an equality comparison.
6786 // Extending a relational comparison when we're checking the sign
6787 // bit would not work.
6788 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006789 (ICI.isEquality() ||
6790 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006791 uint32_t BitWidth =
6792 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6793 APInt NewCST = AndCST->getValue();
6794 NewCST.zext(BitWidth);
6795 APInt NewCI = RHSV;
6796 NewCI.zext(BitWidth);
6797 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006798 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006799 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006800 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006801 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006802 ConstantInt::get(*Context, NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006803 }
6804 }
6805
6806 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6807 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6808 // happens a LOT in code produced by the C front-end, for bitfield
6809 // access.
6810 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6811 if (Shift && !Shift->isShift())
6812 Shift = 0;
6813
6814 ConstantInt *ShAmt;
6815 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6816 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6817 const Type *AndTy = AndCST->getType(); // Type of the and.
6818
6819 // We can fold this as long as we can't shift unknown bits
6820 // into the mask. This can only happen with signed shift
6821 // rights, as they sign-extend.
6822 if (ShAmt) {
6823 bool CanFold = Shift->isLogicalShift();
6824 if (!CanFold) {
6825 // To test for the bad case of the signed shr, see if any
6826 // of the bits shifted in could be tested after the mask.
6827 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6828 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6829
6830 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6831 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6832 AndCST->getValue()) == 0)
6833 CanFold = true;
6834 }
6835
6836 if (CanFold) {
6837 Constant *NewCst;
6838 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006839 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006840 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006841 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006842
6843 // Check to see if we are shifting out any of the bits being
6844 // compared.
Owen Anderson02b48c32009-07-29 18:55:55 +00006845 if (ConstantExpr::get(Shift->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00006846 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006847 // If we shifted bits out, the fold is not going to work out.
6848 // As a special case, check to see if this means that the
6849 // result is always true or false now.
6850 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006851 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006852 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006853 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006854 } else {
6855 ICI.setOperand(1, NewCst);
6856 Constant *NewAndCST;
6857 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006858 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006859 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006860 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006861 LHSI->setOperand(1, NewAndCST);
6862 LHSI->setOperand(0, Shift->getOperand(0));
6863 AddToWorkList(Shift); // Shift is dead.
6864 AddUsesToWorkList(ICI);
6865 return &ICI;
6866 }
6867 }
6868 }
6869
6870 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6871 // preferable because it allows the C<<Y expression to be hoisted out
6872 // of a loop if Y is invariant and X is not.
6873 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00006874 ICI.isEquality() && !Shift->isArithmeticShift() &&
6875 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006876 // Compute C << Y.
6877 Value *NS;
6878 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006879 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006880 Shift->getOperand(1), "tmp");
6881 } else {
6882 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006883 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006884 Shift->getOperand(1), "tmp");
6885 }
6886 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6887
6888 // Compute X & (C << Y).
6889 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006890 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006891 InsertNewInstBefore(NewAnd, ICI);
6892
6893 ICI.setOperand(0, NewAnd);
6894 return &ICI;
6895 }
6896 }
6897 break;
6898
6899 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6900 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6901 if (!ShAmt) break;
6902
6903 uint32_t TypeBits = RHSV.getBitWidth();
6904
6905 // Check that the shift amount is in range. If not, don't perform
6906 // undefined shifts. When the shift is visited it will be
6907 // simplified.
6908 if (ShAmt->uge(TypeBits))
6909 break;
6910
6911 if (ICI.isEquality()) {
6912 // If we are comparing against bits always shifted out, the
6913 // comparison cannot succeed.
6914 Constant *Comp =
Owen Anderson02b48c32009-07-29 18:55:55 +00006915 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Anderson24be4c12009-07-03 00:17:18 +00006916 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006917 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6918 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneacb44d2009-07-24 23:12:02 +00006919 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006920 return ReplaceInstUsesWith(ICI, Cst);
6921 }
6922
6923 if (LHSI->hasOneUse()) {
6924 // Otherwise strength reduce the shift into an and.
6925 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6926 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006927 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Anderson24be4c12009-07-03 00:17:18 +00006928 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006929
6930 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006931 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006932 Mask, LHSI->getName()+".mask");
6933 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006934 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006935 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006936 }
6937 }
6938
6939 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6940 bool TrueIfSigned = false;
6941 if (LHSI->hasOneUse() &&
6942 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6943 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneacb44d2009-07-24 23:12:02 +00006944 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006945 (TypeBits-ShAmt->getZExtValue()-1));
6946 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006947 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006948 Mask, LHSI->getName()+".mask");
6949 Value *And = InsertNewInstBefore(AndI, ICI);
6950
Owen Anderson6601fcd2009-07-09 23:48:35 +00006951 return new ICmpInst(*Context,
6952 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00006953 And, Constant::getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006954 }
6955 break;
6956 }
6957
6958 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6959 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006960 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006961 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006962 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006963
Chris Lattner5ee84f82008-03-21 05:19:58 +00006964 // Check that the shift amount is in range. If not, don't perform
6965 // undefined shifts. When the shift is visited it will be
6966 // simplified.
6967 uint32_t TypeBits = RHSV.getBitWidth();
6968 if (ShAmt->uge(TypeBits))
6969 break;
6970
6971 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006972
Chris Lattner5ee84f82008-03-21 05:19:58 +00006973 // If we are comparing against bits always shifted out, the
6974 // comparison cannot succeed.
6975 APInt Comp = RHSV << ShAmtVal;
6976 if (LHSI->getOpcode() == Instruction::LShr)
6977 Comp = Comp.lshr(ShAmtVal);
6978 else
6979 Comp = Comp.ashr(ShAmtVal);
6980
6981 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6982 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneacb44d2009-07-24 23:12:02 +00006983 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00006984 return ReplaceInstUsesWith(ICI, Cst);
6985 }
6986
6987 // Otherwise, check to see if the bits shifted out are known to be zero.
6988 // If so, we can compare against the unshifted value:
6989 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006990 if (LHSI->hasOneUse() &&
6991 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006992 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00006993 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00006994 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006995 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006996
Evan Chengfb9292a2008-04-23 00:38:06 +00006997 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006998 // Otherwise strength reduce the shift into an and.
6999 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007000 Constant *Mask = ConstantInt::get(*Context, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007001
Chris Lattner5ee84f82008-03-21 05:19:58 +00007002 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00007003 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007004 Mask, LHSI->getName()+".mask");
7005 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007006 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Anderson02b48c32009-07-29 18:55:55 +00007007 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007008 }
7009 break;
7010 }
7011
7012 case Instruction::SDiv:
7013 case Instruction::UDiv:
7014 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7015 // Fold this div into the comparison, producing a range check.
7016 // Determine, based on the divide type, what the range is being
7017 // checked. If there is an overflow on the low or high side, remember
7018 // it, otherwise compute the range [low, hi) bounding the new value.
7019 // See: InsertRangeTest above for the kinds of replacements possible.
7020 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7021 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7022 DivRHS))
7023 return R;
7024 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007025
7026 case Instruction::Add:
7027 // Fold: icmp pred (add, X, C1), C2
7028
7029 if (!ICI.isEquality()) {
7030 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7031 if (!LHSC) break;
7032 const APInt &LHSV = LHSC->getValue();
7033
7034 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7035 .subtract(LHSV);
7036
7037 if (ICI.isSignedPredicate()) {
7038 if (CR.getLower().isSignBit()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007039 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007040 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007041 } else if (CR.getUpper().isSignBit()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007042 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007043 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007044 }
7045 } else {
7046 if (CR.getLower().isMinValue()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007047 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007048 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007049 } else if (CR.getUpper().isMinValue()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007050 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007051 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007052 }
7053 }
7054 }
7055 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007056 }
7057
7058 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7059 if (ICI.isEquality()) {
7060 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7061
7062 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7063 // the second operand is a constant, simplify a bit.
7064 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7065 switch (BO->getOpcode()) {
7066 case Instruction::SRem:
7067 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7068 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7069 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7070 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7071 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00007072 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007073 BO->getName());
7074 InsertNewInstBefore(NewRem, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007075 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersonaac28372009-07-31 20:28:14 +00007076 Constant::getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007077 }
7078 }
7079 break;
7080 case Instruction::Add:
7081 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7082 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7083 if (BO->hasOneUse())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007084 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007085 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007086 } else if (RHSV == 0) {
7087 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7088 // efficiently invertible, or if the add has just this one use.
7089 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7090
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007091 if (Value *NegVal = dyn_castNegVal(BOp1))
Owen Anderson6601fcd2009-07-09 23:48:35 +00007092 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007093 else if (Value *NegVal = dyn_castNegVal(BOp0))
Owen Anderson6601fcd2009-07-09 23:48:35 +00007094 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007095 else if (BO->hasOneUse()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00007096 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007097 InsertNewInstBefore(Neg, ICI);
7098 Neg->takeName(BO);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007099 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007100 }
7101 }
7102 break;
7103 case Instruction::Xor:
7104 // For the xor case, we can xor two constants together, eliminating
7105 // the explicit xor.
7106 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson6601fcd2009-07-09 23:48:35 +00007107 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007108 ConstantExpr::getXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007109
7110 // FALLTHROUGH
7111 case Instruction::Sub:
7112 // Replace (([sub|xor] A, B) != 0) with (A != B)
7113 if (RHSV == 0)
Owen Anderson6601fcd2009-07-09 23:48:35 +00007114 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007115 BO->getOperand(1));
7116 break;
7117
7118 case Instruction::Or:
7119 // If bits are being or'd in that are not present in the constant we
7120 // are comparing against, then the comparison could never succeed!
7121 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007122 Constant *NotCI = ConstantExpr::getNot(RHS);
7123 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00007124 return ReplaceInstUsesWith(ICI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007125 ConstantInt::get(Type::Int1Ty,
Owen Anderson24be4c12009-07-03 00:17:18 +00007126 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007127 }
7128 break;
7129
7130 case Instruction::And:
7131 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7132 // If bits are being compared against that are and'd out, then the
7133 // comparison can never succeed!
7134 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007135 return ReplaceInstUsesWith(ICI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007136 ConstantInt::get(Type::Int1Ty,
Owen Anderson24be4c12009-07-03 00:17:18 +00007137 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007138
7139 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7140 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007141 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007142 ICmpInst::ICMP_NE, LHSI,
Owen Andersonaac28372009-07-31 20:28:14 +00007143 Constant::getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007144
7145 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007146 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007147 Value *X = BO->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +00007148 Constant *Zero = Constant::getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007149 ICmpInst::Predicate pred = isICMP_NE ?
7150 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson6601fcd2009-07-09 23:48:35 +00007151 return new ICmpInst(*Context, pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007152 }
7153
7154 // ((X & ~7) == 0) --> X < 8
7155 if (RHSV == 0 && isHighOnes(BOC)) {
7156 Value *X = BO->getOperand(0);
Owen Anderson02b48c32009-07-29 18:55:55 +00007157 Constant *NegX = ConstantExpr::getNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007158 ICmpInst::Predicate pred = isICMP_NE ?
7159 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson6601fcd2009-07-09 23:48:35 +00007160 return new ICmpInst(*Context, pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007161 }
7162 }
7163 default: break;
7164 }
7165 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7166 // Handle icmp {eq|ne} <intrinsic>, intcst.
7167 if (II->getIntrinsicID() == Intrinsic::bswap) {
7168 AddToWorkList(II);
7169 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007170 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007171 return &ICI;
7172 }
7173 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007174 }
7175 return 0;
7176}
7177
7178/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7179/// We only handle extending casts so far.
7180///
7181Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7182 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7183 Value *LHSCIOp = LHSCI->getOperand(0);
7184 const Type *SrcTy = LHSCIOp->getType();
7185 const Type *DestTy = LHSCI->getType();
7186 Value *RHSCIOp;
7187
7188 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7189 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007190 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7191 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007192 cast<IntegerType>(DestTy)->getBitWidth()) {
7193 Value *RHSOp = 0;
7194 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007195 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007196 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7197 RHSOp = RHSC->getOperand(0);
7198 // If the pointer types don't match, insert a bitcast.
7199 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00007200 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007201 }
7202
7203 if (RHSOp)
Owen Anderson6601fcd2009-07-09 23:48:35 +00007204 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007205 }
7206
7207 // The code below only handles extension cast instructions, so far.
7208 // Enforce this.
7209 if (LHSCI->getOpcode() != Instruction::ZExt &&
7210 LHSCI->getOpcode() != Instruction::SExt)
7211 return 0;
7212
7213 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7214 bool isSignedCmp = ICI.isSignedPredicate();
7215
7216 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7217 // Not an extension from the same type?
7218 RHSCIOp = CI->getOperand(0);
7219 if (RHSCIOp->getType() != LHSCIOp->getType())
7220 return 0;
7221
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007222 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007223 // and the other is a zext), then we can't handle this.
7224 if (CI->getOpcode() != LHSCI->getOpcode())
7225 return 0;
7226
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007227 // Deal with equality cases early.
7228 if (ICI.isEquality())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007229 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007230
7231 // A signed comparison of sign extended values simplifies into a
7232 // signed comparison.
7233 if (isSignedCmp && isSignedExt)
Owen Anderson6601fcd2009-07-09 23:48:35 +00007234 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007235
7236 // The other three cases all fold into an unsigned comparison.
Owen Anderson6601fcd2009-07-09 23:48:35 +00007237 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007238 }
7239
7240 // If we aren't dealing with a constant on the RHS, exit early
7241 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7242 if (!CI)
7243 return 0;
7244
7245 // Compute the constant that would happen if we truncated to SrcTy then
7246 // reextended to DestTy.
Owen Anderson02b48c32009-07-29 18:55:55 +00007247 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7248 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007249 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007250
7251 // If the re-extended constant didn't change...
7252 if (Res2 == CI) {
7253 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7254 // For example, we might have:
Dan Gohman9e1657f2009-06-14 23:30:43 +00007255 // %A = sext i16 %X to i32
7256 // %B = icmp ugt i32 %A, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007257 // It is incorrect to transform this into
Dan Gohman9e1657f2009-06-14 23:30:43 +00007258 // %B = icmp ugt i16 %X, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007259 // because %A may have negative value.
7260 //
Chris Lattner3d816532008-07-11 04:09:09 +00007261 // However, we allow this when the compare is EQ/NE, because they are
7262 // signless.
7263 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007264 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00007265 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007266 }
7267
7268 // The re-extended constant changed so the constant cannot be represented
7269 // in the shorter type. Consequently, we cannot emit a simple comparison.
7270
7271 // First, handle some easy cases. We know the result cannot be equal at this
7272 // point so handle the ICI.isEquality() cases
7273 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007274 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007275 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007276 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007277
7278 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7279 // should have been folded away previously and not enter in here.
7280 Value *Result;
7281 if (isSignedCmp) {
7282 // We're performing a signed comparison.
7283 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00007284 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007285 else
Owen Anderson4f720fa2009-07-31 17:39:07 +00007286 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007287 } else {
7288 // We're performing an unsigned comparison.
7289 if (isSignedExt) {
7290 // We're performing an unsigned comp with a sign extended value.
7291 // This is true if the input is >= 0. [aka >s -1]
Owen Andersonaac28372009-07-31 20:28:14 +00007292 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007293 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7294 LHSCIOp, NegOne, ICI.getName()), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007295 } else {
7296 // Unsigned extend & unsigned compare -> always true.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007297 Result = ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007298 }
7299 }
7300
7301 // Finally, return the value computed.
7302 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007303 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007304 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007305
7306 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7307 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7308 "ICmp should be folded!");
7309 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00007310 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohmancdff2122009-08-12 16:23:25 +00007311 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007312}
7313
7314Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7315 return commonShiftTransforms(I);
7316}
7317
7318Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7319 return commonShiftTransforms(I);
7320}
7321
7322Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007323 if (Instruction *R = commonShiftTransforms(I))
7324 return R;
7325
7326 Value *Op0 = I.getOperand(0);
7327
7328 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7329 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7330 if (CSI->isAllOnesValue())
7331 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007332
Dan Gohman2526aea2009-06-16 19:55:29 +00007333 // See if we can turn a signed shr into an unsigned shr.
7334 if (MaskedValueIsZero(Op0,
7335 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7336 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7337
7338 // Arithmetic shifting an all-sign-bit value is a no-op.
7339 unsigned NumSignBits = ComputeNumSignBits(Op0);
7340 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7341 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007342
Chris Lattnere3c504f2007-12-06 01:59:46 +00007343 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007344}
7345
7346Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7347 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7348 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7349
7350 // shl X, 0 == X and shr X, 0 == X
7351 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00007352 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7353 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007354 return ReplaceInstUsesWith(I, Op0);
7355
7356 if (isa<UndefValue>(Op0)) {
7357 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7358 return ReplaceInstUsesWith(I, Op0);
7359 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007360 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007361 }
7362 if (isa<UndefValue>(Op1)) {
7363 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7364 return ReplaceInstUsesWith(I, Op0);
7365 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007366 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007367 }
7368
Dan Gohman2bc21562009-05-21 02:28:33 +00007369 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007370 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007371 return &I;
7372
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007373 // Try to fold constant and into select arguments.
7374 if (isa<Constant>(Op0))
7375 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7376 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7377 return R;
7378
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007379 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7380 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7381 return Res;
7382 return 0;
7383}
7384
7385Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7386 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007387 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007388
7389 // See if we can simplify any instructions used by the instruction whose sole
7390 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007391 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007392
Dan Gohman9e1657f2009-06-14 23:30:43 +00007393 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7394 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007395 //
7396 if (Op1->uge(TypeBits)) {
7397 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007398 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007399 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007400 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007401 return &I;
7402 }
7403 }
7404
7405 // ((X*C1) << C2) == (X * (C1 << C2))
7406 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7407 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7408 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007409 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007410 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007411
7412 // Try to fold constant and into select arguments.
7413 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7414 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7415 return R;
7416 if (isa<PHINode>(Op0))
7417 if (Instruction *NV = FoldOpIntoPhi(I))
7418 return NV;
7419
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007420 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7421 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7422 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7423 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7424 // place. Don't try to do this transformation in this case. Also, we
7425 // require that the input operand is a shift-by-constant so that we have
7426 // confidence that the shifts will get folded together. We could do this
7427 // xform in more cases, but it is unlikely to be profitable.
7428 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7429 isa<ConstantInt>(TrOp->getOperand(1))) {
7430 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00007431 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00007432 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007433 I.getName());
7434 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7435
7436 // For logical shifts, the truncation has the effect of making the high
7437 // part of the register be zeros. Emulate this by inserting an AND to
7438 // clear the top bits as needed. This 'and' will usually be zapped by
7439 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007440 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7441 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007442 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7443
7444 // The mask we constructed says what the trunc would do if occurring
7445 // between the shifts. We want to know the effect *after* the second
7446 // shift. We know that it is a logical shift by a constant, so adjust the
7447 // mask as appropriate.
7448 if (I.getOpcode() == Instruction::Shl)
7449 MaskV <<= Op1->getZExtValue();
7450 else {
7451 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7452 MaskV = MaskV.lshr(Op1->getZExtValue());
7453 }
7454
Owen Anderson24be4c12009-07-03 00:17:18 +00007455 Instruction *And =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007456 BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
Owen Anderson24be4c12009-07-03 00:17:18 +00007457 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007458 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7459
7460 // Return the value truncated to the interesting size.
7461 return new TruncInst(And, I.getType());
7462 }
7463 }
7464
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007465 if (Op0->hasOneUse()) {
7466 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7467 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7468 Value *V1, *V2;
7469 ConstantInt *CC;
7470 switch (Op0BO->getOpcode()) {
7471 default: break;
7472 case Instruction::Add:
7473 case Instruction::And:
7474 case Instruction::Or:
7475 case Instruction::Xor: {
7476 // These operators commute.
7477 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7478 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007479 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007480 m_Specific(Op1)))){
Gabor Greifa645dd32008-05-16 19:29:10 +00007481 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007482 Op0BO->getOperand(0), Op1,
7483 Op0BO->getName());
7484 InsertNewInstBefore(YS, I); // (Y << C)
7485 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007486 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007487 Op0BO->getOperand(1)->getName());
7488 InsertNewInstBefore(X, I); // (X + (Y << C))
7489 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007490 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007491 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7492 }
7493
7494 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7495 Value *Op0BOOp1 = Op0BO->getOperand(1);
7496 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7497 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007498 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007499 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007500 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007501 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007502 Op0BO->getOperand(0), Op1,
7503 Op0BO->getName());
7504 InsertNewInstBefore(YS, I); // (Y << C)
7505 Instruction *XM =
Owen Anderson24be4c12009-07-03 00:17:18 +00007506 BinaryOperator::CreateAnd(V1,
Owen Anderson02b48c32009-07-29 18:55:55 +00007507 ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007508 V1->getName()+".mask");
7509 InsertNewInstBefore(XM, I); // X & (CC << C)
7510
Gabor Greifa645dd32008-05-16 19:29:10 +00007511 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007512 }
7513 }
7514
7515 // FALL THROUGH.
7516 case Instruction::Sub: {
7517 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7518 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007519 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007520 m_Specific(Op1)))) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007521 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007522 Op0BO->getOperand(1), Op1,
7523 Op0BO->getName());
7524 InsertNewInstBefore(YS, I); // (Y << C)
7525 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007526 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007527 Op0BO->getOperand(0)->getName());
7528 InsertNewInstBefore(X, I); // (X + (Y << C))
7529 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007530 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007531 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7532 }
7533
7534 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7535 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7536 match(Op0BO->getOperand(0),
7537 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007538 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007539 cast<BinaryOperator>(Op0BO->getOperand(0))
7540 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007541 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007542 Op0BO->getOperand(1), Op1,
7543 Op0BO->getName());
7544 InsertNewInstBefore(YS, I); // (Y << C)
7545 Instruction *XM =
Owen Anderson24be4c12009-07-03 00:17:18 +00007546 BinaryOperator::CreateAnd(V1,
Owen Anderson02b48c32009-07-29 18:55:55 +00007547 ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007548 V1->getName()+".mask");
7549 InsertNewInstBefore(XM, I); // X & (CC << C)
7550
Gabor Greifa645dd32008-05-16 19:29:10 +00007551 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007552 }
7553
7554 break;
7555 }
7556 }
7557
7558
7559 // If the operand is an bitwise operator with a constant RHS, and the
7560 // shift is the only use, we can pull it out of the shift.
7561 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7562 bool isValid = true; // Valid only for And, Or, Xor
7563 bool highBitSet = false; // Transform if high bit of constant set?
7564
7565 switch (Op0BO->getOpcode()) {
7566 default: isValid = false; break; // Do not perform transform!
7567 case Instruction::Add:
7568 isValid = isLeftShift;
7569 break;
7570 case Instruction::Or:
7571 case Instruction::Xor:
7572 highBitSet = false;
7573 break;
7574 case Instruction::And:
7575 highBitSet = true;
7576 break;
7577 }
7578
7579 // If this is a signed shift right, and the high bit is modified
7580 // by the logical operation, do not perform the transformation.
7581 // The highBitSet boolean indicates the value of the high bit of
7582 // the constant which would cause it to be modified for this
7583 // operation.
7584 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007585 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007586 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007587
7588 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007589 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007590
7591 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007592 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007593 InsertNewInstBefore(NewShift, I);
7594 NewShift->takeName(Op0BO);
7595
Gabor Greifa645dd32008-05-16 19:29:10 +00007596 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007597 NewRHS);
7598 }
7599 }
7600 }
7601 }
7602
7603 // Find out if this is a shift of a shift by a constant.
7604 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7605 if (ShiftOp && !ShiftOp->isShift())
7606 ShiftOp = 0;
7607
7608 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7609 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7610 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7611 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7612 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7613 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7614 Value *X = ShiftOp->getOperand(0);
7615
7616 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007617
7618 const IntegerType *Ty = cast<IntegerType>(I.getType());
7619
7620 // Check for (X << c1) << c2 and (X >> c1) >> c2
7621 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007622 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7623 // saturates.
7624 if (AmtSum >= TypeBits) {
7625 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007626 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007627 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7628 }
7629
Gabor Greifa645dd32008-05-16 19:29:10 +00007630 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007631 ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007632 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7633 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007634 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00007635 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007636
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007637 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00007638 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007639 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7640 I.getOpcode() == Instruction::LShr) {
7641 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007642 if (AmtSum >= TypeBits)
7643 AmtSum = TypeBits-1;
7644
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007645 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007646 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007647 InsertNewInstBefore(Shift, I);
7648
7649 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007650 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007651 }
7652
7653 // Okay, if we get here, one shift must be left, and the other shift must be
7654 // right. See if the amounts are equal.
7655 if (ShiftAmt1 == ShiftAmt2) {
7656 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7657 if (I.getOpcode() == Instruction::Shl) {
7658 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007659 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007660 }
7661 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7662 if (I.getOpcode() == Instruction::LShr) {
7663 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007664 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007665 }
7666 // We can simplify ((X << C) >>s C) into a trunc + sext.
7667 // NOTE: we could do this for any C, but that would make 'unusual' integer
7668 // types. For now, just stick to ones well-supported by the code
7669 // generators.
7670 const Type *SExtType = 0;
7671 switch (Ty->getBitWidth() - ShiftAmt1) {
7672 case 1 :
7673 case 8 :
7674 case 16 :
7675 case 32 :
7676 case 64 :
7677 case 128:
Owen Anderson6b6e2d92009-07-29 22:17:13 +00007678 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007679 break;
7680 default: break;
7681 }
7682 if (SExtType) {
7683 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7684 InsertNewInstBefore(NewTrunc, I);
7685 return new SExtInst(NewTrunc, Ty);
7686 }
7687 // Otherwise, we can't handle it yet.
7688 } else if (ShiftAmt1 < ShiftAmt2) {
7689 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7690
7691 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7692 if (I.getOpcode() == Instruction::Shl) {
7693 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7694 ShiftOp->getOpcode() == Instruction::AShr);
7695 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007696 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007697 InsertNewInstBefore(Shift, I);
7698
7699 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007700 return BinaryOperator::CreateAnd(Shift,
7701 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007702 }
7703
7704 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7705 if (I.getOpcode() == Instruction::LShr) {
7706 assert(ShiftOp->getOpcode() == Instruction::Shl);
7707 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007708 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007709 InsertNewInstBefore(Shift, I);
7710
7711 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007712 return BinaryOperator::CreateAnd(Shift,
7713 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007714 }
7715
7716 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7717 } else {
7718 assert(ShiftAmt2 < ShiftAmt1);
7719 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7720
7721 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7722 if (I.getOpcode() == Instruction::Shl) {
7723 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7724 ShiftOp->getOpcode() == Instruction::AShr);
7725 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007726 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007727 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007728 InsertNewInstBefore(Shift, I);
7729
7730 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007731 return BinaryOperator::CreateAnd(Shift,
7732 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007733 }
7734
7735 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7736 if (I.getOpcode() == Instruction::LShr) {
7737 assert(ShiftOp->getOpcode() == Instruction::Shl);
7738 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007739 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007740 InsertNewInstBefore(Shift, I);
7741
7742 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007743 return BinaryOperator::CreateAnd(Shift,
7744 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007745 }
7746
7747 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7748 }
7749 }
7750 return 0;
7751}
7752
7753
7754/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7755/// expression. If so, decompose it, returning some value X, such that Val is
7756/// X*Scale+Offset.
7757///
7758static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007759 int &Offset, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007760 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7761 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7762 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007763 Scale = 0;
Owen Andersoneacb44d2009-07-24 23:12:02 +00007764 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007765 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7766 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7767 if (I->getOpcode() == Instruction::Shl) {
7768 // This is a value scaled by '1 << the shift amt'.
7769 Scale = 1U << RHS->getZExtValue();
7770 Offset = 0;
7771 return I->getOperand(0);
7772 } else if (I->getOpcode() == Instruction::Mul) {
7773 // This value is scaled by 'RHS'.
7774 Scale = RHS->getZExtValue();
7775 Offset = 0;
7776 return I->getOperand(0);
7777 } else if (I->getOpcode() == Instruction::Add) {
7778 // We have X+C. Check to see if we really have (X*C2)+C1,
7779 // where C1 is divisible by C2.
7780 unsigned SubScale;
7781 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00007782 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7783 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007784 Offset += RHS->getZExtValue();
7785 Scale = SubScale;
7786 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007787 }
7788 }
7789 }
7790
7791 // Otherwise, we can't look past this.
7792 Scale = 1;
7793 Offset = 0;
7794 return Val;
7795}
7796
7797
7798/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7799/// try to eliminate the cast by moving the type information into the alloc.
7800Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7801 AllocationInst &AI) {
7802 const PointerType *PTy = cast<PointerType>(CI.getType());
7803
7804 // Remove any uses of AI that are dead.
7805 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7806
7807 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7808 Instruction *User = cast<Instruction>(*UI++);
7809 if (isInstructionTriviallyDead(User)) {
7810 while (UI != E && *UI == User)
7811 ++UI; // If this instruction uses AI more than once, don't break UI.
7812
7813 ++NumDeadInst;
Dan Gohman3fa885b2009-08-12 16:28:31 +00007814 DOUT << "IC: DCE: " << *User << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007815 EraseInstFromFunction(*User);
7816 }
7817 }
Dan Gohmana80e2712009-07-21 23:21:54 +00007818
7819 // This requires TargetData to get the alloca alignment and size information.
7820 if (!TD) return 0;
7821
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007822 // Get the type really allocated and the type casted to.
7823 const Type *AllocElTy = AI.getAllocatedType();
7824 const Type *CastElTy = PTy->getElementType();
7825 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7826
7827 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7828 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7829 if (CastElTyAlign < AllocElTyAlign) return 0;
7830
7831 // If the allocation has multiple uses, only promote it if we are strictly
7832 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007833 // same, we open the door to infinite loops of various kinds. (A reference
7834 // from a dbg.declare doesn't count as a use for this purpose.)
7835 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7836 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007837
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007838 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7839 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007840 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7841
7842 // See if we can satisfy the modulus by pulling a scale out of the array
7843 // size argument.
7844 unsigned ArraySizeScale;
7845 int ArrayOffset;
7846 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00007847 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7848 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007849
7850 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7851 // do the xform.
7852 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7853 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7854
7855 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7856 Value *Amt = 0;
7857 if (Scale == 1) {
7858 Amt = NumElements;
7859 } else {
7860 // If the allocation size is constant, form a constant mul expression
Owen Andersoneacb44d2009-07-24 23:12:02 +00007861 Amt = ConstantInt::get(Type::Int32Ty, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007862 if (isa<ConstantInt>(NumElements))
Owen Anderson02b48c32009-07-29 18:55:55 +00007863 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
Dan Gohman8fd520a2009-06-15 22:12:54 +00007864 cast<ConstantInt>(Amt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007865 // otherwise multiply the amount and the number of elements
Chris Lattner27cc5472009-03-17 17:55:15 +00007866 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00007867 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007868 Amt = InsertNewInstBefore(Tmp, AI);
7869 }
7870 }
7871
7872 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007873 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007874 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007875 Amt = InsertNewInstBefore(Tmp, AI);
7876 }
7877
7878 AllocationInst *New;
7879 if (isa<MallocInst>(AI))
Owen Anderson140166d2009-07-15 23:53:25 +00007880 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007881 else
Owen Anderson140166d2009-07-15 23:53:25 +00007882 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007883 InsertNewInstBefore(New, AI);
7884 New->takeName(&AI);
7885
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007886 // If the allocation has one real use plus a dbg.declare, just remove the
7887 // declare.
7888 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7889 EraseInstFromFunction(*DI);
7890 }
7891 // If the allocation has multiple real uses, insert a cast and change all
7892 // things that used it to use the new cast. This will also hack on CI, but it
7893 // will die soon.
7894 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007895 AddUsesToWorkList(AI);
7896 // New is the allocation instruction, pointer typed. AI is the original
7897 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7898 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7899 InsertNewInstBefore(NewCast, AI);
7900 AI.replaceAllUsesWith(NewCast);
7901 }
7902 return ReplaceInstUsesWith(CI, New);
7903}
7904
7905/// CanEvaluateInDifferentType - Return true if we can take the specified value
7906/// and return it as type Ty without inserting any new casts and without
7907/// changing the computed value. This is used by code that tries to decide
7908/// whether promoting or shrinking integer operations to wider or smaller types
7909/// will allow us to eliminate a truncate or extend.
7910///
7911/// This is a truncation operation if Ty is smaller than V->getType(), or an
7912/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007913///
7914/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7915/// should return true if trunc(V) can be computed by computing V in the smaller
7916/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7917/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7918/// efficiently truncated.
7919///
7920/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7921/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7922/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007923bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00007924 unsigned CastOpc,
7925 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007926 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007927 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007928 return true;
7929
7930 Instruction *I = dyn_cast<Instruction>(V);
7931 if (!I) return false;
7932
Dan Gohman8fd520a2009-06-15 22:12:54 +00007933 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007934
Chris Lattneref70bb82007-08-02 06:11:14 +00007935 // If this is an extension or truncate, we can often eliminate it.
7936 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7937 // If this is a cast from the destination type, we can trivially eliminate
7938 // it, and this will remove a cast overall.
7939 if (I->getOperand(0)->getType() == Ty) {
7940 // If the first operand is itself a cast, and is eliminable, do not count
7941 // this as an eliminable cast. We would prefer to eliminate those two
7942 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007943 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007944 ++NumCastsRemoved;
7945 return true;
7946 }
7947 }
7948
7949 // We can't extend or shrink something that has multiple uses: doing so would
7950 // require duplicating the instruction in general, which isn't profitable.
7951 if (!I->hasOneUse()) return false;
7952
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007953 unsigned Opc = I->getOpcode();
7954 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007955 case Instruction::Add:
7956 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007957 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007958 case Instruction::And:
7959 case Instruction::Or:
7960 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007961 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007962 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007963 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007964 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007965 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007966
Eli Friedman08c45bc2009-07-13 22:46:01 +00007967 case Instruction::UDiv:
7968 case Instruction::URem: {
7969 // UDiv and URem can be truncated if all the truncated bits are zero.
7970 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7971 uint32_t BitWidth = Ty->getScalarSizeInBits();
7972 if (BitWidth < OrigBitWidth) {
7973 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7974 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7975 MaskedValueIsZero(I->getOperand(1), Mask)) {
7976 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7977 NumCastsRemoved) &&
7978 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7979 NumCastsRemoved);
7980 }
7981 }
7982 break;
7983 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007984 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007985 // If we are truncating the result of this SHL, and if it's a shift of a
7986 // constant amount, we can always perform a SHL in a smaller type.
7987 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007988 uint32_t BitWidth = Ty->getScalarSizeInBits();
7989 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007990 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007991 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007992 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007993 }
7994 break;
7995 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007996 // If this is a truncate of a logical shr, we can truncate it to a smaller
7997 // lshr iff we know that the bits we would otherwise be shifting in are
7998 // already zeros.
7999 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008000 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8001 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008002 if (BitWidth < OrigBitWidth &&
8003 MaskedValueIsZero(I->getOperand(0),
8004 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8005 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00008006 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008007 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008008 }
8009 }
8010 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008011 case Instruction::ZExt:
8012 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00008013 case Instruction::Trunc:
8014 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00008015 // can safely replace it. Note that replacing it does not reduce the number
8016 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008017 if (Opc == CastOpc)
8018 return true;
8019
8020 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00008021 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008022 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008023 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008024 case Instruction::Select: {
8025 SelectInst *SI = cast<SelectInst>(I);
8026 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008027 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008028 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008029 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008030 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008031 case Instruction::PHI: {
8032 // We can change a phi if we can change all operands.
8033 PHINode *PN = cast<PHINode>(I);
8034 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8035 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008036 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00008037 return false;
8038 return true;
8039 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008040 default:
8041 // TODO: Can handle more cases here.
8042 break;
8043 }
8044
8045 return false;
8046}
8047
8048/// EvaluateInDifferentType - Given an expression that
8049/// CanEvaluateInDifferentType returns true for, actually insert the code to
8050/// evaluate the expression.
8051Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8052 bool isSigned) {
8053 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +00008054 return ConstantExpr::getIntegerCast(C, Ty,
Owen Anderson24be4c12009-07-03 00:17:18 +00008055 isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008056
8057 // Otherwise, it must be an instruction.
8058 Instruction *I = cast<Instruction>(V);
8059 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008060 unsigned Opc = I->getOpcode();
8061 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008062 case Instruction::Add:
8063 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00008064 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008065 case Instruction::And:
8066 case Instruction::Or:
8067 case Instruction::Xor:
8068 case Instruction::AShr:
8069 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00008070 case Instruction::Shl:
8071 case Instruction::UDiv:
8072 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008073 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8074 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008075 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008076 break;
8077 }
8078 case Instruction::Trunc:
8079 case Instruction::ZExt:
8080 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008081 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00008082 // just return the source. There's no need to insert it because it is not
8083 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008084 if (I->getOperand(0)->getType() == Ty)
8085 return I->getOperand(0);
8086
Chris Lattner4200c2062008-06-18 04:00:49 +00008087 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00008088 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00008089 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00008090 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008091 case Instruction::Select: {
8092 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8093 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8094 Res = SelectInst::Create(I->getOperand(0), True, False);
8095 break;
8096 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008097 case Instruction::PHI: {
8098 PHINode *OPN = cast<PHINode>(I);
8099 PHINode *NPN = PHINode::Create(Ty);
8100 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8101 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8102 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8103 }
8104 Res = NPN;
8105 break;
8106 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008107 default:
8108 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00008109 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008110 break;
8111 }
8112
Chris Lattner4200c2062008-06-18 04:00:49 +00008113 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008114 return InsertNewInstBefore(Res, *I);
8115}
8116
8117/// @brief Implement the transforms common to all CastInst visitors.
8118Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8119 Value *Src = CI.getOperand(0);
8120
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008121 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8122 // eliminate it now.
8123 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8124 if (Instruction::CastOps opc =
8125 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8126 // The first cast (CSrc) is eliminable so we need to fix up or replace
8127 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008128 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008129 }
8130 }
8131
8132 // If we are casting a select then fold the cast into the select
8133 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8134 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8135 return NV;
8136
8137 // If we are casting a PHI then fold the cast into the PHI
8138 if (isa<PHINode>(Src))
8139 if (Instruction *NV = FoldOpIntoPhi(CI))
8140 return NV;
8141
8142 return 0;
8143}
8144
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008145/// FindElementAtOffset - Given a type and a constant offset, determine whether
8146/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008147/// the specified offset. If so, fill them into NewIndices and return the
8148/// resultant element type, otherwise return null.
8149static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8150 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008151 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008152 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008153 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008154 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008155
8156 // Start with the index over the outer type. Note that the type size
8157 // might be zero (even if the offset isn't zero) if the indexed type
8158 // is something like [0 x {int, int}]
8159 const Type *IntPtrTy = TD->getIntPtrType();
8160 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008161 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008162 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008163 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008164
Chris Lattnerce48c462009-01-11 20:15:20 +00008165 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008166 if (Offset < 0) {
8167 --FirstIdx;
8168 Offset += TySize;
8169 assert(Offset >= 0);
8170 }
8171 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8172 }
8173
Owen Andersoneacb44d2009-07-24 23:12:02 +00008174 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008175
8176 // Index into the types. If we fail, set OrigBase to null.
8177 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008178 // Indexing into tail padding between struct/array elements.
8179 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008180 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008181
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008182 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8183 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008184 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8185 "Offset must stay within the indexed type");
8186
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008187 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008188 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008189
8190 Offset -= SL->getElementOffset(Elt);
8191 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008192 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008193 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008194 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00008195 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008196 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008197 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008198 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008199 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008200 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008201 }
8202 }
8203
Chris Lattner54dddc72009-01-24 01:00:13 +00008204 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008205}
8206
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008207/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8208Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8209 Value *Src = CI.getOperand(0);
8210
8211 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8212 // If casting the result of a getelementptr instruction with no offset, turn
8213 // this into a cast of the original pointer!
8214 if (GEP->hasAllZeroIndices()) {
8215 // Changing the cast operand is usually not a good idea but it is safe
8216 // here because the pointer operand is being replaced with another
8217 // pointer operand so the opcode doesn't need to change.
8218 AddToWorkList(GEP);
8219 CI.setOperand(0, GEP->getOperand(0));
8220 return &CI;
8221 }
8222
8223 // If the GEP has a single use, and the base pointer is a bitcast, and the
8224 // GEP computes a constant offset, see if we can convert these three
8225 // instructions into fewer. This typically happens with unions and other
8226 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008227 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008228 if (GEP->hasAllConstantIndices()) {
8229 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +00008230 ConstantInt *OffsetV =
8231 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008232 int64_t Offset = OffsetV->getSExtValue();
8233
8234 // Get the base pointer input of the bitcast, and the type it points to.
8235 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8236 const Type *GEPIdxTy =
8237 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008238 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008239 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008240 // If we were able to index down into an element, create the GEP
8241 // and bitcast the result. This eliminates one bitcast, potentially
8242 // two.
8243 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8244 NewIndices.begin(),
8245 NewIndices.end(), "");
8246 InsertNewInstBefore(NGEP, CI);
8247 NGEP->takeName(GEP);
Dan Gohman17f46f72009-07-28 01:40:03 +00008248 if (cast<GEPOperator>(GEP)->isInBounds())
8249 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008250
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008251 if (isa<BitCastInst>(CI))
8252 return new BitCastInst(NGEP, CI.getType());
8253 assert(isa<PtrToIntInst>(CI));
8254 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008255 }
8256 }
8257 }
8258 }
8259
8260 return commonCastTransforms(CI);
8261}
8262
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008263/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8264/// type like i42. We don't want to introduce operations on random non-legal
8265/// integer types where they don't already exist in the code. In the future,
8266/// we should consider making this based off target-data, so that 32-bit targets
8267/// won't get i64 operations etc.
8268static bool isSafeIntegerType(const Type *Ty) {
8269 switch (Ty->getPrimitiveSizeInBits()) {
8270 case 8:
8271 case 16:
8272 case 32:
8273 case 64:
8274 return true;
8275 default:
8276 return false;
8277 }
8278}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008279
Eli Friedman827e37a2009-07-13 20:58:59 +00008280/// commonIntCastTransforms - This function implements the common transforms
8281/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008282Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8283 if (Instruction *Result = commonCastTransforms(CI))
8284 return Result;
8285
8286 Value *Src = CI.getOperand(0);
8287 const Type *SrcTy = Src->getType();
8288 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008289 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8290 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008291
8292 // See if we can simplify any instructions used by the LHS whose sole
8293 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008294 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008295 return &CI;
8296
8297 // If the source isn't an instruction or has more than one use then we
8298 // can't do anything more.
8299 Instruction *SrcI = dyn_cast<Instruction>(Src);
8300 if (!SrcI || !Src->hasOneUse())
8301 return 0;
8302
8303 // Attempt to propagate the cast into the instruction for int->int casts.
8304 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008305 // Only do this if the dest type is a simple type, don't convert the
8306 // expression tree to something weird like i93 unless the source is also
8307 // strange.
8308 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman8fd520a2009-06-15 22:12:54 +00008309 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8310 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng814a00c2009-01-16 02:11:43 +00008311 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008312 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008313 // eliminates the cast, so it is always a win. If this is a zero-extension,
8314 // we need to do an AND to maintain the clear top-part of the computation,
8315 // so we require that the input have eliminated at least one cast. If this
8316 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008317 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008318 bool DoXForm = false;
8319 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008320 switch (CI.getOpcode()) {
8321 default:
8322 // All the others use floating point so we shouldn't actually
8323 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008324 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008325 case Instruction::Trunc:
8326 DoXForm = true;
8327 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008328 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008329 DoXForm = NumCastsRemoved >= 1;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008330 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008331 // If it's unnecessary to issue an AND to clear the high bits, it's
8332 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008333 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008334 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8335 if (MaskedValueIsZero(TryRes, Mask))
8336 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008337
8338 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008339 if (TryI->use_empty())
8340 EraseInstFromFunction(*TryI);
8341 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008342 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008343 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008344 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008345 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008346 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008347 // If we do not have to emit the truncate + sext pair, then it's always
8348 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008349 //
8350 // It's not safe to eliminate the trunc + sext pair if one of the
8351 // eliminated cast is a truncate. e.g.
8352 // t2 = trunc i32 t1 to i16
8353 // t3 = sext i16 t2 to i32
8354 // !=
8355 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008356 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008357 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8358 if (NumSignBits > (DestBitSize - SrcBitSize))
8359 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008360
8361 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008362 if (TryI->use_empty())
8363 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008364 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008365 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008366 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008367 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008368
8369 if (DoXForm) {
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008370 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8371 << " cast: " << CI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008372 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8373 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008374 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008375 // Just replace this cast with the result.
8376 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008377
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008378 assert(Res->getType() == DestTy);
8379 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008380 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008381 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008382 // Just replace this cast with the result.
8383 return ReplaceInstUsesWith(CI, Res);
8384 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008385 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008386
8387 // If the high bits are already zero, just replace this cast with the
8388 // result.
8389 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8390 if (MaskedValueIsZero(Res, Mask))
8391 return ReplaceInstUsesWith(CI, Res);
8392
8393 // We need to emit an AND to clear the high bits.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008394 Constant *C = ConstantInt::get(*Context,
8395 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008396 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008397 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008398 case Instruction::SExt: {
8399 // If the high bits are already filled with sign bit, just replace this
8400 // cast with the result.
8401 unsigned NumSignBits = ComputeNumSignBits(Res);
8402 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008403 return ReplaceInstUsesWith(CI, Res);
8404
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008405 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00008406 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008407 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8408 CI), DestTy);
8409 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008410 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008411 }
8412 }
8413
8414 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8415 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8416
8417 switch (SrcI->getOpcode()) {
8418 case Instruction::Add:
8419 case Instruction::Mul:
8420 case Instruction::And:
8421 case Instruction::Or:
8422 case Instruction::Xor:
8423 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008424 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8425 // Don't insert two casts unless at least one can be eliminated.
8426 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008427 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008428 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8429 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008430 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008431 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8432 }
8433 }
8434
8435 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8436 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8437 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson4f720fa2009-07-31 17:39:07 +00008438 Op1 == ConstantInt::getTrue(*Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008439 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedman722b4792008-11-30 21:09:11 +00008440 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Anderson24be4c12009-07-03 00:17:18 +00008441 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008442 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008443 }
8444 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008445
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008446 case Instruction::Shl: {
8447 // Canonicalize trunc inside shl, if we can.
8448 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8449 if (CI && DestBitSize < SrcBitSize &&
8450 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8451 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8452 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008453 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008454 }
8455 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008456 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008457 }
8458 return 0;
8459}
8460
8461Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8462 if (Instruction *Result = commonIntCastTransforms(CI))
8463 return Result;
8464
8465 Value *Src = CI.getOperand(0);
8466 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008467 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8468 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008469
8470 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008471 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008472 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattner32177f82009-03-24 18:15:30 +00008473 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersonaac28372009-07-31 20:28:14 +00008474 Value *Zero = Constant::getNullValue(Src->getType());
Owen Anderson6601fcd2009-07-09 23:48:35 +00008475 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008476 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008477
Chris Lattner32177f82009-03-24 18:15:30 +00008478 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8479 ConstantInt *ShAmtV = 0;
8480 Value *ShiftOp = 0;
8481 if (Src->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00008482 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner32177f82009-03-24 18:15:30 +00008483 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8484
8485 // Get a mask for the bits shifting in.
8486 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8487 if (MaskedValueIsZero(ShiftOp, Mask)) {
8488 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00008489 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008490
8491 // Okay, we can shrink this. Truncate the input, then return a new
8492 // shift.
8493 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Anderson02b48c32009-07-29 18:55:55 +00008494 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008495 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008496 }
8497 }
8498
8499 return 0;
8500}
8501
Evan Chenge3779cf2008-03-24 00:21:34 +00008502/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8503/// in order to eliminate the icmp.
8504Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8505 bool DoXform) {
8506 // If we are just checking for a icmp eq of a single bit and zext'ing it
8507 // to an integer, then shift the bit to the appropriate place and then
8508 // cast to integer to avoid the comparison.
8509 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8510 const APInt &Op1CV = Op1C->getValue();
8511
8512 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8513 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8514 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8515 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8516 if (!DoXform) return ICI;
8517
8518 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008519 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008520 In->getType()->getScalarSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008521 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00008522 In->getName()+".lobit"),
8523 CI);
8524 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00008525 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00008526 false/*ZExt*/, "tmp", &CI);
8527
8528 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008529 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008530 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00008531 In->getName()+".not"),
8532 CI);
8533 }
8534
8535 return ReplaceInstUsesWith(CI, In);
8536 }
8537
8538
8539
8540 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8541 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8542 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8543 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8544 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8545 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8546 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8547 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8548 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8549 // This only works for EQ and NE
8550 ICI->isEquality()) {
8551 // If Op1C some other power of two, convert:
8552 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8553 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8554 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8555 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8556
8557 APInt KnownZeroMask(~KnownZero);
8558 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8559 if (!DoXform) return ICI;
8560
8561 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8562 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8563 // (X&4) == 2 --> false
8564 // (X&4) != 2 --> true
Owen Andersoneacb44d2009-07-24 23:12:02 +00008565 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00008566 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008567 return ReplaceInstUsesWith(CI, Res);
8568 }
8569
8570 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8571 Value *In = ICI->getOperand(0);
8572 if (ShiftAmt) {
8573 // Perform a logical shr by shiftamt.
8574 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00008575 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008576 ConstantInt::get(In->getType(), ShiftAmt),
Evan Chenge3779cf2008-03-24 00:21:34 +00008577 In->getName()+".lobit"), CI);
8578 }
8579
8580 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008581 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008582 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008583 InsertNewInstBefore(cast<Instruction>(In), CI);
8584 }
8585
8586 if (CI.getType() == In->getType())
8587 return ReplaceInstUsesWith(CI, In);
8588 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008589 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008590 }
8591 }
8592 }
8593
8594 return 0;
8595}
8596
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008597Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8598 // If one of the common conversion will work ..
8599 if (Instruction *Result = commonIntCastTransforms(CI))
8600 return Result;
8601
8602 Value *Src = CI.getOperand(0);
8603
Chris Lattner215d56e2009-02-17 20:47:23 +00008604 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8605 // types and if the sizes are just right we can convert this into a logical
8606 // 'and' which will be much cheaper than the pair of casts.
8607 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8608 // Get the sizes of the types involved. We know that the intermediate type
8609 // will be smaller than A or C, but don't know the relation between A and C.
8610 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008611 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8612 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8613 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008614 // If we're actually extending zero bits, then if
8615 // SrcSize < DstSize: zext(a & mask)
8616 // SrcSize == DstSize: a & mask
8617 // SrcSize > DstSize: trunc(a) & mask
8618 if (SrcSize < DstSize) {
8619 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008620 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattner215d56e2009-02-17 20:47:23 +00008621 Instruction *And =
8622 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8623 InsertNewInstBefore(And, CI);
8624 return new ZExtInst(And, CI.getType());
8625 } else if (SrcSize == DstSize) {
8626 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008627 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008628 AndValue));
Chris Lattner215d56e2009-02-17 20:47:23 +00008629 } else if (SrcSize > DstSize) {
8630 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8631 InsertNewInstBefore(Trunc, CI);
8632 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008633 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008634 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008635 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008636 }
8637 }
8638
Evan Chenge3779cf2008-03-24 00:21:34 +00008639 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8640 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008641
Evan Chenge3779cf2008-03-24 00:21:34 +00008642 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8643 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8644 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8645 // of the (zext icmp) will be transformed.
8646 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8647 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8648 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8649 (transformZExtICmp(LHS, CI, false) ||
8650 transformZExtICmp(RHS, CI, false))) {
8651 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8652 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008653 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008654 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008655 }
8656
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008657 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008658 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8659 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8660 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8661 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008662 if (TI0->getType() == CI.getType())
8663 return
8664 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00008665 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008666 }
8667
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008668 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8669 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8670 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8671 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8672 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8673 And->getOperand(1) == C)
8674 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8675 Value *TI0 = TI->getOperand(0);
8676 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00008677 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008678 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8679 InsertNewInstBefore(NewAnd, *And);
8680 return BinaryOperator::CreateXor(NewAnd, ZC);
8681 }
8682 }
8683
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008684 return 0;
8685}
8686
8687Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8688 if (Instruction *I = commonIntCastTransforms(CI))
8689 return I;
8690
8691 Value *Src = CI.getOperand(0);
8692
Dan Gohman35b76162008-10-30 20:40:10 +00008693 // Canonicalize sign-extend from i1 to a select.
8694 if (Src->getType() == Type::Int1Ty)
8695 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00008696 Constant::getAllOnesValue(CI.getType()),
8697 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008698
8699 // See if the value being truncated is already sign extended. If so, just
8700 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00008701 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00008702 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008703 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8704 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8705 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008706 unsigned NumSignBits = ComputeNumSignBits(Op);
8707
8708 if (OpBits == DestBits) {
8709 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8710 // bits, it is already ready.
8711 if (NumSignBits > DestBits-MidBits)
8712 return ReplaceInstUsesWith(CI, Op);
8713 } else if (OpBits < DestBits) {
8714 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8715 // bits, just sext from i32.
8716 if (NumSignBits > OpBits-MidBits)
8717 return new SExtInst(Op, CI.getType(), "tmp");
8718 } else {
8719 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8720 // bits, just truncate to i32.
8721 if (NumSignBits > OpBits-MidBits)
8722 return new TruncInst(Op, CI.getType(), "tmp");
8723 }
8724 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008725
8726 // If the input is a shl/ashr pair of a same constant, then this is a sign
8727 // extension from a smaller value. If we could trust arbitrary bitwidth
8728 // integers, we could turn this into a truncate to the smaller bit and then
8729 // use a sext for the whole extension. Since we don't, look deeper and check
8730 // for a truncate. If the source and dest are the same type, eliminate the
8731 // trunc and extend and just do shifts. For example, turn:
8732 // %a = trunc i32 %i to i8
8733 // %b = shl i8 %a, 6
8734 // %c = ashr i8 %b, 6
8735 // %d = sext i8 %c to i32
8736 // into:
8737 // %a = shl i32 %i, 30
8738 // %d = ashr i32 %a, 30
8739 Value *A = 0;
8740 ConstantInt *BA = 0, *CA = 0;
8741 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohmancdff2122009-08-12 16:23:25 +00008742 m_ConstantInt(CA))) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008743 BA == CA && isa<TruncInst>(A)) {
8744 Value *I = cast<TruncInst>(A)->getOperand(0);
8745 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008746 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8747 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008748 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00008749 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattner8a2d0592008-08-06 07:35:52 +00008750 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8751 CI.getName()), CI);
8752 return BinaryOperator::CreateAShr(I, ShAmtV);
8753 }
8754 }
8755
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008756 return 0;
8757}
8758
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008759/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8760/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008761static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008762 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008763 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008764 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008765 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8766 if (!losesInfo)
Owen Andersond363a0e2009-07-27 20:59:43 +00008767 return ConstantFP::get(*Context, F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008768 return 0;
8769}
8770
8771/// LookThroughFPExtensions - If this is an fp extension instruction, look
8772/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00008773static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008774 if (Instruction *I = dyn_cast<Instruction>(V))
8775 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00008776 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008777
8778 // If this value is a constant, return the constant in the smallest FP type
8779 // that can accurately represent it. This allows us to turn
8780 // (float)((double)X+2.0) into x+2.0f.
8781 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8782 if (CFP->getType() == Type::PPC_FP128Ty)
8783 return V; // No constant folding of this.
8784 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00008785 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008786 return V;
8787 if (CFP->getType() == Type::DoubleTy)
8788 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00008789 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008790 return V;
8791 // Don't try to shrink to various long double types.
8792 }
8793
8794 return V;
8795}
8796
8797Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8798 if (Instruction *I = commonCastTransforms(CI))
8799 return I;
8800
Dan Gohman7ce405e2009-06-04 22:49:04 +00008801 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008802 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008803 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008804 // many builtins (sqrt, etc).
8805 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8806 if (OpI && OpI->hasOneUse()) {
8807 switch (OpI->getOpcode()) {
8808 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008809 case Instruction::FAdd:
8810 case Instruction::FSub:
8811 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008812 case Instruction::FDiv:
8813 case Instruction::FRem:
8814 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00008815 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8816 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008817 if (LHSTrunc->getType() != SrcTy &&
8818 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008819 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008820 // If the source types were both smaller than the destination type of
8821 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008822 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8823 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008824 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8825 CI.getType(), CI);
8826 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8827 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008828 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008829 }
8830 }
8831 break;
8832 }
8833 }
8834 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008835}
8836
8837Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8838 return commonCastTransforms(CI);
8839}
8840
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008841Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008842 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8843 if (OpI == 0)
8844 return commonCastTransforms(FI);
8845
8846 // fptoui(uitofp(X)) --> X
8847 // fptoui(sitofp(X)) --> X
8848 // This is safe if the intermediate type has enough bits in its mantissa to
8849 // accurately represent all values of X. For example, do not do this with
8850 // i64->float->i64. This is also safe for sitofp case, because any negative
8851 // 'X' value would cause an undefined result for the fptoui.
8852 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8853 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008854 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008855 OpI->getType()->getFPMantissaWidth())
8856 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008857
8858 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008859}
8860
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008861Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008862 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8863 if (OpI == 0)
8864 return commonCastTransforms(FI);
8865
8866 // fptosi(sitofp(X)) --> X
8867 // fptosi(uitofp(X)) --> X
8868 // This is safe if the intermediate type has enough bits in its mantissa to
8869 // accurately represent all values of X. For example, do not do this with
8870 // i64->float->i64. This is also safe for sitofp case, because any negative
8871 // 'X' value would cause an undefined result for the fptoui.
8872 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8873 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008874 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008875 OpI->getType()->getFPMantissaWidth())
8876 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008877
8878 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008879}
8880
8881Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8882 return commonCastTransforms(CI);
8883}
8884
8885Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8886 return commonCastTransforms(CI);
8887}
8888
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008889Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8890 // If the destination integer type is smaller than the intptr_t type for
8891 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8892 // trunc to be exposed to other transforms. Don't do this for extending
8893 // ptrtoint's, because we don't know if the target sign or zero extends its
8894 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008895 if (TD &&
8896 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008897 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8898 TD->getIntPtrType(),
8899 "tmp"), CI);
8900 return new TruncInst(P, CI.getType());
8901 }
8902
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008903 return commonPointerCastTransforms(CI);
8904}
8905
Chris Lattner7c1626482008-01-08 07:23:51 +00008906Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008907 // If the source integer type is larger than the intptr_t type for
8908 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8909 // allows the trunc to be exposed to other transforms. Don't do this for
8910 // extending inttoptr's, because we don't know if the target sign or zero
8911 // extends to pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008912 if (TD &&
8913 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008914 TD->getPointerSizeInBits()) {
8915 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8916 TD->getIntPtrType(),
8917 "tmp"), CI);
8918 return new IntToPtrInst(P, CI.getType());
8919 }
8920
Chris Lattner7c1626482008-01-08 07:23:51 +00008921 if (Instruction *I = commonCastTransforms(CI))
8922 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00008923
Chris Lattner7c1626482008-01-08 07:23:51 +00008924 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008925}
8926
8927Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8928 // If the operands are integer typed then apply the integer transforms,
8929 // otherwise just apply the common ones.
8930 Value *Src = CI.getOperand(0);
8931 const Type *SrcTy = Src->getType();
8932 const Type *DestTy = CI.getType();
8933
Eli Friedman5013d3f2009-07-13 20:53:00 +00008934 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008935 if (Instruction *I = commonPointerCastTransforms(CI))
8936 return I;
8937 } else {
8938 if (Instruction *Result = commonCastTransforms(CI))
8939 return Result;
8940 }
8941
8942
8943 // Get rid of casts from one type to the same type. These are useless and can
8944 // be replaced by the operand.
8945 if (DestTy == Src->getType())
8946 return ReplaceInstUsesWith(CI, Src);
8947
8948 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8949 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8950 const Type *DstElTy = DstPTy->getElementType();
8951 const Type *SrcElTy = SrcPTy->getElementType();
8952
Nate Begemandf5b3612008-03-31 00:22:16 +00008953 // If the address spaces don't match, don't eliminate the bitcast, which is
8954 // required for changing types.
8955 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8956 return 0;
8957
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008958 // If we are casting a malloc or alloca to a pointer to a type of the same
8959 // size, rewrite the allocation instruction to allocate the "right" type.
8960 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8961 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8962 return V;
8963
8964 // If the source and destination are pointers, and this cast is equivalent
8965 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8966 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersonaac28372009-07-31 20:28:14 +00008967 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008968 unsigned NumZeros = 0;
8969 while (SrcElTy != DstElTy &&
8970 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8971 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8972 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8973 ++NumZeros;
8974 }
8975
8976 // If we found a path from the src to dest, create the getelementptr now.
8977 if (SrcElTy == DstElTy) {
8978 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohman17f46f72009-07-28 01:40:03 +00008979 Instruction *GEP = GetElementPtrInst::Create(Src,
8980 Idxs.begin(), Idxs.end(), "",
8981 ((Instruction*) NULL));
8982 cast<GEPOperator>(GEP)->setIsInBounds(true);
8983 return GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008984 }
8985 }
8986
Eli Friedman1d31dee2009-07-18 23:06:53 +00008987 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8988 if (DestVTy->getNumElements() == 1) {
8989 if (!isa<VectorType>(SrcTy)) {
8990 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8991 DestVTy->getElementType(), CI);
Owen Andersonb99ecca2009-07-30 23:03:37 +00008992 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Owen Andersonaac28372009-07-31 20:28:14 +00008993 Constant::getNullValue(Type::Int32Ty));
Eli Friedman1d31dee2009-07-18 23:06:53 +00008994 }
8995 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8996 }
8997 }
8998
8999 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9000 if (SrcVTy->getNumElements() == 1) {
9001 if (!isa<VectorType>(DestTy)) {
9002 Instruction *Elem =
Owen Andersonaac28372009-07-31 20:28:14 +00009003 ExtractElementInst::Create(Src, Constant::getNullValue(Type::Int32Ty));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009004 InsertNewInstBefore(Elem, CI);
9005 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9006 }
9007 }
9008 }
9009
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009010 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9011 if (SVI->hasOneUse()) {
9012 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9013 // a bitconvert to a vector with the same # elts.
9014 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009015 cast<VectorType>(DestTy)->getNumElements() ==
9016 SVI->getType()->getNumElements() &&
9017 SVI->getType()->getNumElements() ==
9018 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009019 CastInst *Tmp;
9020 // If either of the operands is a cast from CI.getType(), then
9021 // evaluating the shuffle in the casted destination's type will allow
9022 // us to eliminate at least one cast.
9023 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9024 Tmp->getOperand(0)->getType() == DestTy) ||
9025 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9026 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedman722b4792008-11-30 21:09:11 +00009027 Value *LHS = InsertCastBefore(Instruction::BitCast,
9028 SVI->getOperand(0), DestTy, CI);
9029 Value *RHS = InsertCastBefore(Instruction::BitCast,
9030 SVI->getOperand(1), DestTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009031 // Return a new shuffle vector. Use the same element ID's, as we
9032 // know the vector types match #elts.
9033 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9034 }
9035 }
9036 }
9037 }
9038 return 0;
9039}
9040
9041/// GetSelectFoldableOperands - We want to turn code that looks like this:
9042/// %C = or %A, %B
9043/// %D = select %cond, %C, %A
9044/// into:
9045/// %C = select %cond, %B, 0
9046/// %D = or %A, %C
9047///
9048/// Assuming that the specified instruction is an operand to the select, return
9049/// a bitmask indicating which operands of this instruction are foldable if they
9050/// equal the other incoming value of the select.
9051///
9052static unsigned GetSelectFoldableOperands(Instruction *I) {
9053 switch (I->getOpcode()) {
9054 case Instruction::Add:
9055 case Instruction::Mul:
9056 case Instruction::And:
9057 case Instruction::Or:
9058 case Instruction::Xor:
9059 return 3; // Can fold through either operand.
9060 case Instruction::Sub: // Can only fold on the amount subtracted.
9061 case Instruction::Shl: // Can only fold on the shift amount.
9062 case Instruction::LShr:
9063 case Instruction::AShr:
9064 return 1;
9065 default:
9066 return 0; // Cannot fold
9067 }
9068}
9069
9070/// GetSelectFoldableConstant - For the same transformation as the previous
9071/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00009072static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00009073 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009074 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00009075 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009076 case Instruction::Add:
9077 case Instruction::Sub:
9078 case Instruction::Or:
9079 case Instruction::Xor:
9080 case Instruction::Shl:
9081 case Instruction::LShr:
9082 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00009083 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009084 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00009085 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009086 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00009087 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009088 }
9089}
9090
9091/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9092/// have the same opcode and only one use each. Try to simplify this.
9093Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9094 Instruction *FI) {
9095 if (TI->getNumOperands() == 1) {
9096 // If this is a non-volatile load or a cast from the same type,
9097 // merge.
9098 if (TI->isCast()) {
9099 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9100 return 0;
9101 } else {
9102 return 0; // unknown unary op.
9103 }
9104
9105 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009106 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00009107 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009108 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009109 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009110 TI->getType());
9111 }
9112
9113 // Only handle binary operators here.
9114 if (!isa<BinaryOperator>(TI))
9115 return 0;
9116
9117 // Figure out if the operations have any operands in common.
9118 Value *MatchOp, *OtherOpT, *OtherOpF;
9119 bool MatchIsOpZero;
9120 if (TI->getOperand(0) == FI->getOperand(0)) {
9121 MatchOp = TI->getOperand(0);
9122 OtherOpT = TI->getOperand(1);
9123 OtherOpF = FI->getOperand(1);
9124 MatchIsOpZero = true;
9125 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9126 MatchOp = TI->getOperand(1);
9127 OtherOpT = TI->getOperand(0);
9128 OtherOpF = FI->getOperand(0);
9129 MatchIsOpZero = false;
9130 } else if (!TI->isCommutative()) {
9131 return 0;
9132 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9133 MatchOp = TI->getOperand(0);
9134 OtherOpT = TI->getOperand(1);
9135 OtherOpF = FI->getOperand(0);
9136 MatchIsOpZero = true;
9137 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9138 MatchOp = TI->getOperand(1);
9139 OtherOpT = TI->getOperand(0);
9140 OtherOpF = FI->getOperand(1);
9141 MatchIsOpZero = true;
9142 } else {
9143 return 0;
9144 }
9145
9146 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009147 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9148 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009149 InsertNewInstBefore(NewSI, SI);
9150
9151 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9152 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009153 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009154 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009155 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009156 }
Edwin Törökbd448e32009-07-14 16:55:14 +00009157 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009158 return 0;
9159}
9160
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009161static bool isSelect01(Constant *C1, Constant *C2) {
9162 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9163 if (!C1I)
9164 return false;
9165 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9166 if (!C2I)
9167 return false;
9168 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9169}
9170
9171/// FoldSelectIntoOp - Try fold the select into one of the operands to
9172/// facilitate further optimization.
9173Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9174 Value *FalseVal) {
9175 // See the comment above GetSelectFoldableOperands for a description of the
9176 // transformation we are doing here.
9177 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9178 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9179 !isa<Constant>(FalseVal)) {
9180 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9181 unsigned OpToFold = 0;
9182 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9183 OpToFold = 1;
9184 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9185 OpToFold = 2;
9186 }
9187
9188 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009189 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009190 Value *OOp = TVI->getOperand(2-OpToFold);
9191 // Avoid creating select between 2 constants unless it's selecting
9192 // between 0 and 1.
9193 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9194 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9195 InsertNewInstBefore(NewSel, SI);
9196 NewSel->takeName(TVI);
9197 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9198 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009199 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009200 }
9201 }
9202 }
9203 }
9204 }
9205
9206 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9207 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9208 !isa<Constant>(TrueVal)) {
9209 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9210 unsigned OpToFold = 0;
9211 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9212 OpToFold = 1;
9213 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9214 OpToFold = 2;
9215 }
9216
9217 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009218 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009219 Value *OOp = FVI->getOperand(2-OpToFold);
9220 // Avoid creating select between 2 constants unless it's selecting
9221 // between 0 and 1.
9222 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9223 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9224 InsertNewInstBefore(NewSel, SI);
9225 NewSel->takeName(FVI);
9226 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9227 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009228 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009229 }
9230 }
9231 }
9232 }
9233 }
9234
9235 return 0;
9236}
9237
Dan Gohman58c09632008-09-16 18:46:06 +00009238/// visitSelectInstWithICmp - Visit a SelectInst that has an
9239/// ICmpInst as its first operand.
9240///
9241Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9242 ICmpInst *ICI) {
9243 bool Changed = false;
9244 ICmpInst::Predicate Pred = ICI->getPredicate();
9245 Value *CmpLHS = ICI->getOperand(0);
9246 Value *CmpRHS = ICI->getOperand(1);
9247 Value *TrueVal = SI.getTrueValue();
9248 Value *FalseVal = SI.getFalseValue();
9249
9250 // Check cases where the comparison is with a constant that
9251 // can be adjusted to fit the min/max idiom. We may edit ICI in
9252 // place here, so make sure the select is the only user.
9253 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009254 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009255 switch (Pred) {
9256 default: break;
9257 case ICmpInst::ICMP_ULT:
9258 case ICmpInst::ICMP_SLT: {
9259 // X < MIN ? T : F --> F
9260 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9261 return ReplaceInstUsesWith(SI, FalseVal);
9262 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009263 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009264 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9265 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9266 Pred = ICmpInst::getSwappedPredicate(Pred);
9267 CmpRHS = AdjustedRHS;
9268 std::swap(FalseVal, TrueVal);
9269 ICI->setPredicate(Pred);
9270 ICI->setOperand(1, CmpRHS);
9271 SI.setOperand(1, TrueVal);
9272 SI.setOperand(2, FalseVal);
9273 Changed = true;
9274 }
9275 break;
9276 }
9277 case ICmpInst::ICMP_UGT:
9278 case ICmpInst::ICMP_SGT: {
9279 // X > MAX ? T : F --> F
9280 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9281 return ReplaceInstUsesWith(SI, FalseVal);
9282 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009283 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009284 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9285 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9286 Pred = ICmpInst::getSwappedPredicate(Pred);
9287 CmpRHS = AdjustedRHS;
9288 std::swap(FalseVal, TrueVal);
9289 ICI->setPredicate(Pred);
9290 ICI->setOperand(1, CmpRHS);
9291 SI.setOperand(1, TrueVal);
9292 SI.setOperand(2, FalseVal);
9293 Changed = true;
9294 }
9295 break;
9296 }
9297 }
9298
Dan Gohman35b76162008-10-30 20:40:10 +00009299 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9300 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009301 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohmancdff2122009-08-12 16:23:25 +00009302 if (match(TrueVal, m_ConstantInt<-1>()) &&
9303 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009304 Pred = ICI->getPredicate();
Dan Gohmancdff2122009-08-12 16:23:25 +00009305 else if (match(TrueVal, m_ConstantInt<0>()) &&
9306 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009307 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9308
Dan Gohman35b76162008-10-30 20:40:10 +00009309 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9310 // If we are just checking for a icmp eq of a single bit and zext'ing it
9311 // to an integer, then shift the bit to the appropriate place and then
9312 // cast to integer to avoid the comparison.
9313 const APInt &Op1CV = CI->getValue();
9314
9315 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9316 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9317 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009318 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009319 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00009320 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009321 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009322 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00009323 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00009324 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009325 if (In->getType() != SI.getType())
9326 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009327 true/*SExt*/, "tmp", ICI);
9328
9329 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohmancdff2122009-08-12 16:23:25 +00009330 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman35b76162008-10-30 20:40:10 +00009331 In->getName()+".not"), *ICI);
9332
9333 return ReplaceInstUsesWith(SI, In);
9334 }
9335 }
9336 }
9337
Dan Gohman58c09632008-09-16 18:46:06 +00009338 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9339 // Transform (X == Y) ? X : Y -> Y
9340 if (Pred == ICmpInst::ICMP_EQ)
9341 return ReplaceInstUsesWith(SI, FalseVal);
9342 // Transform (X != Y) ? X : Y -> X
9343 if (Pred == ICmpInst::ICMP_NE)
9344 return ReplaceInstUsesWith(SI, TrueVal);
9345 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9346
9347 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9348 // Transform (X == Y) ? Y : X -> X
9349 if (Pred == ICmpInst::ICMP_EQ)
9350 return ReplaceInstUsesWith(SI, FalseVal);
9351 // Transform (X != Y) ? Y : X -> Y
9352 if (Pred == ICmpInst::ICMP_NE)
9353 return ReplaceInstUsesWith(SI, TrueVal);
9354 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9355 }
9356
9357 /// NOTE: if we wanted to, this is where to detect integer ABS
9358
9359 return Changed ? &SI : 0;
9360}
9361
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009362Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9363 Value *CondVal = SI.getCondition();
9364 Value *TrueVal = SI.getTrueValue();
9365 Value *FalseVal = SI.getFalseValue();
9366
9367 // select true, X, Y -> X
9368 // select false, X, Y -> Y
9369 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9370 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9371
9372 // select C, X, X -> X
9373 if (TrueVal == FalseVal)
9374 return ReplaceInstUsesWith(SI, TrueVal);
9375
9376 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9377 return ReplaceInstUsesWith(SI, FalseVal);
9378 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9379 return ReplaceInstUsesWith(SI, TrueVal);
9380 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9381 if (isa<Constant>(TrueVal))
9382 return ReplaceInstUsesWith(SI, TrueVal);
9383 else
9384 return ReplaceInstUsesWith(SI, FalseVal);
9385 }
9386
9387 if (SI.getType() == Type::Int1Ty) {
9388 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9389 if (C->getZExtValue()) {
9390 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009391 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009392 } else {
9393 // Change: A = select B, false, C --> A = and !B, C
9394 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009395 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009396 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009397 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009398 }
9399 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9400 if (C->getZExtValue() == false) {
9401 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009402 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009403 } else {
9404 // Change: A = select B, C, true --> A = or !B, C
9405 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009406 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009407 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009408 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009409 }
9410 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009411
9412 // select a, b, a -> a&b
9413 // select a, a, b -> a|b
9414 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009415 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009416 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009417 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009418 }
9419
9420 // Selecting between two integer constants?
9421 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9422 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9423 // select C, 1, 0 -> zext C to int
9424 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009425 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009426 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9427 // select C, 0, 1 -> zext !C to int
9428 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009429 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009430 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009431 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009432 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009433
9434 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009435 // If one of the constants is zero (we know they can't both be) and we
9436 // have an icmp instruction with zero, and we have an 'and' with the
9437 // non-constant value, eliminate this whole mess. This corresponds to
9438 // cases like this: ((X & 27) ? 27 : 0)
9439 if (TrueValC->isZero() || FalseValC->isZero())
9440 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9441 cast<Constant>(IC->getOperand(1))->isNullValue())
9442 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9443 if (ICA->getOpcode() == Instruction::And &&
9444 isa<ConstantInt>(ICA->getOperand(1)) &&
9445 (ICA->getOperand(1) == TrueValC ||
9446 ICA->getOperand(1) == FalseValC) &&
9447 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9448 // Okay, now we know that everything is set up, we just don't
9449 // know whether we have a icmp_ne or icmp_eq and whether the
9450 // true or false val is the zero.
9451 bool ShouldNotVal = !TrueValC->isZero();
9452 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9453 Value *V = ICA;
9454 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009455 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009456 Instruction::Xor, V, ICA->getOperand(1)), SI);
9457 return ReplaceInstUsesWith(SI, V);
9458 }
9459 }
9460 }
9461
9462 // See if we are selecting two values based on a comparison of the two values.
9463 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9464 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9465 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009466 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9467 // This is not safe in general for floating point:
9468 // consider X== -0, Y== +0.
9469 // It becomes safe if either operand is a nonzero constant.
9470 ConstantFP *CFPt, *CFPf;
9471 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9472 !CFPt->getValueAPF().isZero()) ||
9473 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9474 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009475 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009476 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009477 // Transform (X != Y) ? X : Y -> X
9478 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9479 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009480 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009481
9482 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9483 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009484 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9485 // This is not safe in general for floating point:
9486 // consider X== -0, Y== +0.
9487 // It becomes safe if either operand is a nonzero constant.
9488 ConstantFP *CFPt, *CFPf;
9489 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9490 !CFPt->getValueAPF().isZero()) ||
9491 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9492 !CFPf->getValueAPF().isZero()))
9493 return ReplaceInstUsesWith(SI, FalseVal);
9494 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009495 // Transform (X != Y) ? Y : X -> Y
9496 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9497 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009498 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009499 }
Dan Gohman58c09632008-09-16 18:46:06 +00009500 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009501 }
9502
9503 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009504 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9505 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9506 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009507
9508 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9509 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9510 if (TI->hasOneUse() && FI->hasOneUse()) {
9511 Instruction *AddOp = 0, *SubOp = 0;
9512
9513 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9514 if (TI->getOpcode() == FI->getOpcode())
9515 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9516 return IV;
9517
9518 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9519 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009520 if ((TI->getOpcode() == Instruction::Sub &&
9521 FI->getOpcode() == Instruction::Add) ||
9522 (TI->getOpcode() == Instruction::FSub &&
9523 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009524 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009525 } else if ((FI->getOpcode() == Instruction::Sub &&
9526 TI->getOpcode() == Instruction::Add) ||
9527 (FI->getOpcode() == Instruction::FSub &&
9528 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009529 AddOp = TI; SubOp = FI;
9530 }
9531
9532 if (AddOp) {
9533 Value *OtherAddOp = 0;
9534 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9535 OtherAddOp = AddOp->getOperand(1);
9536 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9537 OtherAddOp = AddOp->getOperand(0);
9538 }
9539
9540 if (OtherAddOp) {
9541 // So at this point we know we have (Y -> OtherAddOp):
9542 // select C, (add X, Y), (sub X, Z)
9543 Value *NegVal; // Compute -Z
9544 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00009545 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009546 } else {
9547 NegVal = InsertNewInstBefore(
Dan Gohmancdff2122009-08-12 16:23:25 +00009548 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00009549 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009550 }
9551
9552 Value *NewTrueOp = OtherAddOp;
9553 Value *NewFalseOp = NegVal;
9554 if (AddOp != TI)
9555 std::swap(NewTrueOp, NewFalseOp);
9556 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009557 SelectInst::Create(CondVal, NewTrueOp,
9558 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009559
9560 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009561 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009562 }
9563 }
9564 }
9565
9566 // See if we can fold the select into one of our operands.
9567 if (SI.getType()->isInteger()) {
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009568 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9569 if (FoldI)
9570 return FoldI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009571 }
9572
9573 if (BinaryOperator::isNot(CondVal)) {
9574 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9575 SI.setOperand(1, FalseVal);
9576 SI.setOperand(2, TrueVal);
9577 return &SI;
9578 }
9579
9580 return 0;
9581}
9582
Dan Gohman2d648bb2008-04-10 18:43:06 +00009583/// EnforceKnownAlignment - If the specified pointer points to an object that
9584/// we control, modify the object's alignment to PrefAlign. This isn't
9585/// often possible though. If alignment is important, a more reliable approach
9586/// is to simply align all global variables and allocation instructions to
9587/// their preferred alignment from the beginning.
9588///
9589static unsigned EnforceKnownAlignment(Value *V,
9590 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009591
Dan Gohman2d648bb2008-04-10 18:43:06 +00009592 User *U = dyn_cast<User>(V);
9593 if (!U) return Align;
9594
Dan Gohman9545fb02009-07-17 20:47:02 +00009595 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009596 default: break;
9597 case Instruction::BitCast:
9598 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9599 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009600 // If all indexes are zero, it is just the alignment of the base pointer.
9601 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009602 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009603 if (!isa<Constant>(*i) ||
9604 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009605 AllZeroOperands = false;
9606 break;
9607 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009608
9609 if (AllZeroOperands) {
9610 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009611 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009612 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009613 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009614 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009615 }
9616
9617 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9618 // If there is a large requested alignment and we can, bump up the alignment
9619 // of the global.
9620 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009621 if (GV->getAlignment() >= PrefAlign)
9622 Align = GV->getAlignment();
9623 else {
9624 GV->setAlignment(PrefAlign);
9625 Align = PrefAlign;
9626 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009627 }
9628 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9629 // If there is a requested alignment and if this is an alloca, round up. We
9630 // don't do this for malloc, because some systems can't respect the request.
9631 if (isa<AllocaInst>(AI)) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009632 if (AI->getAlignment() >= PrefAlign)
9633 Align = AI->getAlignment();
9634 else {
9635 AI->setAlignment(PrefAlign);
9636 Align = PrefAlign;
9637 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009638 }
9639 }
9640
9641 return Align;
9642}
9643
9644/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9645/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9646/// and it is more than the alignment of the ultimate object, see if we can
9647/// increase the alignment of the ultimate object, making this check succeed.
9648unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9649 unsigned PrefAlign) {
9650 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9651 sizeof(PrefAlign) * CHAR_BIT;
9652 APInt Mask = APInt::getAllOnesValue(BitWidth);
9653 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9654 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9655 unsigned TrailZ = KnownZero.countTrailingOnes();
9656 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9657
9658 if (PrefAlign > Align)
9659 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9660
9661 // We don't need to make any adjustment.
9662 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009663}
9664
Chris Lattner00ae5132008-01-13 23:50:23 +00009665Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009666 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009667 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009668 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009669 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009670
9671 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009672 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009673 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00009674 return MI;
9675 }
9676
9677 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9678 // load/store.
9679 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9680 if (MemOpLength == 0) return 0;
9681
Chris Lattnerc669fb62008-01-14 00:28:35 +00009682 // Source and destination pointer types are always "i8*" for intrinsic. See
9683 // if the size is something we can handle with a single primitive load/store.
9684 // A single load+store correctly handles overlapping memory in the memmove
9685 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009686 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009687 if (Size == 0) return MI; // Delete this mem transfer.
9688
9689 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009690 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009691
Chris Lattnerc669fb62008-01-14 00:28:35 +00009692 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00009693 Type *NewPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009694 PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009695
9696 // Memcpy forces the use of i8* for the source and destination. That means
9697 // that if you're using memcpy to move one double around, you'll get a cast
9698 // from double* to i8*. We'd much rather use a double load+store rather than
9699 // an i64 load+store, here because this improves the odds that the source or
9700 // dest address will be promotable. See if we can find a better type than the
9701 // integer datatype.
9702 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9703 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00009704 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009705 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9706 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009707 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009708 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9709 if (STy->getNumElements() == 1)
9710 SrcETy = STy->getElementType(0);
9711 else
9712 break;
9713 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9714 if (ATy->getNumElements() == 1)
9715 SrcETy = ATy->getElementType();
9716 else
9717 break;
9718 } else
9719 break;
9720 }
9721
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009722 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009723 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009724 }
9725 }
9726
9727
Chris Lattner00ae5132008-01-13 23:50:23 +00009728 // If the memcpy/memmove provides better alignment info than we can
9729 // infer, use it.
9730 SrcAlign = std::max(SrcAlign, CopyAlign);
9731 DstAlign = std::max(DstAlign, CopyAlign);
9732
9733 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9734 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009735 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9736 InsertNewInstBefore(L, *MI);
9737 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9738
9739 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009740 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009741 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009742}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009743
Chris Lattner5af8a912008-04-30 06:39:11 +00009744Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9745 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009746 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009747 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009748 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +00009749 return MI;
9750 }
9751
9752 // Extract the length and alignment and fill if they are constant.
9753 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9754 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9755 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9756 return 0;
9757 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009758 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009759
9760 // If the length is zero, this is a no-op
9761 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9762
9763 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9764 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009765 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00009766
9767 Value *Dest = MI->getDest();
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009768 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009769
9770 // Alignment 0 is identity for alignment 1 for memset, but not store.
9771 if (Alignment == 0) Alignment = 1;
9772
9773 // Extract the fill value and store.
9774 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +00009775 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +00009776 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009777
9778 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009779 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00009780 return MI;
9781 }
9782
9783 return 0;
9784}
9785
9786
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009787/// visitCallInst - CallInst simplification. This mostly only handles folding
9788/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9789/// the heavy lifting.
9790///
9791Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraa295aa2009-05-13 17:39:14 +00009792 // If the caller function is nounwind, mark the call as nounwind, even if the
9793 // callee isn't.
9794 if (CI.getParent()->getParent()->doesNotThrow() &&
9795 !CI.doesNotThrow()) {
9796 CI.setDoesNotThrow();
9797 return &CI;
9798 }
9799
9800
9801
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009802 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9803 if (!II) return visitCallSite(&CI);
9804
9805 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9806 // visitCallSite.
9807 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9808 bool Changed = false;
9809
9810 // memmove/cpy/set of zero bytes is a noop.
9811 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9812 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9813
9814 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9815 if (CI->getZExtValue() == 1) {
9816 // Replace the instruction with just byte operations. We would
9817 // transform other cases to loads/stores, but we don't know if
9818 // alignment is sufficient.
9819 }
9820 }
9821
9822 // If we have a memmove and the source operation is a constant global,
9823 // then the source and dest pointers can't alias, so we can change this
9824 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009825 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009826 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9827 if (GVSrc->isConstant()) {
9828 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009829 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9830 const Type *Tys[1];
9831 Tys[0] = CI.getOperand(3)->getType();
9832 CI.setOperand(0,
9833 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009834 Changed = true;
9835 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009836
9837 // memmove(x,x,size) -> noop.
9838 if (MMI->getSource() == MMI->getDest())
9839 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009840 }
9841
9842 // If we can determine a pointer alignment that is bigger than currently
9843 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009844 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009845 if (Instruction *I = SimplifyMemTransfer(MI))
9846 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009847 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9848 if (Instruction *I = SimplifyMemSet(MSI))
9849 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009850 }
9851
9852 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009853 }
9854
9855 switch (II->getIntrinsicID()) {
9856 default: break;
9857 case Intrinsic::bswap:
9858 // bswap(bswap(x)) -> x
9859 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9860 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9861 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9862 break;
9863 case Intrinsic::ppc_altivec_lvx:
9864 case Intrinsic::ppc_altivec_lvxl:
9865 case Intrinsic::x86_sse_loadu_ps:
9866 case Intrinsic::x86_sse2_loadu_pd:
9867 case Intrinsic::x86_sse2_loadu_dq:
9868 // Turn PPC lvx -> load if the pointer is known aligned.
9869 // Turn X86 loadups -> load if the pointer is known aligned.
9870 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9871 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009872 PointerType::getUnqual(II->getType()),
Chris Lattner989ba312008-06-18 04:33:20 +00009873 CI);
9874 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009875 }
Chris Lattner989ba312008-06-18 04:33:20 +00009876 break;
9877 case Intrinsic::ppc_altivec_stvx:
9878 case Intrinsic::ppc_altivec_stvxl:
9879 // Turn stvx -> store if the pointer is known aligned.
9880 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9881 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009882 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner989ba312008-06-18 04:33:20 +00009883 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9884 return new StoreInst(II->getOperand(1), Ptr);
9885 }
9886 break;
9887 case Intrinsic::x86_sse_storeu_ps:
9888 case Intrinsic::x86_sse2_storeu_pd:
9889 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009890 // Turn X86 storeu -> store if the pointer is known aligned.
9891 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9892 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009893 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner989ba312008-06-18 04:33:20 +00009894 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9895 return new StoreInst(II->getOperand(2), Ptr);
9896 }
9897 break;
9898
9899 case Intrinsic::x86_sse_cvttss2si: {
9900 // These intrinsics only demands the 0th element of its input vector. If
9901 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00009902 unsigned VWidth =
9903 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9904 APInt DemandedElts(VWidth, 1);
9905 APInt UndefElts(VWidth, 0);
9906 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00009907 UndefElts)) {
9908 II->setOperand(1, V);
9909 return II;
9910 }
9911 break;
9912 }
9913
9914 case Intrinsic::ppc_altivec_vperm:
9915 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9916 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9917 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009918
Chris Lattner989ba312008-06-18 04:33:20 +00009919 // Check that all of the elements are integer constants or undefs.
9920 bool AllEltsOk = true;
9921 for (unsigned i = 0; i != 16; ++i) {
9922 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9923 !isa<UndefValue>(Mask->getOperand(i))) {
9924 AllEltsOk = false;
9925 break;
9926 }
9927 }
9928
9929 if (AllEltsOk) {
9930 // Cast the input vectors to byte vectors.
9931 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9932 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersonb99ecca2009-07-30 23:03:37 +00009933 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009934
Chris Lattner989ba312008-06-18 04:33:20 +00009935 // Only extract each element once.
9936 Value *ExtractedElts[32];
9937 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9938
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009939 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00009940 if (isa<UndefValue>(Mask->getOperand(i)))
9941 continue;
9942 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9943 Idx &= 31; // Match the hardware behavior.
9944
9945 if (ExtractedElts[Idx] == 0) {
9946 Instruction *Elt =
Eric Christopher1ba36872009-07-25 02:28:41 +00009947 ExtractElementInst::Create(Idx < 16 ? Op0 : Op1,
Owen Andersoneacb44d2009-07-24 23:12:02 +00009948 ConstantInt::get(Type::Int32Ty, Idx&15, false), "tmp");
Chris Lattner989ba312008-06-18 04:33:20 +00009949 InsertNewInstBefore(Elt, CI);
9950 ExtractedElts[Idx] = Elt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009951 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009952
Chris Lattner989ba312008-06-18 04:33:20 +00009953 // Insert this value into the result vector.
9954 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Andersoneacb44d2009-07-24 23:12:02 +00009955 ConstantInt::get(Type::Int32Ty, i, false),
Owen Anderson9f5b2aa2009-07-14 23:09:55 +00009956 "tmp");
Chris Lattner989ba312008-06-18 04:33:20 +00009957 InsertNewInstBefore(cast<Instruction>(Result), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009958 }
Chris Lattner989ba312008-06-18 04:33:20 +00009959 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009960 }
Chris Lattner989ba312008-06-18 04:33:20 +00009961 }
9962 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009963
Chris Lattner989ba312008-06-18 04:33:20 +00009964 case Intrinsic::stackrestore: {
9965 // If the save is right next to the restore, remove the restore. This can
9966 // happen when variable allocas are DCE'd.
9967 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9968 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9969 BasicBlock::iterator BI = SS;
9970 if (&*++BI == II)
9971 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009972 }
Chris Lattner989ba312008-06-18 04:33:20 +00009973 }
9974
9975 // Scan down this block to see if there is another stack restore in the
9976 // same block without an intervening call/alloca.
9977 BasicBlock::iterator BI = II;
9978 TerminatorInst *TI = II->getParent()->getTerminator();
9979 bool CannotRemove = false;
9980 for (++BI; &*BI != TI; ++BI) {
9981 if (isa<AllocaInst>(BI)) {
9982 CannotRemove = true;
9983 break;
9984 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00009985 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9986 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9987 // If there is a stackrestore below this one, remove this one.
9988 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9989 return EraseInstFromFunction(CI);
9990 // Otherwise, ignore the intrinsic.
9991 } else {
9992 // If we found a non-intrinsic call, we can't remove the stack
9993 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00009994 CannotRemove = true;
9995 break;
9996 }
Chris Lattner989ba312008-06-18 04:33:20 +00009997 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009998 }
Chris Lattner989ba312008-06-18 04:33:20 +00009999
10000 // If the stack restore is in a return/unwind block and if there are no
10001 // allocas or calls between the restore and the return, nuke the restore.
10002 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10003 return EraseInstFromFunction(CI);
10004 break;
10005 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010006 }
10007
10008 return visitCallSite(II);
10009}
10010
10011// InvokeInst simplification
10012//
10013Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10014 return visitCallSite(&II);
10015}
10016
Dale Johannesen96021832008-04-25 21:16:07 +000010017/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10018/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +000010019static bool isSafeToEliminateVarargsCast(const CallSite CS,
10020 const CastInst * const CI,
10021 const TargetData * const TD,
10022 const int ix) {
10023 if (!CI->isLosslessCast())
10024 return false;
10025
10026 // The size of ByVal arguments is derived from the type, so we
10027 // can't change to a type with a different size. If the size were
10028 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +000010029 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +000010030 return true;
10031
10032 const Type* SrcTy =
10033 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10034 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10035 if (!SrcTy->isSized() || !DstTy->isSized())
10036 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +000010037 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +000010038 return false;
10039 return true;
10040}
10041
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010042// visitCallSite - Improvements for call and invoke instructions.
10043//
10044Instruction *InstCombiner::visitCallSite(CallSite CS) {
10045 bool Changed = false;
10046
10047 // If the callee is a constexpr cast of a function, attempt to move the cast
10048 // to the arguments of the call/invoke.
10049 if (transformConstExprCastCall(CS)) return 0;
10050
10051 Value *Callee = CS.getCalledValue();
10052
10053 if (Function *CalleeF = dyn_cast<Function>(Callee))
10054 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10055 Instruction *OldCall = CS.getInstruction();
10056 // If the call and callee calling conventions don't match, this call must
10057 // be unreachable, as the call is undefined.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010058 new StoreInst(ConstantInt::getTrue(*Context),
Owen Andersonb99ecca2009-07-30 23:03:37 +000010059 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Owen Anderson24be4c12009-07-03 00:17:18 +000010060 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010061 if (!OldCall->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +000010062 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010063 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10064 return EraseInstFromFunction(*OldCall);
10065 return 0;
10066 }
10067
10068 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10069 // This instruction is not reachable, just remove it. We insert a store to
10070 // undef so that we know that this code is not reachable, despite the fact
10071 // that we can't modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010072 new StoreInst(ConstantInt::getTrue(*Context),
Owen Andersonb99ecca2009-07-30 23:03:37 +000010073 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010074 CS.getInstruction());
10075
10076 if (!CS.getInstruction()->use_empty())
10077 CS.getInstruction()->
Owen Andersonb99ecca2009-07-30 23:03:37 +000010078 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010079
10080 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10081 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010082 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson4f720fa2009-07-31 17:39:07 +000010083 ConstantInt::getTrue(*Context), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010084 }
10085 return EraseInstFromFunction(*CS.getInstruction());
10086 }
10087
Duncan Sands74833f22007-09-17 10:26:40 +000010088 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10089 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10090 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10091 return transformCallThroughTrampoline(CS);
10092
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010093 const PointerType *PTy = cast<PointerType>(Callee->getType());
10094 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10095 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +000010096 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010097 // See if we can optimize any arguments passed through the varargs area of
10098 // the call.
10099 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +000010100 E = CS.arg_end(); I != E; ++I, ++ix) {
10101 CastInst *CI = dyn_cast<CastInst>(*I);
10102 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10103 *I = CI->getOperand(0);
10104 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010105 }
Dale Johannesen35615462008-04-23 18:34:37 +000010106 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010107 }
10108
Duncan Sands2937e352007-12-19 21:13:37 +000010109 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010110 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010111 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010112 Changed = true;
10113 }
10114
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010115 return Changed ? CS.getInstruction() : 0;
10116}
10117
10118// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10119// attempt to move the cast to the arguments of the call/invoke.
10120//
10121bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10122 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10123 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10124 if (CE->getOpcode() != Instruction::BitCast ||
10125 !isa<Function>(CE->getOperand(0)))
10126 return false;
10127 Function *Callee = cast<Function>(CE->getOperand(0));
10128 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010129 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010130
10131 // Okay, this is a cast from a function to a different type. Unless doing so
10132 // would cause a type conversion of one of our arguments, change this call to
10133 // be a direct call with arguments casted to the appropriate types.
10134 //
10135 const FunctionType *FT = Callee->getFunctionType();
10136 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010137 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010138
Duncan Sands7901ce12008-06-01 07:38:42 +000010139 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010140 return false; // TODO: Handle multiple return values.
10141
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010142 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010143 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010144 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010145 // Conversion is ok if changing from one pointer type to another or from
10146 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +000010147 !((isa<PointerType>(OldRetTy) || !TD ||
10148 OldRetTy == TD->getIntPtrType()) &&
10149 (isa<PointerType>(NewRetTy) || !TD ||
10150 NewRetTy == TD->getIntPtrType())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010151 return false; // Cannot transform this return value.
10152
Duncan Sands5c489582008-01-06 10:12:28 +000010153 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010154 // void -> non-void is handled specially
Duncan Sands7901ce12008-06-01 07:38:42 +000010155 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010156 return false; // Cannot transform this return value.
10157
Chris Lattner1c8733e2008-03-12 17:45:29 +000010158 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010159 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010160 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010161 return false; // Attribute not compatible with transformed value.
10162 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010163
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010164 // If the callsite is an invoke instruction, and the return value is used by
10165 // a PHI node in a successor, we cannot change the return type of the call
10166 // because there is no place to put the cast instruction (without breaking
10167 // the critical edge). Bail out in this case.
10168 if (!Caller->use_empty())
10169 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10170 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10171 UI != E; ++UI)
10172 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10173 if (PN->getParent() == II->getNormalDest() ||
10174 PN->getParent() == II->getUnwindDest())
10175 return false;
10176 }
10177
10178 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10179 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10180
10181 CallSite::arg_iterator AI = CS.arg_begin();
10182 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10183 const Type *ParamTy = FT->getParamType(i);
10184 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010185
10186 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010187 return false; // Cannot transform this parameter value.
10188
Devang Patelf2a4a922008-09-26 22:53:05 +000010189 if (CallerPAL.getParamAttributes(i + 1)
10190 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010191 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010192
Duncan Sands7901ce12008-06-01 07:38:42 +000010193 // Converting from one pointer type to another or between a pointer and an
10194 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010195 bool isConvertible = ActTy == ParamTy ||
Dan Gohmana80e2712009-07-21 23:21:54 +000010196 (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10197 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010198 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010199 }
10200
10201 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10202 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010203 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010204
Chris Lattner1c8733e2008-03-12 17:45:29 +000010205 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10206 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010207 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010208 // won't be dropping them. Check that these extra arguments have attributes
10209 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010210 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10211 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010212 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010213 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010214 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010215 return false;
10216 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010217
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010218 // Okay, we decided that this is a safe thing to do: go ahead and start
10219 // inserting cast instructions as necessary...
10220 std::vector<Value*> Args;
10221 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010222 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010223 attrVec.reserve(NumCommonArgs);
10224
10225 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010226 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010227
10228 // If the return value is not being used, the type may not be compatible
10229 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010230 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010231
10232 // Add the new return attributes.
10233 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010234 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010235
10236 AI = CS.arg_begin();
10237 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10238 const Type *ParamTy = FT->getParamType(i);
10239 if ((*AI)->getType() == ParamTy) {
10240 Args.push_back(*AI);
10241 } else {
10242 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10243 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010244 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010245 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10246 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010247
10248 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010249 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010250 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010251 }
10252
10253 // If the function takes more arguments than the call was taking, add them
10254 // now...
10255 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +000010256 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010257
10258 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010259 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010260 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +000010261 errs() << "WARNING: While resolving call to function '"
10262 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010263 } else {
10264 // Add all of the arguments in their promoted form to the arg list...
10265 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10266 const Type *PTy = getPromotedType((*AI)->getType());
10267 if (PTy != (*AI)->getType()) {
10268 // Must promote to pass through va_arg area!
10269 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10270 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010271 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010272 InsertNewInstBefore(Cast, *Caller);
10273 Args.push_back(Cast);
10274 } else {
10275 Args.push_back(*AI);
10276 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010277
Duncan Sands4ced1f82008-01-13 08:02:44 +000010278 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010279 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010280 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010281 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010282 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010283 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010284
Devang Patelf2a4a922008-09-26 22:53:05 +000010285 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10286 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10287
Duncan Sands7901ce12008-06-01 07:38:42 +000010288 if (NewRetTy == Type::VoidTy)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010289 Caller->setName(""); // Void type should not have a name.
10290
Eric Christopher3e7381f2009-07-25 02:45:27 +000010291 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10292 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010293
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010294 Instruction *NC;
10295 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010296 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010297 Args.begin(), Args.end(),
10298 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010299 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010300 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010301 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010302 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10303 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010304 CallInst *CI = cast<CallInst>(Caller);
10305 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010306 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010307 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010308 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010309 }
10310
10311 // Insert a cast of the return type as necessary.
10312 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010313 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010314 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010315 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010316 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010317 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010318
10319 // If this is an invoke instruction, we should insert it after the first
10320 // non-phi, instruction in the normal successor block.
10321 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010322 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010323 InsertNewInstBefore(NC, *I);
10324 } else {
10325 // Otherwise, it's a call, just insert cast right after the call instr
10326 InsertNewInstBefore(NC, *Caller);
10327 }
10328 AddUsersToWorkList(*Caller);
10329 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010330 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010331 }
10332 }
10333
10334 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10335 Caller->replaceAllUsesWith(NV);
10336 Caller->eraseFromParent();
10337 RemoveFromWorkList(Caller);
10338 return true;
10339}
10340
Duncan Sands74833f22007-09-17 10:26:40 +000010341// transformCallThroughTrampoline - Turn a call to a function created by the
10342// init_trampoline intrinsic into a direct call to the underlying function.
10343//
10344Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10345 Value *Callee = CS.getCalledValue();
10346 const PointerType *PTy = cast<PointerType>(Callee->getType());
10347 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010348 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010349
10350 // If the call already has the 'nest' attribute somewhere then give up -
10351 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010352 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010353 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010354
10355 IntrinsicInst *Tramp =
10356 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10357
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010358 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010359 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10360 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10361
Devang Pateld222f862008-09-25 21:00:45 +000010362 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010363 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010364 unsigned NestIdx = 1;
10365 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010366 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010367
10368 // Look for a parameter marked with the 'nest' attribute.
10369 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10370 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010371 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010372 // Record the parameter type and any other attributes.
10373 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010374 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010375 break;
10376 }
10377
10378 if (NestTy) {
10379 Instruction *Caller = CS.getInstruction();
10380 std::vector<Value*> NewArgs;
10381 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10382
Devang Pateld222f862008-09-25 21:00:45 +000010383 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010384 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010385
Duncan Sands74833f22007-09-17 10:26:40 +000010386 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010387 // mean appending it. Likewise for attributes.
10388
Devang Patelf2a4a922008-09-26 22:53:05 +000010389 // Add any result attributes.
10390 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010391 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010392
Duncan Sands74833f22007-09-17 10:26:40 +000010393 {
10394 unsigned Idx = 1;
10395 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10396 do {
10397 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010398 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010399 Value *NestVal = Tramp->getOperand(3);
10400 if (NestVal->getType() != NestTy)
10401 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10402 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010403 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010404 }
10405
10406 if (I == E)
10407 break;
10408
Duncan Sands48b81112008-01-14 19:52:09 +000010409 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010410 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010411 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010412 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010413 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010414
10415 ++Idx, ++I;
10416 } while (1);
10417 }
10418
Devang Patelf2a4a922008-09-26 22:53:05 +000010419 // Add any function attributes.
10420 if (Attributes Attr = Attrs.getFnAttributes())
10421 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10422
Duncan Sands74833f22007-09-17 10:26:40 +000010423 // The trampoline may have been bitcast to a bogus type (FTy).
10424 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010425 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010426
Duncan Sands74833f22007-09-17 10:26:40 +000010427 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010428 NewTypes.reserve(FTy->getNumParams()+1);
10429
Duncan Sands74833f22007-09-17 10:26:40 +000010430 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010431 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010432 {
10433 unsigned Idx = 1;
10434 FunctionType::param_iterator I = FTy->param_begin(),
10435 E = FTy->param_end();
10436
10437 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010438 if (Idx == NestIdx)
10439 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010440 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010441
10442 if (I == E)
10443 break;
10444
Duncan Sands48b81112008-01-14 19:52:09 +000010445 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010446 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010447
10448 ++Idx, ++I;
10449 } while (1);
10450 }
10451
10452 // Replace the trampoline call with a direct call. Let the generic
10453 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010454 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +000010455 FTy->isVarArg());
10456 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010457 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +000010458 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010459 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +000010460 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10461 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010462
10463 Instruction *NewCaller;
10464 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010465 NewCaller = InvokeInst::Create(NewCallee,
10466 II->getNormalDest(), II->getUnwindDest(),
10467 NewArgs.begin(), NewArgs.end(),
10468 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010469 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010470 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010471 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010472 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10473 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010474 if (cast<CallInst>(Caller)->isTailCall())
10475 cast<CallInst>(NewCaller)->setTailCall();
10476 cast<CallInst>(NewCaller)->
10477 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010478 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010479 }
10480 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10481 Caller->replaceAllUsesWith(NewCaller);
10482 Caller->eraseFromParent();
10483 RemoveFromWorkList(Caller);
10484 return 0;
10485 }
10486 }
10487
10488 // Replace the trampoline call with a direct call. Since there is no 'nest'
10489 // parameter, there is no need to adjust the argument list. Let the generic
10490 // code sort out any function type mismatches.
10491 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010492 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +000010493 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010494 CS.setCalledFunction(NewCallee);
10495 return CS.getInstruction();
10496}
10497
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010498/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10499/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10500/// and a single binop.
10501Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10502 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010503 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010504 unsigned Opc = FirstInst->getOpcode();
10505 Value *LHSVal = FirstInst->getOperand(0);
10506 Value *RHSVal = FirstInst->getOperand(1);
10507
10508 const Type *LHSType = LHSVal->getType();
10509 const Type *RHSType = RHSVal->getType();
10510
10511 // Scan to see if all operands are the same opcode, all have one use, and all
10512 // kill their operands (i.e. the operands have one use).
Chris Lattner9e1916e2008-12-01 02:34:36 +000010513 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010514 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10515 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10516 // Verify type of the LHS matches so we don't fold cmp's of different
10517 // types or GEP's with different index types.
10518 I->getOperand(0)->getType() != LHSType ||
10519 I->getOperand(1)->getType() != RHSType)
10520 return 0;
10521
10522 // If they are CmpInst instructions, check their predicates
10523 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10524 if (cast<CmpInst>(I)->getPredicate() !=
10525 cast<CmpInst>(FirstInst)->getPredicate())
10526 return 0;
10527
10528 // Keep track of which operand needs a phi node.
10529 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10530 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10531 }
10532
Chris Lattner30078012008-12-01 03:42:51 +000010533 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010534
10535 Value *InLHS = FirstInst->getOperand(0);
10536 Value *InRHS = FirstInst->getOperand(1);
10537 PHINode *NewLHS = 0, *NewRHS = 0;
10538 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010539 NewLHS = PHINode::Create(LHSType,
10540 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010541 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10542 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10543 InsertNewInstBefore(NewLHS, PN);
10544 LHSVal = NewLHS;
10545 }
10546
10547 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010548 NewRHS = PHINode::Create(RHSType,
10549 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010550 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10551 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10552 InsertNewInstBefore(NewRHS, PN);
10553 RHSVal = NewRHS;
10554 }
10555
10556 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010557 if (NewLHS || NewRHS) {
10558 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10559 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10560 if (NewLHS) {
10561 Value *NewInLHS = InInst->getOperand(0);
10562 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10563 }
10564 if (NewRHS) {
10565 Value *NewInRHS = InInst->getOperand(1);
10566 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10567 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010568 }
10569 }
10570
10571 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010572 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010573 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson6601fcd2009-07-09 23:48:35 +000010574 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10575 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010576}
10577
Chris Lattner9e1916e2008-12-01 02:34:36 +000010578Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10579 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10580
10581 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10582 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010583 // This is true if all GEP bases are allocas and if all indices into them are
10584 // constants.
10585 bool AllBasePointersAreAllocas = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010586
10587 // Scan to see if all operands are the same opcode, all have one use, and all
10588 // kill their operands (i.e. the operands have one use).
10589 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10590 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10591 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10592 GEP->getNumOperands() != FirstInst->getNumOperands())
10593 return 0;
10594
Chris Lattneradf354b2009-02-21 00:46:50 +000010595 // Keep track of whether or not all GEPs are of alloca pointers.
10596 if (AllBasePointersAreAllocas &&
10597 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10598 !GEP->hasAllConstantIndices()))
10599 AllBasePointersAreAllocas = false;
10600
Chris Lattner9e1916e2008-12-01 02:34:36 +000010601 // Compare the operand lists.
10602 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10603 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10604 continue;
10605
10606 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10607 // if one of the PHIs has a constant for the index. The index may be
10608 // substantially cheaper to compute for the constants, so making it a
10609 // variable index could pessimize the path. This also handles the case
10610 // for struct indices, which must always be constant.
10611 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10612 isa<ConstantInt>(GEP->getOperand(op)))
10613 return 0;
10614
10615 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10616 return 0;
10617 FixedOperands[op] = 0; // Needs a PHI.
10618 }
10619 }
10620
Chris Lattneradf354b2009-02-21 00:46:50 +000010621 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010622 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010623 // offset calculation, but all the predecessors will have to materialize the
10624 // stack address into a register anyway. We'd actually rather *clone* the
10625 // load up into the predecessors so that we have a load of a gep of an alloca,
10626 // which can usually all be folded into the load.
10627 if (AllBasePointersAreAllocas)
10628 return 0;
10629
Chris Lattner9e1916e2008-12-01 02:34:36 +000010630 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10631 // that is variable.
10632 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10633
10634 bool HasAnyPHIs = false;
10635 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10636 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10637 Value *FirstOp = FirstInst->getOperand(i);
10638 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10639 FirstOp->getName()+".pn");
10640 InsertNewInstBefore(NewPN, PN);
10641
10642 NewPN->reserveOperandSpace(e);
10643 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10644 OperandPhis[i] = NewPN;
10645 FixedOperands[i] = NewPN;
10646 HasAnyPHIs = true;
10647 }
10648
10649
10650 // Add all operands to the new PHIs.
10651 if (HasAnyPHIs) {
10652 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10653 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10654 BasicBlock *InBB = PN.getIncomingBlock(i);
10655
10656 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10657 if (PHINode *OpPhi = OperandPhis[op])
10658 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10659 }
10660 }
10661
10662 Value *Base = FixedOperands[0];
Dan Gohman17f46f72009-07-28 01:40:03 +000010663 GetElementPtrInst *GEP =
10664 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10665 FixedOperands.end());
10666 if (cast<GEPOperator>(FirstInst)->isInBounds())
10667 cast<GEPOperator>(GEP)->setIsInBounds(true);
10668 return GEP;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010669}
10670
10671
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010672/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10673/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010674/// obvious the value of the load is not changed from the point of the load to
10675/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010676///
10677/// Finally, it is safe, but not profitable, to sink a load targetting a
10678/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10679/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010680static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010681 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10682
10683 for (++BBI; BBI != E; ++BBI)
10684 if (BBI->mayWriteToMemory())
10685 return false;
10686
10687 // Check for non-address taken alloca. If not address-taken already, it isn't
10688 // profitable to do this xform.
10689 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10690 bool isAddressTaken = false;
10691 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10692 UI != E; ++UI) {
10693 if (isa<LoadInst>(UI)) continue;
10694 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10695 // If storing TO the alloca, then the address isn't taken.
10696 if (SI->getOperand(1) == AI) continue;
10697 }
10698 isAddressTaken = true;
10699 break;
10700 }
10701
Chris Lattneradf354b2009-02-21 00:46:50 +000010702 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010703 return false;
10704 }
10705
Chris Lattneradf354b2009-02-21 00:46:50 +000010706 // If this load is a load from a GEP with a constant offset from an alloca,
10707 // then we don't want to sink it. In its present form, it will be
10708 // load [constant stack offset]. Sinking it will cause us to have to
10709 // materialize the stack addresses in each predecessor in a register only to
10710 // do a shared load from register in the successor.
10711 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10712 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10713 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10714 return false;
10715
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010716 return true;
10717}
10718
10719
10720// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10721// operator and they all are only used by the PHI, PHI together their
10722// inputs, and do the operation once, to the result of the PHI.
10723Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10724 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10725
10726 // Scan the instruction, looking for input operations that can be folded away.
10727 // If all input operands to the phi are the same instruction (e.g. a cast from
10728 // the same type or "+42") we can pull the operation through the PHI, reducing
10729 // code size and simplifying code.
10730 Constant *ConstantOp = 0;
10731 const Type *CastSrcTy = 0;
10732 bool isVolatile = false;
10733 if (isa<CastInst>(FirstInst)) {
10734 CastSrcTy = FirstInst->getOperand(0)->getType();
10735 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10736 // Can fold binop, compare or shift here if the RHS is a constant,
10737 // otherwise call FoldPHIArgBinOpIntoPHI.
10738 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10739 if (ConstantOp == 0)
10740 return FoldPHIArgBinOpIntoPHI(PN);
10741 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10742 isVolatile = LI->isVolatile();
10743 // We can't sink the load if the loaded value could be modified between the
10744 // load and the PHI.
10745 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010746 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010747 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010748
10749 // If the PHI is of volatile loads and the load block has multiple
10750 // successors, sinking it would remove a load of the volatile value from
10751 // the path through the other successor.
10752 if (isVolatile &&
10753 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10754 return 0;
10755
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010756 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010757 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010758 } else {
10759 return 0; // Cannot fold this operation.
10760 }
10761
10762 // Check to see if all arguments are the same operation.
10763 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10764 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10765 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10766 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10767 return 0;
10768 if (CastSrcTy) {
10769 if (I->getOperand(0)->getType() != CastSrcTy)
10770 return 0; // Cast operation must match.
10771 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10772 // We can't sink the load if the loaded value could be modified between
10773 // the load and the PHI.
10774 if (LI->isVolatile() != isVolatile ||
10775 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010776 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010777 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010778
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010779 // If the PHI is of volatile loads and the load block has multiple
10780 // successors, sinking it would remove a load of the volatile value from
10781 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010782 if (isVolatile &&
10783 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10784 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010785
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010786 } else if (I->getOperand(1) != ConstantOp) {
10787 return 0;
10788 }
10789 }
10790
10791 // Okay, they are all the same operation. Create a new PHI node of the
10792 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010793 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10794 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010795 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10796
10797 Value *InVal = FirstInst->getOperand(0);
10798 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10799
10800 // Add all operands to the new PHI.
10801 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10802 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10803 if (NewInVal != InVal)
10804 InVal = 0;
10805 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10806 }
10807
10808 Value *PhiVal;
10809 if (InVal) {
10810 // The new PHI unions all of the same values together. This is really
10811 // common, so we handle it intelligently here for compile-time speed.
10812 PhiVal = InVal;
10813 delete NewPN;
10814 } else {
10815 InsertNewInstBefore(NewPN, PN);
10816 PhiVal = NewPN;
10817 }
10818
10819 // Insert and return the new operation.
10820 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010821 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010822 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010823 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010824 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson6601fcd2009-07-09 23:48:35 +000010825 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010826 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010827 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10828
10829 // If this was a volatile load that we are merging, make sure to loop through
10830 // and mark all the input loads as non-volatile. If we don't do this, we will
10831 // insert a new volatile load and the old ones will not be deletable.
10832 if (isVolatile)
10833 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10834 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10835
10836 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010837}
10838
10839/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10840/// that is dead.
10841static bool DeadPHICycle(PHINode *PN,
10842 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10843 if (PN->use_empty()) return true;
10844 if (!PN->hasOneUse()) return false;
10845
10846 // Remember this node, and if we find the cycle, return.
10847 if (!PotentiallyDeadPHIs.insert(PN))
10848 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010849
10850 // Don't scan crazily complex things.
10851 if (PotentiallyDeadPHIs.size() == 16)
10852 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010853
10854 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10855 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10856
10857 return false;
10858}
10859
Chris Lattner27b695d2007-11-06 21:52:06 +000010860/// PHIsEqualValue - Return true if this phi node is always equal to
10861/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10862/// z = some value; x = phi (y, z); y = phi (x, z)
10863static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10864 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10865 // See if we already saw this PHI node.
10866 if (!ValueEqualPHIs.insert(PN))
10867 return true;
10868
10869 // Don't scan crazily complex things.
10870 if (ValueEqualPHIs.size() == 16)
10871 return false;
10872
10873 // Scan the operands to see if they are either phi nodes or are equal to
10874 // the value.
10875 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10876 Value *Op = PN->getIncomingValue(i);
10877 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10878 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10879 return false;
10880 } else if (Op != NonPhiInVal)
10881 return false;
10882 }
10883
10884 return true;
10885}
10886
10887
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010888// PHINode simplification
10889//
10890Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10891 // If LCSSA is around, don't mess with Phi nodes
10892 if (MustPreserveLCSSA) return 0;
10893
10894 if (Value *V = PN.hasConstantValue())
10895 return ReplaceInstUsesWith(PN, V);
10896
10897 // If all PHI operands are the same operation, pull them through the PHI,
10898 // reducing code size.
10899 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010900 isa<Instruction>(PN.getIncomingValue(1)) &&
10901 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10902 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10903 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10904 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010905 PN.getIncomingValue(0)->hasOneUse())
10906 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10907 return Result;
10908
10909 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10910 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10911 // PHI)... break the cycle.
10912 if (PN.hasOneUse()) {
10913 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10914 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10915 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10916 PotentiallyDeadPHIs.insert(&PN);
10917 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010918 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010919 }
10920
10921 // If this phi has a single use, and if that use just computes a value for
10922 // the next iteration of a loop, delete the phi. This occurs with unused
10923 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10924 // common case here is good because the only other things that catch this
10925 // are induction variable analysis (sometimes) and ADCE, which is only run
10926 // late.
10927 if (PHIUser->hasOneUse() &&
10928 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10929 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010930 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010931 }
10932 }
10933
Chris Lattner27b695d2007-11-06 21:52:06 +000010934 // We sometimes end up with phi cycles that non-obviously end up being the
10935 // same value, for example:
10936 // z = some value; x = phi (y, z); y = phi (x, z)
10937 // where the phi nodes don't necessarily need to be in the same block. Do a
10938 // quick check to see if the PHI node only contains a single non-phi value, if
10939 // so, scan to see if the phi cycle is actually equal to that value.
10940 {
10941 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10942 // Scan for the first non-phi operand.
10943 while (InValNo != NumOperandVals &&
10944 isa<PHINode>(PN.getIncomingValue(InValNo)))
10945 ++InValNo;
10946
10947 if (InValNo != NumOperandVals) {
10948 Value *NonPhiInVal = PN.getOperand(InValNo);
10949
10950 // Scan the rest of the operands to see if there are any conflicts, if so
10951 // there is no need to recursively scan other phis.
10952 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10953 Value *OpVal = PN.getIncomingValue(InValNo);
10954 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10955 break;
10956 }
10957
10958 // If we scanned over all operands, then we have one unique value plus
10959 // phi values. Scan PHI nodes to see if they all merge in each other or
10960 // the value.
10961 if (InValNo == NumOperandVals) {
10962 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10963 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10964 return ReplaceInstUsesWith(PN, NonPhiInVal);
10965 }
10966 }
10967 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010968 return 0;
10969}
10970
10971static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10972 Instruction *InsertPoint,
10973 InstCombiner *IC) {
Dan Gohman8fd520a2009-06-15 22:12:54 +000010974 unsigned PtrSize = DTy->getScalarSizeInBits();
10975 unsigned VTySize = V->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010976 // We must cast correctly to the pointer type. Ensure that we
10977 // sign extend the integer value if it is smaller as this is
10978 // used for address computation.
10979 Instruction::CastOps opcode =
10980 (VTySize < PtrSize ? Instruction::SExt :
10981 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10982 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10983}
10984
10985
10986Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10987 Value *PtrOp = GEP.getOperand(0);
10988 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10989 // If so, eliminate the noop.
10990 if (GEP.getNumOperands() == 1)
10991 return ReplaceInstUsesWith(GEP, PtrOp);
10992
10993 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010994 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010995
10996 bool HasZeroPointerIndex = false;
10997 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10998 HasZeroPointerIndex = C->isNullValue();
10999
11000 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11001 return ReplaceInstUsesWith(GEP, PtrOp);
11002
11003 // Eliminate unneeded casts for indices.
11004 bool MadeChange = false;
11005
11006 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif17396002008-06-12 21:37:33 +000011007 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11008 i != e; ++i, ++GTI) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011009 if (TD && isa<SequentialType>(*GTI)) {
Gabor Greif17396002008-06-12 21:37:33 +000011010 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011011 if (CI->getOpcode() == Instruction::ZExt ||
11012 CI->getOpcode() == Instruction::SExt) {
11013 const Type *SrcTy = CI->getOperand(0)->getType();
11014 // We can eliminate a cast from i32 to i64 iff the target
11015 // is a 32-bit pointer target.
Dan Gohman8fd520a2009-06-15 22:12:54 +000011016 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011017 MadeChange = true;
Gabor Greif17396002008-06-12 21:37:33 +000011018 *i = CI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011019 }
11020 }
11021 }
11022 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman5d639ed2008-09-11 23:06:38 +000011023 // to what we need. If narrower, sign-extend it to what we need.
11024 // If the incoming value needs a cast instruction,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011025 // insert it. This explicit cast can make subsequent optimizations more
11026 // obvious.
Gabor Greif17396002008-06-12 21:37:33 +000011027 Value *Op = *i;
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011028 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011029 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Anderson02b48c32009-07-29 18:55:55 +000011030 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011031 MadeChange = true;
11032 } else {
11033 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11034 GEP);
Gabor Greif17396002008-06-12 21:37:33 +000011035 *i = Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011036 MadeChange = true;
11037 }
Eric Christopher3e7381f2009-07-25 02:45:27 +000011038 } else if (TD->getTypeSizeInBits(Op->getType())
11039 < TD->getPointerSizeInBits()) {
Dan Gohman5d639ed2008-09-11 23:06:38 +000011040 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Anderson02b48c32009-07-29 18:55:55 +000011041 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
Dan Gohman5d639ed2008-09-11 23:06:38 +000011042 MadeChange = true;
11043 } else {
11044 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11045 GEP);
11046 *i = Op;
11047 MadeChange = true;
11048 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011049 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011050 }
11051 }
11052 if (MadeChange) return &GEP;
11053
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011054 // Combine Indices - If the source pointer to this getelementptr instruction
11055 // is a getelementptr instruction, combine the indices of the two
11056 // getelementptr instructions into a single instruction.
11057 //
11058 SmallVector<Value*, 8> SrcGEPOperands;
Dan Gohman17f46f72009-07-28 01:40:03 +000011059 bool BothInBounds = cast<GEPOperator>(&GEP)->isInBounds();
11060 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011061 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Dan Gohman17f46f72009-07-28 01:40:03 +000011062 if (!Src->isInBounds())
11063 BothInBounds = false;
11064 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011065
11066 if (!SrcGEPOperands.empty()) {
11067 // Note that if our source is a gep chain itself that we wait for that
11068 // chain to be resolved before we perform this transformation. This
11069 // avoids us creating a TON of code in some cases.
11070 //
11071 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11072 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11073 return 0; // Wait until our source is folded to completion.
11074
11075 SmallVector<Value*, 8> Indices;
11076
11077 // Find out whether the last index in the source GEP is a sequential idx.
11078 bool EndsWithSequential = false;
11079 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11080 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11081 EndsWithSequential = !isa<StructType>(*I);
11082
11083 // Can we combine the two pointer arithmetics offsets?
11084 if (EndsWithSequential) {
11085 // Replace: gep (gep %P, long B), long A, ...
11086 // With: T = long A+B; gep %P, T, ...
11087 //
11088 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +000011089 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011090 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +000011091 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011092 Sum = SO1;
11093 } else {
11094 // If they aren't the same type, convert both to an integer of the
11095 // target's pointer size.
11096 if (SO1->getType() != GO1->getType()) {
11097 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011098 SO1 =
Owen Anderson02b48c32009-07-29 18:55:55 +000011099 ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011100 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011101 GO1 =
Owen Anderson02b48c32009-07-29 18:55:55 +000011102 ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Dan Gohmana80e2712009-07-21 23:21:54 +000011103 } else if (TD) {
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011104 unsigned PS = TD->getPointerSizeInBits();
11105 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011106 // Convert GO1 to SO1's type.
11107 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11108
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011109 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011110 // Convert SO1 to GO1's type.
11111 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11112 } else {
11113 const Type *PT = TD->getIntPtrType();
11114 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11115 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11116 }
11117 }
11118 }
11119 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Anderson02b48c32009-07-29 18:55:55 +000011120 Sum = ConstantExpr::getAdd(cast<Constant>(SO1),
Owen Anderson24be4c12009-07-03 00:17:18 +000011121 cast<Constant>(GO1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011122 else {
Gabor Greifa645dd32008-05-16 19:29:10 +000011123 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011124 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11125 }
11126 }
11127
11128 // Recycle the GEP we already have if possible.
11129 if (SrcGEPOperands.size() == 2) {
11130 GEP.setOperand(0, SrcGEPOperands[0]);
11131 GEP.setOperand(1, Sum);
11132 return &GEP;
11133 } else {
11134 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11135 SrcGEPOperands.end()-1);
11136 Indices.push_back(Sum);
11137 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11138 }
11139 } else if (isa<Constant>(*GEP.idx_begin()) &&
11140 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11141 SrcGEPOperands.size() != 1) {
11142 // Otherwise we can do the fold if the first index of the GEP is a zero
11143 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11144 SrcGEPOperands.end());
11145 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11146 }
11147
Dan Gohman17f46f72009-07-28 01:40:03 +000011148 if (!Indices.empty()) {
11149 GetElementPtrInst *NewGEP = GetElementPtrInst::Create(SrcGEPOperands[0],
11150 Indices.begin(),
11151 Indices.end(),
11152 GEP.getName());
11153 if (BothInBounds)
11154 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11155 return NewGEP;
11156 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011157
11158 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11159 // GEP of global variable. If all of the indices for this GEP are
11160 // constants, we can promote this to a constexpr instead of an instruction.
11161
11162 // Scan for nonconstants...
11163 SmallVector<Constant*, 8> Indices;
11164 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11165 for (; I != E && isa<Constant>(*I); ++I)
11166 Indices.push_back(cast<Constant>(*I));
11167
11168 if (I == E) { // If they are all constants...
Owen Anderson02b48c32009-07-29 18:55:55 +000011169 Constant *CE = ConstantExpr::getGetElementPtr(GV,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011170 &Indices[0],Indices.size());
11171
11172 // Replace all uses of the GEP with the new constexpr...
11173 return ReplaceInstUsesWith(GEP, CE);
11174 }
11175 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
11176 if (!isa<PointerType>(X->getType())) {
11177 // Not interesting. Source pointer must be a cast from pointer.
11178 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011179 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11180 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011181 //
Duncan Sandscf866e62009-03-02 09:18:21 +000011182 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11183 // into : GEP i8* X, ...
11184 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011185 // This occurs when the program declares an array extern like "int X[];"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011186 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11187 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011188 if (const ArrayType *CATy =
11189 dyn_cast<ArrayType>(CPTy->getElementType())) {
11190 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11191 if (CATy->getElementType() == XTy->getElementType()) {
11192 // -> GEP i8* X, ...
11193 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohman17f46f72009-07-28 01:40:03 +000011194 GetElementPtrInst *NewGEP =
11195 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11196 GEP.getName());
11197 if (cast<GEPOperator>(&GEP)->isInBounds())
11198 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11199 return NewGEP;
Duncan Sandscf866e62009-03-02 09:18:21 +000011200 } else if (const ArrayType *XATy =
11201 dyn_cast<ArrayType>(XTy->getElementType())) {
11202 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011203 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011204 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011205 // At this point, we know that the cast source type is a pointer
11206 // to an array of the same type as the destination pointer
11207 // array. Because the array type is never stepped over (there
11208 // is a leading zero) we can fold the cast into this GEP.
11209 GEP.setOperand(0, X);
11210 return &GEP;
11211 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011212 }
11213 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011214 } else if (GEP.getNumOperands() == 2) {
11215 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011216 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11217 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011218 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11219 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000011220 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011221 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11222 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011223 Value *Idx[2];
Owen Andersonaac28372009-07-31 20:28:14 +000011224 Idx[0] = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011225 Idx[1] = GEP.getOperand(1);
Dan Gohman17f46f72009-07-28 01:40:03 +000011226 GetElementPtrInst *NewGEP =
11227 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11228 if (cast<GEPOperator>(&GEP)->isInBounds())
11229 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11230 Value *V = InsertNewInstBefore(NewGEP, GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011231 // V and GEP are both pointer types --> BitCast
11232 return new BitCastInst(V, GEP.getType());
11233 }
11234
11235 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011236 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011237 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011238 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011239
Dan Gohmana80e2712009-07-21 23:21:54 +000011240 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011241 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011242 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011243
11244 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11245 // allow either a mul, shift, or constant here.
11246 Value *NewIdx = 0;
11247 ConstantInt *Scale = 0;
11248 if (ArrayEltSize == 1) {
11249 NewIdx = GEP.getOperand(1);
Owen Anderson24be4c12009-07-03 00:17:18 +000011250 Scale =
Owen Andersoneacb44d2009-07-24 23:12:02 +000011251 ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011252 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011253 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011254 Scale = CI;
11255 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11256 if (Inst->getOpcode() == Instruction::Shl &&
11257 isa<ConstantInt>(Inst->getOperand(1))) {
11258 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11259 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +000011260 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011261 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011262 NewIdx = Inst->getOperand(0);
11263 } else if (Inst->getOpcode() == Instruction::Mul &&
11264 isa<ConstantInt>(Inst->getOperand(1))) {
11265 Scale = cast<ConstantInt>(Inst->getOperand(1));
11266 NewIdx = Inst->getOperand(0);
11267 }
11268 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011269
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011270 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011271 // out, perform the transformation. Note, we don't know whether Scale is
11272 // signed or not. We'll use unsigned version of division/modulo
11273 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011274 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011275 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011276 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011277 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011278 if (Scale->getZExtValue() != 1) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011279 Constant *C =
Owen Anderson02b48c32009-07-29 18:55:55 +000011280 ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011281 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000011282 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011283 NewIdx = InsertNewInstBefore(Sc, GEP);
11284 }
11285
11286 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011287 Value *Idx[2];
Owen Andersonaac28372009-07-31 20:28:14 +000011288 Idx[0] = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011289 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011290 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000011291 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohman17f46f72009-07-28 01:40:03 +000011292 if (cast<GEPOperator>(&GEP)->isInBounds())
11293 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011294 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11295 // The NewGEP must be pointer typed, so must the old one -> BitCast
11296 return new BitCastInst(NewGEP, GEP.getType());
11297 }
11298 }
11299 }
11300 }
Chris Lattner111ea772009-01-09 04:53:57 +000011301
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011302 /// See if we can simplify:
11303 /// X = bitcast A to B*
11304 /// Y = gep X, <...constant indices...>
11305 /// into a gep of the original struct. This is important for SROA and alias
11306 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011307 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011308 if (TD &&
11309 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011310 // Determine how much the GEP moves the pointer. We are guaranteed to get
11311 // a constant back from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +000011312 ConstantInt *OffsetV =
11313 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011314 int64_t Offset = OffsetV->getSExtValue();
11315
11316 // If this GEP instruction doesn't move the pointer, just replace the GEP
11317 // with a bitcast of the real input to the dest type.
11318 if (Offset == 0) {
11319 // If the bitcast is of an allocation, and the allocation will be
11320 // converted to match the type of the cast, don't touch this.
11321 if (isa<AllocationInst>(BCI->getOperand(0))) {
11322 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11323 if (Instruction *I = visitBitCast(*BCI)) {
11324 if (I != BCI) {
11325 I->takeName(BCI);
11326 BCI->getParent()->getInstList().insert(BCI, I);
11327 ReplaceInstUsesWith(*BCI, I);
11328 }
11329 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011330 }
Chris Lattner111ea772009-01-09 04:53:57 +000011331 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011332 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011333 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011334
11335 // Otherwise, if the offset is non-zero, we need to find out if there is a
11336 // field at Offset in 'A's type. If so, we can pull the cast through the
11337 // GEP.
11338 SmallVector<Value*, 8> NewIndices;
11339 const Type *InTy =
11340 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000011341 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011342 Instruction *NGEP =
11343 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11344 NewIndices.end());
11345 if (NGEP->getType() == GEP.getType()) return NGEP;
Dan Gohman17f46f72009-07-28 01:40:03 +000011346 if (cast<GEPOperator>(&GEP)->isInBounds())
11347 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011348 InsertNewInstBefore(NGEP, GEP);
11349 NGEP->takeName(&GEP);
11350 return new BitCastInst(NGEP, GEP.getType());
11351 }
Chris Lattner111ea772009-01-09 04:53:57 +000011352 }
11353 }
11354
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011355 return 0;
11356}
11357
11358Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11359 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011360 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011361 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11362 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011363 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011364 AllocationInst *New = 0;
11365
11366 // Create and insert the replacement instruction...
11367 if (isa<MallocInst>(AI))
Owen Anderson140166d2009-07-15 23:53:25 +000011368 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011369 else {
11370 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson140166d2009-07-15 23:53:25 +000011371 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011372 }
11373
11374 InsertNewInstBefore(New, AI);
11375
11376 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011377 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011378 //
11379 BasicBlock::iterator It = New;
Dale Johannesena499d0d2009-03-11 22:19:43 +000011380 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011381
11382 // Now that I is pointing to the first non-allocation-inst in the block,
11383 // insert our getelementptr instruction...
11384 //
Owen Andersonaac28372009-07-31 20:28:14 +000011385 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011386 Value *Idx[2];
11387 Idx[0] = NullIdx;
11388 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000011389 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11390 New->getName()+".sub", It);
Dan Gohman17f46f72009-07-28 01:40:03 +000011391 cast<GEPOperator>(V)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011392
11393 // Now make everything use the getelementptr instead of the original
11394 // allocation.
11395 return ReplaceInstUsesWith(AI, V);
11396 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +000011397 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011398 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011399 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011400
Dan Gohmana80e2712009-07-21 23:21:54 +000011401 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000011402 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011403 // Note that we only do this for alloca's, because malloc should allocate
11404 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011405 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +000011406 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000011407
11408 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11409 if (AI.getAlignment() == 0)
11410 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11411 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011412
11413 return 0;
11414}
11415
11416Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11417 Value *Op = FI.getOperand(0);
11418
11419 // free undef -> unreachable.
11420 if (isa<UndefValue>(Op)) {
11421 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000011422 new StoreInst(ConstantInt::getTrue(*Context),
Owen Andersonb99ecca2009-07-30 23:03:37 +000011423 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011424 return EraseInstFromFunction(FI);
11425 }
11426
11427 // If we have 'free null' delete the instruction. This can happen in stl code
11428 // when lots of inlining happens.
11429 if (isa<ConstantPointerNull>(Op))
11430 return EraseInstFromFunction(FI);
11431
11432 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11433 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11434 FI.setOperand(0, CI->getOperand(0));
11435 return &FI;
11436 }
11437
11438 // Change free (gep X, 0,0,0,0) into free(X)
11439 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11440 if (GEPI->hasAllZeroIndices()) {
11441 AddToWorkList(GEPI);
11442 FI.setOperand(0, GEPI->getOperand(0));
11443 return &FI;
11444 }
11445 }
11446
11447 // Change free(malloc) into nothing, if the malloc has a single use.
11448 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11449 if (MI->hasOneUse()) {
11450 EraseInstFromFunction(FI);
11451 return EraseInstFromFunction(*MI);
11452 }
11453
11454 return 0;
11455}
11456
11457
11458/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011459static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011460 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011461 User *CI = cast<User>(LI.getOperand(0));
11462 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011463 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011464
Nick Lewycky291c5942009-05-08 06:47:37 +000011465 if (TD) {
11466 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11467 // Instead of loading constant c string, use corresponding integer value
11468 // directly if string length is small enough.
11469 std::string Str;
11470 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11471 unsigned len = Str.length();
11472 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11473 unsigned numBits = Ty->getPrimitiveSizeInBits();
11474 // Replace LI with immediate integer store.
11475 if ((numBits >> 3) == len + 1) {
11476 APInt StrVal(numBits, 0);
11477 APInt SingleChar(numBits, 0);
11478 if (TD->isLittleEndian()) {
11479 for (signed i = len-1; i >= 0; i--) {
11480 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11481 StrVal = (StrVal << 8) | SingleChar;
11482 }
11483 } else {
11484 for (unsigned i = 0; i < len; i++) {
11485 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11486 StrVal = (StrVal << 8) | SingleChar;
11487 }
11488 // Append NULL at the end.
11489 SingleChar = 0;
Bill Wendling44a36ea2008-02-26 10:53:30 +000011490 StrVal = (StrVal << 8) | SingleChar;
11491 }
Owen Andersoneacb44d2009-07-24 23:12:02 +000011492 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky291c5942009-05-08 06:47:37 +000011493 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling44a36ea2008-02-26 10:53:30 +000011494 }
Devang Patela0f8ea82007-10-18 19:52:32 +000011495 }
11496 }
11497 }
11498
Mon P Wangbd05ed82009-02-07 22:19:29 +000011499 const PointerType *DestTy = cast<PointerType>(CI->getType());
11500 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011501 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011502
11503 // If the address spaces don't match, don't eliminate the cast.
11504 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11505 return 0;
11506
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011507 const Type *SrcPTy = SrcTy->getElementType();
11508
11509 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11510 isa<VectorType>(DestPTy)) {
11511 // If the source is an array, the code below will not succeed. Check to
11512 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11513 // constants.
11514 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11515 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11516 if (ASrcTy->getNumElements() != 0) {
11517 Value *Idxs[2];
Owen Andersonaac28372009-07-31 20:28:14 +000011518 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
Owen Anderson02b48c32009-07-29 18:55:55 +000011519 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011520 SrcTy = cast<PointerType>(CastOp->getType());
11521 SrcPTy = SrcTy->getElementType();
11522 }
11523
Dan Gohmana80e2712009-07-21 23:21:54 +000011524 if (IC.getTargetData() &&
11525 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011526 isa<VectorType>(SrcPTy)) &&
11527 // Do not allow turning this into a load of an integer, which is then
11528 // casted to a pointer, this pessimizes pointer analysis a lot.
11529 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000011530 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11531 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011532
11533 // Okay, we are casting from one integer or pointer type to another of
11534 // the same size. Instead of casting the pointer before the load, cast
11535 // the result of the loaded value.
11536 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11537 CI->getName(),
11538 LI.isVolatile()),LI);
11539 // Now cast the result of the load.
11540 return new BitCastInst(NewLoad, LI.getType());
11541 }
11542 }
11543 }
11544 return 0;
11545}
11546
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011547Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11548 Value *Op = LI.getOperand(0);
11549
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011550 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011551 if (TD) {
11552 unsigned KnownAlign =
11553 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11554 if (KnownAlign >
11555 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11556 LI.getAlignment()))
11557 LI.setAlignment(KnownAlign);
11558 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011559
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011560 // load (cast X) --> cast (load X) iff safe
11561 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011562 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011563 return Res;
11564
11565 // None of the following transforms are legal for volatile loads.
11566 if (LI.isVolatile()) return 0;
11567
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011568 // Do really simple store-to-load forwarding and load CSE, to catch cases
11569 // where there are several consequtive memory accesses to the same location,
11570 // separated by a few arithmetic operations.
11571 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011572 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11573 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011574
Christopher Lamb2c175392007-12-29 07:56:53 +000011575 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11576 const Value *GEPI0 = GEPI->getOperand(0);
11577 // TODO: Consider a target hook for valid address spaces for this xform.
11578 if (isa<ConstantPointerNull>(GEPI0) &&
11579 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011580 // Insert a new store to null instruction before the load to indicate
11581 // that this code is not reachable. We do this instead of inserting
11582 // an unreachable instruction directly because we cannot modify the
11583 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011584 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011585 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011586 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011587 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011588 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011589
11590 if (Constant *C = dyn_cast<Constant>(Op)) {
11591 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000011592 // TODO: Consider a target hook for valid address spaces for this xform.
11593 if (isa<UndefValue>(C) || (C->isNullValue() &&
11594 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011595 // Insert a new store to null instruction before the load to indicate that
11596 // this code is not reachable. We do this instead of inserting an
11597 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011598 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011599 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011600 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011601 }
11602
11603 // Instcombine load (constant global) into the value loaded.
11604 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands54e70f62009-03-21 21:27:31 +000011605 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011606 return ReplaceInstUsesWith(LI, GV->getInitializer());
11607
11608 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011609 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011610 if (CE->getOpcode() == Instruction::GetElementPtr) {
11611 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +000011612 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011613 if (Constant *V =
Owen Andersond4d90a02009-07-06 18:42:36 +000011614 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Anderson175b6542009-07-22 00:24:57 +000011615 *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011616 return ReplaceInstUsesWith(LI, V);
11617 if (CE->getOperand(0)->isNullValue()) {
11618 // Insert a new store to null instruction before the load to indicate
11619 // that this code is not reachable. We do this instead of inserting
11620 // an unreachable instruction directly because we cannot modify the
11621 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011622 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011623 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011624 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011625 }
11626
11627 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000011628 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011629 return Res;
11630 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011631 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011632 }
Chris Lattner0270a112007-08-11 18:48:48 +000011633
11634 // If this load comes from anywhere in a constant global, and if the global
11635 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000011636 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands54e70f62009-03-21 21:27:31 +000011637 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner0270a112007-08-11 18:48:48 +000011638 if (GV->getInitializer()->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +000011639 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011640 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011641 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011642 }
11643 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011644
11645 if (Op->hasOneUse()) {
11646 // Change select and PHI nodes to select values instead of addresses: this
11647 // helps alias analysis out a lot, allows many others simplifications, and
11648 // exposes redundancy in the code.
11649 //
11650 // Note that we cannot do the transformation unless we know that the
11651 // introduced loads cannot trap! Something like this is valid as long as
11652 // the condition is always false: load (select bool %C, int* null, int* %G),
11653 // but it would not be valid if we transformed it to load from null
11654 // unconditionally.
11655 //
11656 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11657 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11658 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11659 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11660 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11661 SI->getOperand(1)->getName()+".val"), LI);
11662 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11663 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000011664 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011665 }
11666
11667 // load (select (cond, null, P)) -> load P
11668 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11669 if (C->isNullValue()) {
11670 LI.setOperand(0, SI->getOperand(2));
11671 return &LI;
11672 }
11673
11674 // load (select (cond, P, null)) -> load P
11675 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11676 if (C->isNullValue()) {
11677 LI.setOperand(0, SI->getOperand(1));
11678 return &LI;
11679 }
11680 }
11681 }
11682 return 0;
11683}
11684
11685/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011686/// when possible. This makes it generally easy to do alias analysis and/or
11687/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011688static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11689 User *CI = cast<User>(SI.getOperand(1));
11690 Value *CastOp = CI->getOperand(0);
11691
11692 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011693 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11694 if (SrcTy == 0) return 0;
11695
11696 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011697
Chris Lattnera032c0e2009-01-16 20:08:59 +000011698 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11699 return 0;
11700
Chris Lattner54dddc72009-01-24 01:00:13 +000011701 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11702 /// to its first element. This allows us to handle things like:
11703 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11704 /// on 32-bit hosts.
11705 SmallVector<Value*, 4> NewGEPIndices;
11706
Chris Lattnera032c0e2009-01-16 20:08:59 +000011707 // If the source is an array, the code below will not succeed. Check to
11708 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11709 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011710 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11711 // Index through pointer.
Owen Andersonaac28372009-07-31 20:28:14 +000011712 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
Chris Lattner54dddc72009-01-24 01:00:13 +000011713 NewGEPIndices.push_back(Zero);
11714
11715 while (1) {
11716 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011717 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011718 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011719 NewGEPIndices.push_back(Zero);
11720 SrcPTy = STy->getElementType(0);
11721 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11722 NewGEPIndices.push_back(Zero);
11723 SrcPTy = ATy->getElementType();
11724 } else {
11725 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011726 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011727 }
11728
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011729 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000011730 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011731
11732 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11733 return 0;
11734
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011735 // If the pointers point into different address spaces or if they point to
11736 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000011737 if (!IC.getTargetData() ||
11738 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011739 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000011740 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11741 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000011742 return 0;
11743
11744 // Okay, we are casting from one integer or pointer type to another of
11745 // the same size. Instead of casting the pointer before
11746 // the store, cast the value to be stored.
11747 Value *NewCast;
11748 Value *SIOp0 = SI.getOperand(0);
11749 Instruction::CastOps opcode = Instruction::BitCast;
11750 const Type* CastSrcTy = SIOp0->getType();
11751 const Type* CastDstTy = SrcPTy;
11752 if (isa<PointerType>(CastDstTy)) {
11753 if (CastSrcTy->isInteger())
11754 opcode = Instruction::IntToPtr;
11755 } else if (isa<IntegerType>(CastDstTy)) {
11756 if (isa<PointerType>(SIOp0->getType()))
11757 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011758 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011759
11760 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11761 // emit a GEP to index into its first field.
11762 if (!NewGEPIndices.empty()) {
11763 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Anderson02b48c32009-07-29 18:55:55 +000011764 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner54dddc72009-01-24 01:00:13 +000011765 NewGEPIndices.size());
11766 else
11767 CastOp = IC.InsertNewInstBefore(
11768 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11769 NewGEPIndices.end()), SI);
Dan Gohman17f46f72009-07-28 01:40:03 +000011770 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner54dddc72009-01-24 01:00:13 +000011771 }
11772
Chris Lattnera032c0e2009-01-16 20:08:59 +000011773 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Anderson02b48c32009-07-29 18:55:55 +000011774 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnera032c0e2009-01-16 20:08:59 +000011775 else
11776 NewCast = IC.InsertNewInstBefore(
11777 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11778 SI);
11779 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011780}
11781
Chris Lattner6fd8c802008-11-27 08:56:30 +000011782/// equivalentAddressValues - Test if A and B will obviously have the same
11783/// value. This includes recognizing that %t0 and %t1 will have the same
11784/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000011785/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011786/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000011787/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011788/// %t2 = load i32* %t1
11789///
11790static bool equivalentAddressValues(Value *A, Value *B) {
11791 // Test if the values are trivially equivalent.
11792 if (A == B) return true;
11793
11794 // Test if the values come form identical arithmetic instructions.
11795 if (isa<BinaryOperator>(A) ||
11796 isa<CastInst>(A) ||
11797 isa<PHINode>(A) ||
11798 isa<GetElementPtrInst>(A))
11799 if (Instruction *BI = dyn_cast<Instruction>(B))
11800 if (cast<Instruction>(A)->isIdenticalTo(BI))
11801 return true;
11802
11803 // Otherwise they may not be equivalent.
11804 return false;
11805}
11806
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011807// If this instruction has two uses, one of which is a llvm.dbg.declare,
11808// return the llvm.dbg.declare.
11809DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11810 if (!V->hasNUses(2))
11811 return 0;
11812 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11813 UI != E; ++UI) {
11814 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11815 return DI;
11816 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11817 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11818 return DI;
11819 }
11820 }
11821 return 0;
11822}
11823
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011824Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11825 Value *Val = SI.getOperand(0);
11826 Value *Ptr = SI.getOperand(1);
11827
11828 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11829 EraseInstFromFunction(SI);
11830 ++NumCombined;
11831 return 0;
11832 }
11833
11834 // If the RHS is an alloca with a single use, zapify the store, making the
11835 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011836 // If the RHS is an alloca with a two uses, the other one being a
11837 // llvm.dbg.declare, zapify the store and the declare, making the
11838 // alloca dead. We must do this to prevent declare's from affecting
11839 // codegen.
11840 if (!SI.isVolatile()) {
11841 if (Ptr->hasOneUse()) {
11842 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011843 EraseInstFromFunction(SI);
11844 ++NumCombined;
11845 return 0;
11846 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011847 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11848 if (isa<AllocaInst>(GEP->getOperand(0))) {
11849 if (GEP->getOperand(0)->hasOneUse()) {
11850 EraseInstFromFunction(SI);
11851 ++NumCombined;
11852 return 0;
11853 }
11854 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11855 EraseInstFromFunction(*DI);
11856 EraseInstFromFunction(SI);
11857 ++NumCombined;
11858 return 0;
11859 }
11860 }
11861 }
11862 }
11863 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11864 EraseInstFromFunction(*DI);
11865 EraseInstFromFunction(SI);
11866 ++NumCombined;
11867 return 0;
11868 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011869 }
11870
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011871 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011872 if (TD) {
11873 unsigned KnownAlign =
11874 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11875 if (KnownAlign >
11876 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11877 SI.getAlignment()))
11878 SI.setAlignment(KnownAlign);
11879 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011880
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011881 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011882 // stores to the same location, separated by a few arithmetic operations. This
11883 // situation often occurs with bitfield accesses.
11884 BasicBlock::iterator BBI = &SI;
11885 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11886 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000011887 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000011888 // Don't count debug info directives, lest they affect codegen,
11889 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11890 // It is necessary for correctness to skip those that feed into a
11891 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000011892 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000011893 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011894 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011895 continue;
11896 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011897
11898 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11899 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011900 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11901 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011902 ++NumDeadStore;
11903 ++BBI;
11904 EraseInstFromFunction(*PrevSI);
11905 continue;
11906 }
11907 break;
11908 }
11909
11910 // If this is a load, we have to stop. However, if the loaded value is from
11911 // the pointer we're loading and is producing the pointer we're storing,
11912 // then *this* store is dead (X = load P; store X -> P).
11913 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011914 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11915 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011916 EraseInstFromFunction(SI);
11917 ++NumCombined;
11918 return 0;
11919 }
11920 // Otherwise, this is a load from some other location. Stores before it
11921 // may not be dead.
11922 break;
11923 }
11924
11925 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011926 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011927 break;
11928 }
11929
11930
11931 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11932
11933 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner96e0a652009-06-11 17:54:56 +000011934 if (isa<ConstantPointerNull>(Ptr) &&
11935 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011936 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000011937 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011938 if (Instruction *U = dyn_cast<Instruction>(Val))
11939 AddToWorkList(U); // Dropped a use.
11940 ++NumCombined;
11941 }
11942 return 0; // Do not modify these!
11943 }
11944
11945 // store undef, Ptr -> noop
11946 if (isa<UndefValue>(Val)) {
11947 EraseInstFromFunction(SI);
11948 ++NumCombined;
11949 return 0;
11950 }
11951
11952 // If the pointer destination is a cast, see if we can fold the cast into the
11953 // source instead.
11954 if (isa<CastInst>(Ptr))
11955 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11956 return Res;
11957 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11958 if (CE->isCast())
11959 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11960 return Res;
11961
11962
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011963 // If this store is the last instruction in the basic block (possibly
11964 // excepting debug info instructions and the pointer bitcasts that feed
11965 // into them), and if the block ends with an unconditional branch, try
11966 // to move it to the successor block.
11967 BBI = &SI;
11968 do {
11969 ++BBI;
11970 } while (isa<DbgInfoIntrinsic>(BBI) ||
11971 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011972 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11973 if (BI->isUnconditional())
11974 if (SimplifyStoreAtEndOfBlock(SI))
11975 return 0; // xform done!
11976
11977 return 0;
11978}
11979
11980/// SimplifyStoreAtEndOfBlock - Turn things like:
11981/// if () { *P = v1; } else { *P = v2 }
11982/// into a phi node with a store in the successor.
11983///
11984/// Simplify things like:
11985/// *P = v1; if () { *P = v2; }
11986/// into a phi node with a store in the successor.
11987///
11988bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11989 BasicBlock *StoreBB = SI.getParent();
11990
11991 // Check to see if the successor block has exactly two incoming edges. If
11992 // so, see if the other predecessor contains a store to the same location.
11993 // if so, insert a PHI node (if needed) and move the stores down.
11994 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11995
11996 // Determine whether Dest has exactly two predecessors and, if so, compute
11997 // the other predecessor.
11998 pred_iterator PI = pred_begin(DestBB);
11999 BasicBlock *OtherBB = 0;
12000 if (*PI != StoreBB)
12001 OtherBB = *PI;
12002 ++PI;
12003 if (PI == pred_end(DestBB))
12004 return false;
12005
12006 if (*PI != StoreBB) {
12007 if (OtherBB)
12008 return false;
12009 OtherBB = *PI;
12010 }
12011 if (++PI != pred_end(DestBB))
12012 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000012013
12014 // Bail out if all the relevant blocks aren't distinct (this can happen,
12015 // for example, if SI is in an infinite loop)
12016 if (StoreBB == DestBB || OtherBB == DestBB)
12017 return false;
12018
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012019 // Verify that the other block ends in a branch and is not otherwise empty.
12020 BasicBlock::iterator BBI = OtherBB->getTerminator();
12021 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12022 if (!OtherBr || BBI == OtherBB->begin())
12023 return false;
12024
12025 // If the other block ends in an unconditional branch, check for the 'if then
12026 // else' case. there is an instruction before the branch.
12027 StoreInst *OtherStore = 0;
12028 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012029 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012030 // Skip over debugging info.
12031 while (isa<DbgInfoIntrinsic>(BBI) ||
12032 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12033 if (BBI==OtherBB->begin())
12034 return false;
12035 --BBI;
12036 }
12037 // If this isn't a store, or isn't a store to the same location, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012038 OtherStore = dyn_cast<StoreInst>(BBI);
12039 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12040 return false;
12041 } else {
12042 // Otherwise, the other block ended with a conditional branch. If one of the
12043 // destinations is StoreBB, then we have the if/then case.
12044 if (OtherBr->getSuccessor(0) != StoreBB &&
12045 OtherBr->getSuccessor(1) != StoreBB)
12046 return false;
12047
12048 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12049 // if/then triangle. See if there is a store to the same ptr as SI that
12050 // lives in OtherBB.
12051 for (;; --BBI) {
12052 // Check to see if we find the matching store.
12053 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12054 if (OtherStore->getOperand(1) != SI.getOperand(1))
12055 return false;
12056 break;
12057 }
Eli Friedman3a311d52008-06-13 22:02:12 +000012058 // If we find something that may be using or overwriting the stored
12059 // value, or if we run out of instructions, we can't do the xform.
12060 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012061 BBI == OtherBB->begin())
12062 return false;
12063 }
12064
12065 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000012066 // make sure nothing reads or overwrites the stored value in
12067 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012068 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12069 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000012070 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012071 return false;
12072 }
12073 }
12074
12075 // Insert a PHI node now if we need it.
12076 Value *MergedVal = OtherStore->getOperand(0);
12077 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000012078 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012079 PN->reserveOperandSpace(2);
12080 PN->addIncoming(SI.getOperand(0), SI.getParent());
12081 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12082 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12083 }
12084
12085 // Advance to a place where it is safe to insert the new store and
12086 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000012087 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012088 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12089 OtherStore->isVolatile()), *BBI);
12090
12091 // Nuke the old stores.
12092 EraseInstFromFunction(SI);
12093 EraseInstFromFunction(*OtherStore);
12094 ++NumCombined;
12095 return true;
12096}
12097
12098
12099Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12100 // Change br (not X), label True, label False to: br X, label False, True
12101 Value *X = 0;
12102 BasicBlock *TrueDest;
12103 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +000012104 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012105 !isa<Constant>(X)) {
12106 // Swap Destinations and condition...
12107 BI.setCondition(X);
12108 BI.setSuccessor(0, FalseDest);
12109 BI.setSuccessor(1, TrueDest);
12110 return &BI;
12111 }
12112
12113 // Cannonicalize fcmp_one -> fcmp_oeq
12114 FCmpInst::Predicate FPred; Value *Y;
12115 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Dan Gohmancdff2122009-08-12 16:23:25 +000012116 TrueDest, FalseDest)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012117 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12118 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12119 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12120 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson6601fcd2009-07-09 23:48:35 +000012121 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012122 NewSCC->takeName(I);
12123 // Swap Destinations and condition...
12124 BI.setCondition(NewSCC);
12125 BI.setSuccessor(0, FalseDest);
12126 BI.setSuccessor(1, TrueDest);
12127 RemoveFromWorkList(I);
12128 I->eraseFromParent();
12129 AddToWorkList(NewSCC);
12130 return &BI;
12131 }
12132
12133 // Cannonicalize icmp_ne -> icmp_eq
12134 ICmpInst::Predicate IPred;
12135 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Dan Gohmancdff2122009-08-12 16:23:25 +000012136 TrueDest, FalseDest)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012137 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12138 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12139 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12140 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12141 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson6601fcd2009-07-09 23:48:35 +000012142 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012143 NewSCC->takeName(I);
12144 // Swap Destinations and condition...
12145 BI.setCondition(NewSCC);
12146 BI.setSuccessor(0, FalseDest);
12147 BI.setSuccessor(1, TrueDest);
12148 RemoveFromWorkList(I);
12149 I->eraseFromParent();;
12150 AddToWorkList(NewSCC);
12151 return &BI;
12152 }
12153
12154 return 0;
12155}
12156
12157Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12158 Value *Cond = SI.getCondition();
12159 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12160 if (I->getOpcode() == Instruction::Add)
12161 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12162 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12163 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012164 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +000012165 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012166 AddRHS));
12167 SI.setOperand(0, I->getOperand(0));
12168 AddToWorkList(I);
12169 return &SI;
12170 }
12171 }
12172 return 0;
12173}
12174
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012175Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012176 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012177
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012178 if (!EV.hasIndices())
12179 return ReplaceInstUsesWith(EV, Agg);
12180
12181 if (Constant *C = dyn_cast<Constant>(Agg)) {
12182 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012183 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012184
12185 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +000012186 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012187
12188 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12189 // Extract the element indexed by the first index out of the constant
12190 Value *V = C->getOperand(*EV.idx_begin());
12191 if (EV.getNumIndices() > 1)
12192 // Extract the remaining indices out of the constant indexed by the
12193 // first index
12194 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12195 else
12196 return ReplaceInstUsesWith(EV, V);
12197 }
12198 return 0; // Can't handle other constants
12199 }
12200 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12201 // We're extracting from an insertvalue instruction, compare the indices
12202 const unsigned *exti, *exte, *insi, *inse;
12203 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12204 exte = EV.idx_end(), inse = IV->idx_end();
12205 exti != exte && insi != inse;
12206 ++exti, ++insi) {
12207 if (*insi != *exti)
12208 // The insert and extract both reference distinctly different elements.
12209 // This means the extract is not influenced by the insert, and we can
12210 // replace the aggregate operand of the extract with the aggregate
12211 // operand of the insert. i.e., replace
12212 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12213 // %E = extractvalue { i32, { i32 } } %I, 0
12214 // with
12215 // %E = extractvalue { i32, { i32 } } %A, 0
12216 return ExtractValueInst::Create(IV->getAggregateOperand(),
12217 EV.idx_begin(), EV.idx_end());
12218 }
12219 if (exti == exte && insi == inse)
12220 // Both iterators are at the end: Index lists are identical. Replace
12221 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12222 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12223 // with "i32 42"
12224 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12225 if (exti == exte) {
12226 // The extract list is a prefix of the insert list. i.e. replace
12227 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12228 // %E = extractvalue { i32, { i32 } } %I, 1
12229 // with
12230 // %X = extractvalue { i32, { i32 } } %A, 1
12231 // %E = insertvalue { i32 } %X, i32 42, 0
12232 // by switching the order of the insert and extract (though the
12233 // insertvalue should be left in, since it may have other uses).
12234 Value *NewEV = InsertNewInstBefore(
12235 ExtractValueInst::Create(IV->getAggregateOperand(),
12236 EV.idx_begin(), EV.idx_end()),
12237 EV);
12238 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12239 insi, inse);
12240 }
12241 if (insi == inse)
12242 // The insert list is a prefix of the extract list
12243 // We can simply remove the common indices from the extract and make it
12244 // operate on the inserted value instead of the insertvalue result.
12245 // i.e., replace
12246 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12247 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12248 // with
12249 // %E extractvalue { i32 } { i32 42 }, 0
12250 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12251 exti, exte);
12252 }
12253 // Can't simplify extracts from other values. Note that nested extracts are
12254 // already simplified implicitely by the above (extract ( extract (insert) )
12255 // will be translated into extract ( insert ( extract ) ) first and then just
12256 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012257 return 0;
12258}
12259
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012260/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12261/// is to leave as a vector operation.
12262static bool CheapToScalarize(Value *V, bool isConstant) {
12263 if (isa<ConstantAggregateZero>(V))
12264 return true;
12265 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12266 if (isConstant) return true;
12267 // If all elts are the same, we can extract.
12268 Constant *Op0 = C->getOperand(0);
12269 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12270 if (C->getOperand(i) != Op0)
12271 return false;
12272 return true;
12273 }
12274 Instruction *I = dyn_cast<Instruction>(V);
12275 if (!I) return false;
12276
12277 // Insert element gets simplified to the inserted element or is deleted if
12278 // this is constant idx extract element and its a constant idx insertelt.
12279 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12280 isa<ConstantInt>(I->getOperand(2)))
12281 return true;
12282 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12283 return true;
12284 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12285 if (BO->hasOneUse() &&
12286 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12287 CheapToScalarize(BO->getOperand(1), isConstant)))
12288 return true;
12289 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12290 if (CI->hasOneUse() &&
12291 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12292 CheapToScalarize(CI->getOperand(1), isConstant)))
12293 return true;
12294
12295 return false;
12296}
12297
12298/// Read and decode a shufflevector mask.
12299///
12300/// It turns undef elements into values that are larger than the number of
12301/// elements in the input.
12302static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12303 unsigned NElts = SVI->getType()->getNumElements();
12304 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12305 return std::vector<unsigned>(NElts, 0);
12306 if (isa<UndefValue>(SVI->getOperand(2)))
12307 return std::vector<unsigned>(NElts, 2*NElts);
12308
12309 std::vector<unsigned> Result;
12310 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012311 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12312 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012313 Result.push_back(NElts*2); // undef -> 8
12314 else
Gabor Greif17396002008-06-12 21:37:33 +000012315 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012316 return Result;
12317}
12318
12319/// FindScalarElement - Given a vector and an element number, see if the scalar
12320/// value is already around as a register, for example if it were inserted then
12321/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012322static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012323 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012324 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12325 const VectorType *PTy = cast<VectorType>(V->getType());
12326 unsigned Width = PTy->getNumElements();
12327 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012328 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012329
12330 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012331 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012332 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +000012333 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012334 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12335 return CP->getOperand(EltNo);
12336 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12337 // If this is an insert to a variable element, we don't know what it is.
12338 if (!isa<ConstantInt>(III->getOperand(2)))
12339 return 0;
12340 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12341
12342 // If this is an insert to the element we are looking for, return the
12343 // inserted value.
12344 if (EltNo == IIElt)
12345 return III->getOperand(1);
12346
12347 // Otherwise, the insertelement doesn't modify the value, recurse on its
12348 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000012349 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012350 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012351 unsigned LHSWidth =
12352 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012353 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012354 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012355 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012356 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012357 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012358 else
Owen Andersonb99ecca2009-07-30 23:03:37 +000012359 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012360 }
12361
12362 // Otherwise, we don't know.
12363 return 0;
12364}
12365
12366Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012367 // If vector val is undef, replace extract with scalar undef.
12368 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012369 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012370
12371 // If vector val is constant 0, replace extract with scalar 0.
12372 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +000012373 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012374
12375 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012376 // If vector val is constant with all elements the same, replace EI with
12377 // that element. When the elements are not identical, we cannot replace yet
12378 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012379 Constant *op0 = C->getOperand(0);
12380 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12381 if (C->getOperand(i) != op0) {
12382 op0 = 0;
12383 break;
12384 }
12385 if (op0)
12386 return ReplaceInstUsesWith(EI, op0);
12387 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000012388
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012389 // If extracting a specified index from the vector, see if we can recursively
12390 // find a previously computed scalar that was inserted into the vector.
12391 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12392 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedmanf34209b2009-07-18 19:04:16 +000012393 unsigned VectorWidth =
12394 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012395
12396 // If this is extracting an invalid index, turn this into undef, to avoid
12397 // crashing the code below.
12398 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +000012399 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012400
12401 // This instruction only demands the single element from the input vector.
12402 // If the input vector has a single use, simplify it based on this use
12403 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000012404 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012405 APInt UndefElts(VectorWidth, 0);
12406 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012407 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012408 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012409 EI.setOperand(0, V);
12410 return &EI;
12411 }
12412 }
12413
Owen Anderson24be4c12009-07-03 00:17:18 +000012414 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012415 return ReplaceInstUsesWith(EI, Elt);
12416
12417 // If the this extractelement is directly using a bitcast from a vector of
12418 // the same number of elements, see if we can find the source element from
12419 // it. In this case, we will end up needing to bitcast the scalars.
12420 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12421 if (const VectorType *VT =
12422 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12423 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012424 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12425 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012426 return new BitCastInst(Elt, EI.getType());
12427 }
12428 }
12429
12430 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12431 if (I->hasOneUse()) {
12432 // Push extractelement into predecessor operation if legal and
12433 // profitable to do so
12434 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12435 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12436 if (CheapToScalarize(BO, isConstantElt)) {
12437 ExtractElementInst *newEI0 =
Eric Christopher1ba36872009-07-25 02:28:41 +000012438 ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012439 EI.getName()+".lhs");
12440 ExtractElementInst *newEI1 =
Eric Christopher1ba36872009-07-25 02:28:41 +000012441 ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012442 EI.getName()+".rhs");
12443 InsertNewInstBefore(newEI0, EI);
12444 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000012445 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012446 }
12447 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000012448 unsigned AS =
12449 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000012450 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Anderson6b6e2d92009-07-29 22:17:13 +000012451 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000012452 GetElementPtrInst *GEP =
12453 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohman17f46f72009-07-28 01:40:03 +000012454 cast<GEPOperator>(GEP)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012455 InsertNewInstBefore(GEP, EI);
12456 return new LoadInst(GEP);
12457 }
12458 }
12459 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12460 // Extracting the inserted element?
12461 if (IE->getOperand(2) == EI.getOperand(1))
12462 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12463 // If the inserted and extracted elements are constants, they must not
12464 // be the same value, extract from the pre-inserted value instead.
12465 if (isa<Constant>(IE->getOperand(2)) &&
12466 isa<Constant>(EI.getOperand(1))) {
12467 AddUsesToWorkList(EI);
12468 EI.setOperand(0, IE->getOperand(0));
12469 return &EI;
12470 }
12471 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12472 // If this is extracting an element from a shufflevector, figure out where
12473 // it came from and extract from the appropriate input element instead.
12474 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12475 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12476 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012477 unsigned LHSWidth =
12478 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12479
12480 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012481 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012482 else if (SrcIdx < LHSWidth*2) {
12483 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012484 Src = SVI->getOperand(1);
12485 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012486 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012487 }
Eric Christopher1ba36872009-07-25 02:28:41 +000012488 return ExtractElementInst::Create(Src,
Owen Andersoneacb44d2009-07-24 23:12:02 +000012489 ConstantInt::get(Type::Int32Ty, SrcIdx, false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012490 }
12491 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000012492 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012493 }
12494 return 0;
12495}
12496
12497/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12498/// elements from either LHS or RHS, return the shuffle mask and true.
12499/// Otherwise, return false.
12500static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000012501 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012502 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012503 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12504 "Invalid CollectSingleShuffleElements");
12505 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12506
12507 if (isa<UndefValue>(V)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012508 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012509 return true;
12510 } else if (V == LHS) {
12511 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneacb44d2009-07-24 23:12:02 +000012512 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012513 return true;
12514 } else if (V == RHS) {
12515 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneacb44d2009-07-24 23:12:02 +000012516 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012517 return true;
12518 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12519 // If this is an insert of an extract from some other vector, include it.
12520 Value *VecOp = IEI->getOperand(0);
12521 Value *ScalarOp = IEI->getOperand(1);
12522 Value *IdxOp = IEI->getOperand(2);
12523
12524 if (!isa<ConstantInt>(IdxOp))
12525 return false;
12526 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12527
12528 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12529 // Okay, we can handle this if the vector we are insertinting into is
12530 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012531 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012532 // If so, update the mask to reflect the inserted undef.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012533 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012534 return true;
12535 }
12536 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12537 if (isa<ConstantInt>(EI->getOperand(1)) &&
12538 EI->getOperand(0)->getType() == V->getType()) {
12539 unsigned ExtractedIdx =
12540 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12541
12542 // This must be extracting from either LHS or RHS.
12543 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12544 // Okay, we can handle this if the vector we are insertinting into is
12545 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012546 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012547 // If so, update the mask to reflect the inserted value.
12548 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012549 Mask[InsertedIdx % NumElts] =
Owen Andersoneacb44d2009-07-24 23:12:02 +000012550 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012551 } else {
12552 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012553 Mask[InsertedIdx % NumElts] =
Owen Andersoneacb44d2009-07-24 23:12:02 +000012554 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012555
12556 }
12557 return true;
12558 }
12559 }
12560 }
12561 }
12562 }
12563 // TODO: Handle shufflevector here!
12564
12565 return false;
12566}
12567
12568/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12569/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12570/// that computes V and the LHS value of the shuffle.
12571static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012572 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012573 assert(isa<VectorType>(V->getType()) &&
12574 (RHS == 0 || V->getType() == RHS->getType()) &&
12575 "Invalid shuffle!");
12576 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12577
12578 if (isa<UndefValue>(V)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012579 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012580 return V;
12581 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000012582 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012583 return V;
12584 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12585 // If this is an insert of an extract from some other vector, include it.
12586 Value *VecOp = IEI->getOperand(0);
12587 Value *ScalarOp = IEI->getOperand(1);
12588 Value *IdxOp = IEI->getOperand(2);
12589
12590 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12591 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12592 EI->getOperand(0)->getType() == V->getType()) {
12593 unsigned ExtractedIdx =
12594 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12595 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12596
12597 // Either the extracted from or inserted into vector must be RHSVec,
12598 // otherwise we'd end up with a shuffle of three inputs.
12599 if (EI->getOperand(0) == RHS || RHS == 0) {
12600 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000012601 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012602 Mask[InsertedIdx % NumElts] =
Owen Andersoneacb44d2009-07-24 23:12:02 +000012603 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012604 return V;
12605 }
12606
12607 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012608 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12609 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012610 // Everything but the extracted element is replaced with the RHS.
12611 for (unsigned i = 0; i != NumElts; ++i) {
12612 if (i != InsertedIdx)
Owen Andersoneacb44d2009-07-24 23:12:02 +000012613 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012614 }
12615 return V;
12616 }
12617
12618 // If this insertelement is a chain that comes from exactly these two
12619 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000012620 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12621 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012622 return EI->getOperand(0);
12623
12624 }
12625 }
12626 }
12627 // TODO: Handle shufflevector here!
12628
12629 // Otherwise, can't do anything fancy. Return an identity vector.
12630 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneacb44d2009-07-24 23:12:02 +000012631 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012632 return V;
12633}
12634
12635Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12636 Value *VecOp = IE.getOperand(0);
12637 Value *ScalarOp = IE.getOperand(1);
12638 Value *IdxOp = IE.getOperand(2);
12639
12640 // Inserting an undef or into an undefined place, remove this.
12641 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12642 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000012643
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012644 // If the inserted element was extracted from some other vector, and if the
12645 // indexes are constant, try to turn this into a shufflevector operation.
12646 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12647 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12648 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000012649 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012650 unsigned ExtractedIdx =
12651 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12652 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12653
12654 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12655 return ReplaceInstUsesWith(IE, VecOp);
12656
12657 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012658 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012659
12660 // If we are extracting a value from a vector, then inserting it right
12661 // back into the same place, just use the input vector.
12662 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12663 return ReplaceInstUsesWith(IE, VecOp);
12664
12665 // We could theoretically do this for ANY input. However, doing so could
12666 // turn chains of insertelement instructions into a chain of shufflevector
12667 // instructions, and right now we do not merge shufflevectors. As such,
12668 // only do this in a situation where it is clear that there is benefit.
12669 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12670 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12671 // the values of VecOp, except then one read from EIOp0.
12672 // Build a new shuffle mask.
12673 std::vector<Constant*> Mask;
12674 if (isa<UndefValue>(VecOp))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012675 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012676 else {
12677 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersoneacb44d2009-07-24 23:12:02 +000012678 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012679 NumVectorElts));
12680 }
Owen Anderson24be4c12009-07-03 00:17:18 +000012681 Mask[InsertedIdx] =
Owen Andersoneacb44d2009-07-24 23:12:02 +000012682 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012683 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Anderson2f422e02009-07-28 21:19:26 +000012684 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012685 }
12686
12687 // If this insertelement isn't used by some other insertelement, turn it
12688 // (and any insertelements it points to), into one big shuffle.
12689 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12690 std::vector<Constant*> Mask;
12691 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000012692 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Andersonb99ecca2009-07-30 23:03:37 +000012693 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012694 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000012695 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +000012696 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012697 }
12698 }
12699 }
12700
Eli Friedmanbefee262009-06-06 20:08:03 +000012701 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12702 APInt UndefElts(VWidth, 0);
12703 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12704 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12705 return &IE;
12706
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012707 return 0;
12708}
12709
12710
12711Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12712 Value *LHS = SVI.getOperand(0);
12713 Value *RHS = SVI.getOperand(1);
12714 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12715
12716 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012717
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012718 // Undefined shuffle mask -> undefined value.
12719 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012720 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012721
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012722 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012723
12724 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12725 return 0;
12726
Evan Cheng63295ab2009-02-03 10:05:09 +000012727 APInt UndefElts(VWidth, 0);
12728 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12729 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012730 LHS = SVI.getOperand(0);
12731 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012732 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012733 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012734
12735 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12736 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12737 if (LHS == RHS || isa<UndefValue>(LHS)) {
12738 if (isa<UndefValue>(LHS) && LHS == RHS) {
12739 // shuffle(undef,undef,mask) -> undef.
12740 return ReplaceInstUsesWith(SVI, LHS);
12741 }
12742
12743 // Remap any references to RHS to use LHS.
12744 std::vector<Constant*> Elts;
12745 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12746 if (Mask[i] >= 2*e)
Owen Andersonb99ecca2009-07-30 23:03:37 +000012747 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012748 else {
12749 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012750 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012751 Mask[i] = 2*e; // Turn into undef.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012752 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012753 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012754 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersoneacb44d2009-07-24 23:12:02 +000012755 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012756 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012757 }
12758 }
12759 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +000012760 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +000012761 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012762 LHS = SVI.getOperand(0);
12763 RHS = SVI.getOperand(1);
12764 MadeChange = true;
12765 }
12766
12767 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12768 bool isLHSID = true, isRHSID = true;
12769
12770 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12771 if (Mask[i] >= e*2) continue; // Ignore undef values.
12772 // Is this an identity shuffle of the LHS value?
12773 isLHSID &= (Mask[i] == i);
12774
12775 // Is this an identity shuffle of the RHS value?
12776 isRHSID &= (Mask[i]-e == i);
12777 }
12778
12779 // Eliminate identity shuffles.
12780 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12781 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12782
12783 // If the LHS is a shufflevector itself, see if we can combine it with this
12784 // one without producing an unusual shuffle. Here we are really conservative:
12785 // we are absolutely afraid of producing a shuffle mask not in the input
12786 // program, because the code gen may not be smart enough to turn a merged
12787 // shuffle into two specific shuffles: it may produce worse code. As such,
12788 // we only merge two shuffles if the result is one of the two input shuffle
12789 // masks. In this case, merging the shuffles just removes one instruction,
12790 // which we know is safe. This is good for things like turning:
12791 // (splat(splat)) -> splat.
12792 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12793 if (isa<UndefValue>(RHS)) {
12794 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12795
12796 std::vector<unsigned> NewMask;
12797 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12798 if (Mask[i] >= 2*e)
12799 NewMask.push_back(2*e);
12800 else
12801 NewMask.push_back(LHSMask[Mask[i]]);
12802
12803 // If the result mask is equal to the src shuffle or this shuffle mask, do
12804 // the replacement.
12805 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000012806 unsigned LHSInNElts =
12807 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012808 std::vector<Constant*> Elts;
12809 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000012810 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012811 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012812 } else {
Owen Andersoneacb44d2009-07-24 23:12:02 +000012813 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012814 }
12815 }
12816 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12817 LHSSVI->getOperand(1),
Owen Anderson2f422e02009-07-28 21:19:26 +000012818 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012819 }
12820 }
12821 }
12822
12823 return MadeChange ? &SVI : 0;
12824}
12825
12826
12827
12828
12829/// TryToSinkInstruction - Try to move the specified instruction from its
12830/// current block into the beginning of DestBlock, which can only happen if it's
12831/// safe to move the instruction past all of the instructions between it and the
12832/// end of its block.
12833static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12834 assert(I->hasOneUse() && "Invariants didn't hold!");
12835
12836 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000012837 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012838 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012839
12840 // Do not sink alloca instructions out of the entry block.
12841 if (isa<AllocaInst>(I) && I->getParent() ==
12842 &DestBlock->getParent()->getEntryBlock())
12843 return false;
12844
12845 // We can only sink load instructions if there is nothing between the load and
12846 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012847 if (I->mayReadFromMemory()) {
12848 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012849 Scan != E; ++Scan)
12850 if (Scan->mayWriteToMemory())
12851 return false;
12852 }
12853
Dan Gohman514277c2008-05-23 21:05:58 +000012854 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012855
Dale Johannesen24339f12009-03-03 01:09:07 +000012856 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012857 I->moveBefore(InsertPos);
12858 ++NumSunkInst;
12859 return true;
12860}
12861
12862
12863/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12864/// all reachable code to the worklist.
12865///
12866/// This has a couple of tricks to make the code faster and more powerful. In
12867/// particular, we constant fold and DCE instructions as we go, to avoid adding
12868/// them to the worklist (this significantly speeds up instcombine on code where
12869/// many instructions are dead or constant). Additionally, if we find a branch
12870/// whose condition is a known constant, we only visit the reachable successors.
12871///
12872static void AddReachableCodeToWorklist(BasicBlock *BB,
12873 SmallPtrSet<BasicBlock*, 64> &Visited,
12874 InstCombiner &IC,
12875 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000012876 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012877 Worklist.push_back(BB);
12878
12879 while (!Worklist.empty()) {
12880 BB = Worklist.back();
12881 Worklist.pop_back();
12882
12883 // We have now visited this block! If we've already been here, ignore it.
12884 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012885
12886 DbgInfoIntrinsic *DBI_Prev = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012887 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12888 Instruction *Inst = BBI++;
12889
12890 // DCE instruction if trivially dead.
12891 if (isInstructionTriviallyDead(Inst)) {
12892 ++NumDeadInst;
Dan Gohman3fa885b2009-08-12 16:28:31 +000012893 DOUT << "IC: DCE: " << *Inst << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012894 Inst->eraseFromParent();
12895 continue;
12896 }
12897
12898 // ConstantProp instruction if trivially constant.
Owen Andersond4d90a02009-07-06 18:42:36 +000012899 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Dan Gohman3fa885b2009-08-12 16:28:31 +000012900 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012901 Inst->replaceAllUsesWith(C);
12902 ++NumConstProp;
12903 Inst->eraseFromParent();
12904 continue;
12905 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000012906
Devang Patel794140c2008-11-19 18:56:50 +000012907 // If there are two consecutive llvm.dbg.stoppoint calls then
12908 // it is likely that the optimizer deleted code in between these
12909 // two intrinsics.
12910 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12911 if (DBI_Next) {
12912 if (DBI_Prev
12913 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12914 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12915 IC.RemoveFromWorkList(DBI_Prev);
12916 DBI_Prev->eraseFromParent();
12917 }
12918 DBI_Prev = DBI_Next;
Zhou Sheng77e03b92009-02-23 10:14:11 +000012919 } else {
12920 DBI_Prev = 0;
Devang Patel794140c2008-11-19 18:56:50 +000012921 }
12922
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012923 IC.AddToWorkList(Inst);
12924 }
12925
12926 // Recursively visit successors. If this is a branch or switch on a
12927 // constant, only visit the reachable successor.
12928 TerminatorInst *TI = BB->getTerminator();
12929 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12930 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12931 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012932 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012933 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012934 continue;
12935 }
12936 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12937 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12938 // See if this is an explicit destination.
12939 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12940 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012941 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012942 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012943 continue;
12944 }
12945
12946 // Otherwise it is the default destination.
12947 Worklist.push_back(SI->getSuccessor(0));
12948 continue;
12949 }
12950 }
12951
12952 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12953 Worklist.push_back(TI->getSuccessor(i));
12954 }
12955}
12956
12957bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12958 bool Changed = false;
Dan Gohmana80e2712009-07-21 23:21:54 +000012959 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012960
Daniel Dunbar005975c2009-07-25 00:23:56 +000012961 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12962 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012963
12964 {
12965 // Do a depth-first traversal of the function, populate the worklist with
12966 // the reachable instructions. Ignore blocks that are not reachable. Keep
12967 // track of which blocks we visit.
12968 SmallPtrSet<BasicBlock*, 64> Visited;
12969 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12970
12971 // Do a quick scan over the function. If we find any blocks that are
12972 // unreachable, remove any instructions inside of them. This prevents
12973 // the instcombine code from having to deal with some bad special cases.
12974 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12975 if (!Visited.count(BB)) {
12976 Instruction *Term = BB->getTerminator();
12977 while (Term != BB->begin()) { // Remove instrs bottom-up
12978 BasicBlock::iterator I = Term; --I;
12979
Dan Gohman3fa885b2009-08-12 16:28:31 +000012980 DOUT << "IC: DCE: " << *I << '\n';
Dale Johannesendf356c62009-03-10 21:19:49 +000012981 // A debug intrinsic shouldn't force another iteration if we weren't
12982 // going to do one without it.
12983 if (!isa<DbgInfoIntrinsic>(I)) {
12984 ++NumDeadInst;
12985 Changed = true;
12986 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012987 if (!I->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +000012988 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012989 I->eraseFromParent();
12990 }
12991 }
12992 }
12993
12994 while (!Worklist.empty()) {
12995 Instruction *I = RemoveOneFromWorkList();
12996 if (I == 0) continue; // skip null values.
12997
12998 // Check to see if we can DCE the instruction.
12999 if (isInstructionTriviallyDead(I)) {
13000 // Add operands to the worklist.
13001 if (I->getNumOperands() < 4)
13002 AddUsesToWorkList(*I);
13003 ++NumDeadInst;
13004
Dan Gohman3fa885b2009-08-12 16:28:31 +000013005 DOUT << "IC: DCE: " << *I << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013006
13007 I->eraseFromParent();
13008 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000013009 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013010 continue;
13011 }
13012
13013 // Instruction isn't dead, see if we can constant propagate it.
Owen Andersond4d90a02009-07-06 18:42:36 +000013014 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Dan Gohman3fa885b2009-08-12 16:28:31 +000013015 DOUT << "IC: ConstFold to: " << *C << " from: " << *I << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013016
13017 // Add operands to the worklist.
13018 AddUsesToWorkList(*I);
13019 ReplaceInstUsesWith(*I, C);
13020
13021 ++NumConstProp;
13022 I->eraseFromParent();
13023 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000013024 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013025 continue;
13026 }
13027
Eli Friedman5c619182009-07-15 22:13:34 +000013028 if (TD) {
Nick Lewyckyadb67922008-05-25 20:56:15 +000013029 // See if we can constant fold its operands.
Chris Lattnerf6d58862009-01-31 07:04:22 +000013030 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13031 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Andersond4d90a02009-07-06 18:42:36 +000013032 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13033 F.getContext(), TD))
Chris Lattnerf6d58862009-01-31 07:04:22 +000013034 if (NewC != CE) {
13035 i->set(NewC);
13036 Changed = true;
13037 }
Nick Lewyckyadb67922008-05-25 20:56:15 +000013038 }
13039
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013040 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000013041 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013042 BasicBlock *BB = I->getParent();
13043 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13044 if (UserParent != BB) {
13045 bool UserIsSuccessor = false;
13046 // See if the user is one of our successors.
13047 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13048 if (*SI == UserParent) {
13049 UserIsSuccessor = true;
13050 break;
13051 }
13052
13053 // If the user is one of our immediate successors, and if that successor
13054 // only has us as a predecessors (we'd have to split the critical edge
13055 // otherwise), we can keep going.
13056 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13057 next(pred_begin(UserParent)) == pred_end(UserParent))
13058 // Okay, the CFG is simple enough, try to sink this instruction.
13059 Changed |= TryToSinkInstruction(I, UserParent);
13060 }
13061 }
13062
13063 // Now that we have an instruction, try combining it to simplify it...
13064#ifndef NDEBUG
13065 std::string OrigI;
13066#endif
13067 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13068 if (Instruction *Result = visit(*I)) {
13069 ++NumCombined;
13070 // Should we replace the old instruction with a new one?
13071 if (Result != I) {
Dan Gohman3fa885b2009-08-12 16:28:31 +000013072 DOUT << "IC: Old = " << *I << '\n'
13073 << " New = " << *Result << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013074
13075 // Everything uses the new instruction now.
13076 I->replaceAllUsesWith(Result);
13077
13078 // Push the new instruction and any users onto the worklist.
13079 AddToWorkList(Result);
13080 AddUsersToWorkList(*Result);
13081
13082 // Move the name to the new instruction first.
13083 Result->takeName(I);
13084
13085 // Insert the new instruction into the basic block...
13086 BasicBlock *InstParent = I->getParent();
13087 BasicBlock::iterator InsertPos = I;
13088
13089 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13090 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13091 ++InsertPos;
13092
13093 InstParent->getInstList().insert(InsertPos, Result);
13094
13095 // Make sure that we reprocess all operands now that we reduced their
13096 // use counts.
13097 AddUsesToWorkList(*I);
13098
13099 // Instructions can end up on the worklist more than once. Make sure
13100 // we do not process an instruction that has been deleted.
13101 RemoveFromWorkList(I);
13102
13103 // Erase the old instruction.
13104 InstParent->getInstList().erase(I);
13105 } else {
13106#ifndef NDEBUG
Dan Gohman3fa885b2009-08-12 16:28:31 +000013107 DOUT << "IC: Mod = " << OrigI << '\n'
13108 << " New = " << *I << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013109#endif
13110
13111 // If the instruction was modified, it's possible that it is now dead.
13112 // if so, remove it.
13113 if (isInstructionTriviallyDead(I)) {
13114 // Make sure we process all operands now that we are reducing their
13115 // use counts.
13116 AddUsesToWorkList(*I);
13117
13118 // Instructions may end up in the worklist more than once. Erase all
13119 // occurrences of this instruction.
13120 RemoveFromWorkList(I);
13121 I->eraseFromParent();
13122 } else {
13123 AddToWorkList(I);
13124 AddUsersToWorkList(*I);
13125 }
13126 }
13127 Changed = true;
13128 }
13129 }
13130
13131 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000013132
13133 // Do an explicit clear, this shrinks the map if needed.
13134 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013135 return Changed;
13136}
13137
13138
13139bool InstCombiner::runOnFunction(Function &F) {
13140 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000013141 Context = &F.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013142
13143 bool EverMadeChange = false;
13144
13145 // Iterate while there is work to do.
13146 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000013147 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013148 EverMadeChange = true;
13149 return EverMadeChange;
13150}
13151
13152FunctionPass *llvm::createInstructionCombiningPass() {
13153 return new InstCombiner();
13154}