blob: 186d8378a4972cd2323ab101f4eae4545408dca0 [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"
39#include "llvm/Pass.h"
40#include "llvm/DerivedTypes.h"
41#include "llvm/GlobalVariable.h"
42#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnera432bc72008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
47#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049#include "llvm/Support/Debug.h"
50#include "llvm/Support/GetElementPtrTypeIterator.h"
51#include "llvm/Support/InstVisitor.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/PatternMatch.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/ADT/DenseMap.h"
56#include "llvm/ADT/SmallVector.h"
57#include "llvm/ADT/SmallPtrSet.h"
58#include "llvm/ADT/Statistic.h"
59#include "llvm/ADT/STLExtras.h"
60#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000061#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062#include <sstream>
63using namespace llvm;
64using namespace llvm::PatternMatch;
65
66STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72namespace {
73 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
76 // Worklist of all of the instructions that need to be simplified.
Chris Lattnera06291a2008-08-15 04:03:01 +000077 SmallVector<Instruction*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078 DenseMap<Instruction*, unsigned> WorklistMap;
79 TargetData *TD;
80 bool MustPreserveLCSSA;
81 public:
82 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000083 InstCombiner() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084
85 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
Dan Gohman55d19662008-07-07 17:46:23 +000088 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
109
110
111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
115 void AddUsersToWorkList(Value &I) {
116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117 UI != UE; ++UI)
118 AddToWorkList(cast<Instruction>(*UI));
119 }
120
121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
Gabor Greif17396002008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127 AddToWorkList(Op);
128 }
129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
Gabor Greif17396002008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 AddToWorkList(Op);
142 // Set the operand to undef to drop the use.
Gabor Greif17396002008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144 }
145
146 return R;
147 }
148
149 public:
150 virtual bool runOnFunction(Function &F);
151
152 bool DoOneIteration(Function &F, unsigned ItNum);
153
154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155 AU.addRequired<TargetData>();
156 AU.addPreservedID(LCSSAID);
157 AU.setPreservesCFG();
158 }
159
160 TargetData &getTargetData() const { return *TD; }
161
162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
166 // I - Change was made, I is still valid, I may be dead though
167 // otherwise - Change was made, replace I with returned instruction
168 //
169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000175 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000183 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000185 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000186 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000187 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 Instruction *visitOr (BinaryOperator &I);
189 Instruction *visitXor(BinaryOperator &I);
190 Instruction *visitShl(BinaryOperator &I);
191 Instruction *visitAShr(BinaryOperator &I);
192 Instruction *visitLShr(BinaryOperator &I);
193 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000194 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
195 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196 Instruction *visitFCmpInst(FCmpInst &I);
197 Instruction *visitICmpInst(ICmpInst &I);
198 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
199 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
200 Instruction *LHS,
201 ConstantInt *RHS);
202 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203 ConstantInt *DivRHS);
204
205 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206 ICmpInst::Predicate Cond, Instruction &I);
207 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
208 BinaryOperator &I);
209 Instruction *commonCastTransforms(CastInst &CI);
210 Instruction *commonIntCastTransforms(CastInst &CI);
211 Instruction *commonPointerCastTransforms(CastInst &CI);
212 Instruction *visitTrunc(TruncInst &CI);
213 Instruction *visitZExt(ZExtInst &CI);
214 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000215 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000217 Instruction *visitFPToUI(FPToUIInst &FI);
218 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 Instruction *visitUIToFP(CastInst &CI);
220 Instruction *visitSIToFP(CastInst &CI);
221 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000222 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223 Instruction *visitBitCast(BitCastInst &CI);
224 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
225 Instruction *FI);
Dan Gohman58c09632008-09-16 18:46:06 +0000226 Instruction *visitSelectInst(SelectInst &SI);
227 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 Instruction *visitCallInst(CallInst &CI);
229 Instruction *visitInvokeInst(InvokeInst &II);
230 Instruction *visitPHINode(PHINode &PN);
231 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
232 Instruction *visitAllocationInst(AllocationInst &AI);
233 Instruction *visitFreeInst(FreeInst &FI);
234 Instruction *visitLoadInst(LoadInst &LI);
235 Instruction *visitStoreInst(StoreInst &SI);
236 Instruction *visitBranchInst(BranchInst &BI);
237 Instruction *visitSwitchInst(SwitchInst &SI);
238 Instruction *visitInsertElementInst(InsertElementInst &IE);
239 Instruction *visitExtractElementInst(ExtractElementInst &EI);
240 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000241 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242
243 // visitInstruction - Specify what to return for unhandled instructions...
244 Instruction *visitInstruction(Instruction &I) { return 0; }
245
246 private:
247 Instruction *visitCallSite(CallSite CS);
248 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000249 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000250 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000252 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253
254 public:
255 // InsertNewInstBefore - insert an instruction New before instruction Old
256 // in the program. Add the new instruction to the worklist.
257 //
258 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
259 assert(New && New->getParent() == 0 &&
260 "New instruction already inserted into a basic block!");
261 BasicBlock *BB = Old.getParent();
262 BB->getInstList().insert(&Old, New); // Insert inst
263 AddToWorkList(New);
264 return New;
265 }
266
267 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
268 /// This also adds the cast to the worklist. Finally, this returns the
269 /// cast.
270 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
271 Instruction &Pos) {
272 if (V->getType() == Ty) return V;
273
274 if (Constant *CV = dyn_cast<Constant>(V))
275 return ConstantExpr::getCast(opc, CV, Ty);
276
Gabor Greifa645dd32008-05-16 19:29:10 +0000277 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278 AddToWorkList(C);
279 return C;
280 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000281
282 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
283 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
284 }
285
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286
287 // ReplaceInstUsesWith - This method is to be used when an instruction is
288 // found to be dead, replacable with another preexisting expression. Here
289 // we add all uses of I to the worklist, replace all uses of I with the new
290 // value, then return I, so that the inst combiner will know that I was
291 // modified.
292 //
293 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
294 AddUsersToWorkList(I); // Add all modified instrs to worklist
295 if (&I != V) {
296 I.replaceAllUsesWith(V);
297 return &I;
298 } else {
299 // If we are replacing the instruction with itself, this must be in a
300 // segment of unreachable code, so just clobber the instruction.
301 I.replaceAllUsesWith(UndefValue::get(I.getType()));
302 return &I;
303 }
304 }
305
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000306 // EraseInstFromFunction - When dealing with an instruction that has side
307 // effects or produces a void value, we can't rely on DCE to delete the
308 // instruction. Instead, visit methods should return the value returned by
309 // this function.
310 Instruction *EraseInstFromFunction(Instruction &I) {
311 assert(I.use_empty() && "Cannot erase instruction that is used!");
312 AddUsesToWorkList(I);
313 RemoveFromWorkList(&I);
314 I.eraseFromParent();
315 return 0; // Don't do anything with FI
316 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000317
318 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
319 APInt &KnownOne, unsigned Depth = 0) const {
320 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
321 }
322
323 bool MaskedValueIsZero(Value *V, const APInt &Mask,
324 unsigned Depth = 0) const {
325 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
326 }
327 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
328 return llvm::ComputeNumSignBits(Op, TD, Depth);
329 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330
331 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000332
333 /// SimplifyCommutative - This performs a few simplifications for
334 /// commutative operators.
335 bool SimplifyCommutative(BinaryOperator &I);
336
337 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
338 /// most-complex to least-complex order.
339 bool SimplifyCompare(CmpInst &I);
340
Chris Lattner676c78e2009-01-31 08:15:18 +0000341 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
342 /// based on the demanded bits.
343 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
344 APInt& KnownZero, APInt& KnownOne,
345 unsigned Depth);
346 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000348 unsigned Depth=0);
349
350 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
351 /// SimplifyDemandedBits knows about. See if the instruction has any
352 /// properties that allow us to simplify its operands.
353 bool SimplifyDemandedInstructionBits(Instruction &Inst);
354
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000355 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
356 uint64_t &UndefElts, unsigned Depth = 0);
357
358 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
359 // PHI node as operand #0, see if we can fold the instruction into the PHI
360 // (which is only possible if all operands to the PHI are constants).
361 Instruction *FoldOpIntoPhi(Instruction &I);
362
363 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
364 // operator and they all are only used by the PHI, PHI together their
365 // inputs, and do the operation once, to the result of the PHI.
366 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
367 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000368 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
369
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000370
371 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
372 ConstantInt *AndRHS, BinaryOperator &TheAnd);
373
374 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
375 bool isSub, Instruction &I);
376 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
377 bool isSigned, bool Inside, Instruction &IB);
378 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
379 Instruction *MatchBSwap(BinaryOperator &I);
380 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000381 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000382 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000383
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384
385 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000386
Dan Gohman2d648bb2008-04-10 18:43:06 +0000387 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000388 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000389 unsigned GetOrEnforceKnownAlignment(Value *V,
390 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000391
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393}
394
Dan Gohman089efff2008-05-13 00:00:25 +0000395char InstCombiner::ID = 0;
396static RegisterPass<InstCombiner>
397X("instcombine", "Combine redundant instructions");
398
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399// getComplexity: Assign a complexity or rank value to LLVM Values...
400// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
401static unsigned getComplexity(Value *V) {
402 if (isa<Instruction>(V)) {
403 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
404 return 3;
405 return 4;
406 }
407 if (isa<Argument>(V)) return 3;
408 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
409}
410
411// isOnlyUse - Return true if this instruction will be deleted if we stop using
412// it.
413static bool isOnlyUse(Value *V) {
414 return V->hasOneUse() || isa<Constant>(V);
415}
416
417// getPromotedType - Return the specified type promoted as it would be to pass
418// though a va_arg area...
419static const Type *getPromotedType(const Type *Ty) {
420 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
421 if (ITy->getBitWidth() < 32)
422 return Type::Int32Ty;
423 }
424 return Ty;
425}
426
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000427/// getBitCastOperand - If the specified operand is a CastInst, a constant
428/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
429/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430static Value *getBitCastOperand(Value *V) {
431 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000432 // BitCastInst?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433 return I->getOperand(0);
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000434 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
435 // GetElementPtrInst?
436 if (GEP->hasAllZeroIndices())
437 return GEP->getOperand(0);
438 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000440 // BitCast ConstantExp?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441 return CE->getOperand(0);
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000442 else if (CE->getOpcode() == Instruction::GetElementPtr) {
443 // GetElementPtr ConstantExp?
444 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
445 I != E; ++I) {
446 ConstantInt *CI = dyn_cast<ConstantInt>(I);
447 if (!CI || !CI->isZero())
448 // Any non-zero indices? Not cast-like.
449 return 0;
450 }
451 // All-zero indices? This is just like casting.
452 return CE->getOperand(0);
453 }
454 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000455 return 0;
456}
457
458/// This function is a wrapper around CastInst::isEliminableCastPair. It
459/// simply extracts arguments and returns what that function returns.
460static Instruction::CastOps
461isEliminableCastPair(
462 const CastInst *CI, ///< The first cast instruction
463 unsigned opcode, ///< The opcode of the second cast instruction
464 const Type *DstTy, ///< The target type for the second cast instruction
465 TargetData *TD ///< The target data for pointer size
466) {
467
468 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
469 const Type *MidTy = CI->getType(); // B from above
470
471 // Get the opcodes of the two Cast instructions
472 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
473 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
474
475 return Instruction::CastOps(
476 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
477 DstTy, TD->getIntPtrType()));
478}
479
480/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
481/// in any code being generated. It does not require codegen if V is simple
482/// enough or if the cast can be folded into other casts.
483static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
484 const Type *Ty, TargetData *TD) {
485 if (V->getType() == Ty || isa<Constant>(V)) return false;
486
487 // If this is another cast that can be eliminated, it isn't codegen either.
488 if (const CastInst *CI = dyn_cast<CastInst>(V))
489 if (isEliminableCastPair(CI, opcode, Ty, TD))
490 return false;
491 return true;
492}
493
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000494// SimplifyCommutative - This performs a few simplifications for commutative
495// operators:
496//
497// 1. Order operands such that they are listed from right (least complex) to
498// left (most complex). This puts constants before unary operators before
499// binary operators.
500//
501// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
502// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
503//
504bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
505 bool Changed = false;
506 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
507 Changed = !I.swapOperands();
508
509 if (!I.isAssociative()) return Changed;
510 Instruction::BinaryOps Opcode = I.getOpcode();
511 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
512 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
513 if (isa<Constant>(I.getOperand(1))) {
514 Constant *Folded = ConstantExpr::get(I.getOpcode(),
515 cast<Constant>(I.getOperand(1)),
516 cast<Constant>(Op->getOperand(1)));
517 I.setOperand(0, Op->getOperand(0));
518 I.setOperand(1, Folded);
519 return true;
520 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
521 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
522 isOnlyUse(Op) && isOnlyUse(Op1)) {
523 Constant *C1 = cast<Constant>(Op->getOperand(1));
524 Constant *C2 = cast<Constant>(Op1->getOperand(1));
525
526 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
527 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000528 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000529 Op1->getOperand(0),
530 Op1->getName(), &I);
531 AddToWorkList(New);
532 I.setOperand(0, New);
533 I.setOperand(1, Folded);
534 return true;
535 }
536 }
537 return Changed;
538}
539
540/// SimplifyCompare - For a CmpInst this function just orders the operands
541/// so that theyare listed from right (least complex) to left (most complex).
542/// This puts constants before unary operators before binary operators.
543bool InstCombiner::SimplifyCompare(CmpInst &I) {
544 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
545 return false;
546 I.swapOperands();
547 // Compare instructions are not associative so there's nothing else we can do.
548 return true;
549}
550
551// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
552// if the LHS is a constant zero (which is the 'negate' form).
553//
554static inline Value *dyn_castNegVal(Value *V) {
555 if (BinaryOperator::isNeg(V))
556 return BinaryOperator::getNegArgument(V);
557
558 // Constants can be considered to be negated values if they can be folded.
559 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
560 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000561
562 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
563 if (C->getType()->getElementType()->isInteger())
564 return ConstantExpr::getNeg(C);
565
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566 return 0;
567}
568
569static inline Value *dyn_castNotVal(Value *V) {
570 if (BinaryOperator::isNot(V))
571 return BinaryOperator::getNotArgument(V);
572
573 // Constants can be considered to be not'ed values...
574 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
575 return ConstantInt::get(~C->getValue());
576 return 0;
577}
578
579// dyn_castFoldableMul - If this value is a multiply that can be folded into
580// other computations (because it has a constant operand), return the
581// non-constant operand of the multiply, and set CST to point to the multiplier.
582// Otherwise, return null.
583//
584static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
585 if (V->hasOneUse() && V->getType()->isInteger())
586 if (Instruction *I = dyn_cast<Instruction>(V)) {
587 if (I->getOpcode() == Instruction::Mul)
588 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
589 return I->getOperand(0);
590 if (I->getOpcode() == Instruction::Shl)
591 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
592 // The multiplier is really 1 << CST.
593 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
594 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
595 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
596 return I->getOperand(0);
597 }
598 }
599 return 0;
600}
601
602/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
603/// expression, return it.
604static User *dyn_castGetElementPtr(Value *V) {
605 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
606 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
607 if (CE->getOpcode() == Instruction::GetElementPtr)
608 return cast<User>(V);
609 return false;
610}
611
Dan Gohman2d648bb2008-04-10 18:43:06 +0000612/// getOpcode - If this is an Instruction or a ConstantExpr, return the
613/// opcode value. Otherwise return UserOp1.
Dan Gohman8c397862008-05-29 19:53:46 +0000614static unsigned getOpcode(const Value *V) {
615 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000616 return I->getOpcode();
Dan Gohman8c397862008-05-29 19:53:46 +0000617 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000618 return CE->getOpcode();
619 // Use UserOp1 to mean there's no opcode.
620 return Instruction::UserOp1;
621}
622
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000623/// AddOne - Add one to a ConstantInt
624static ConstantInt *AddOne(ConstantInt *C) {
625 APInt Val(C->getValue());
626 return ConstantInt::get(++Val);
627}
628/// SubOne - Subtract one from a ConstantInt
629static ConstantInt *SubOne(ConstantInt *C) {
630 APInt Val(C->getValue());
631 return ConstantInt::get(--Val);
632}
633/// Add - Add two ConstantInts together
634static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
635 return ConstantInt::get(C1->getValue() + C2->getValue());
636}
637/// And - Bitwise AND two ConstantInts together
638static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() & C2->getValue());
640}
641/// Subtract - Subtract one ConstantInt from another
642static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
643 return ConstantInt::get(C1->getValue() - C2->getValue());
644}
645/// Multiply - Multiply two ConstantInts together
646static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
647 return ConstantInt::get(C1->getValue() * C2->getValue());
648}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000649/// MultiplyOverflows - True if the multiply can not be expressed in an int
650/// this size.
651static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
652 uint32_t W = C1->getBitWidth();
653 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
654 if (sign) {
655 LHSExt.sext(W * 2);
656 RHSExt.sext(W * 2);
657 } else {
658 LHSExt.zext(W * 2);
659 RHSExt.zext(W * 2);
660 }
661
662 APInt MulExt = LHSExt * RHSExt;
663
664 if (sign) {
665 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
666 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
667 return MulExt.slt(Min) || MulExt.sgt(Max);
668 } else
669 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
670}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000672
673/// ShrinkDemandedConstant - Check to see if the specified operand of the
674/// specified instruction is a constant integer. If so, check to see if there
675/// are any bits set in the constant that are not demanded. If so, shrink the
676/// constant and return true.
677static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
678 APInt Demanded) {
679 assert(I && "No instruction?");
680 assert(OpNo < I->getNumOperands() && "Operand index too large");
681
682 // If the operand is not a constant integer, nothing to do.
683 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
684 if (!OpC) return false;
685
686 // If there are no bits set that aren't demanded, nothing to do.
687 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
688 if ((~Demanded & OpC->getValue()) == 0)
689 return false;
690
691 // This instruction is producing bits that are not demanded. Shrink the RHS.
692 Demanded &= OpC->getValue();
693 I->setOperand(OpNo, ConstantInt::get(Demanded));
694 return true;
695}
696
697// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
698// set of known zero and one bits, compute the maximum and minimum values that
699// could have the specified known zero and known one bits, returning them in
700// min/max.
701static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
702 const APInt& KnownZero,
703 const APInt& KnownOne,
704 APInt& Min, APInt& Max) {
705 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
706 assert(KnownZero.getBitWidth() == BitWidth &&
707 KnownOne.getBitWidth() == BitWidth &&
708 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
709 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
710 APInt UnknownBits = ~(KnownZero|KnownOne);
711
712 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
713 // bit if it is unknown.
714 Min = KnownOne;
715 Max = KnownOne|UnknownBits;
716
717 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
718 Min.set(BitWidth-1);
719 Max.clear(BitWidth-1);
720 }
721}
722
723// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
724// a set of known zero and one bits, compute the maximum and minimum values that
725// could have the specified known zero and known one bits, returning them in
726// min/max.
727static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000728 const APInt &KnownZero,
729 const APInt &KnownOne,
730 APInt &Min, APInt &Max) {
731 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000732 assert(KnownZero.getBitWidth() == BitWidth &&
733 KnownOne.getBitWidth() == BitWidth &&
734 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
735 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
736 APInt UnknownBits = ~(KnownZero|KnownOne);
737
738 // The minimum value is when the unknown bits are all zeros.
739 Min = KnownOne;
740 // The maximum value is when the unknown bits are all ones.
741 Max = KnownOne|UnknownBits;
742}
743
Chris Lattner676c78e2009-01-31 08:15:18 +0000744/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
745/// SimplifyDemandedBits knows about. See if the instruction has any
746/// properties that allow us to simplify its operands.
747bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
748 unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
749 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
750 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
751
752 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
753 KnownZero, KnownOne, 0);
754 if (V == 0) return false;
755 if (V == &Inst) return true;
756 ReplaceInstUsesWith(Inst, V);
757 return true;
758}
759
760/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
761/// specified instruction operand if possible, updating it in place. It returns
762/// true if it made any change and false otherwise.
763bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
764 APInt &KnownZero, APInt &KnownOne,
765 unsigned Depth) {
766 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
767 KnownZero, KnownOne, Depth);
768 if (NewVal == 0) return false;
769 U.set(NewVal);
770 return true;
771}
772
773
774/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
775/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000776/// that only the bits set in DemandedMask of the result of V are ever used
777/// downstream. Consequently, depending on the mask and V, it may be possible
778/// to replace V with a constant or one of its operands. In such cases, this
779/// function does the replacement and returns true. In all other cases, it
780/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000781/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000782/// to be zero in the expression. These are provided to potentially allow the
783/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
784/// the expression. KnownOne and KnownZero always follow the invariant that
785/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
786/// the bits in KnownOne and KnownZero may only be accurate for those bits set
787/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
788/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000789///
790/// This returns null if it did not change anything and it permits no
791/// simplification. This returns V itself if it did some simplification of V's
792/// operands based on the information about what bits are demanded. This returns
793/// some other non-null value if it found out that V is equal to another value
794/// in the context where the specified bits are demanded, but not for all users.
795Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
796 APInt &KnownZero, APInt &KnownOne,
797 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000798 assert(V != 0 && "Null pointer of Value???");
799 assert(Depth <= 6 && "Limit Search Depth");
800 uint32_t BitWidth = DemandedMask.getBitWidth();
801 const IntegerType *VTy = cast<IntegerType>(V->getType());
802 assert(VTy->getBitWidth() == BitWidth &&
803 KnownZero.getBitWidth() == BitWidth &&
804 KnownOne.getBitWidth() == BitWidth &&
805 "Value *V, DemandedMask, KnownZero and KnownOne \
806 must have same BitWidth");
807 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
808 // We know all of the bits for a constant!
809 KnownOne = CI->getValue() & DemandedMask;
810 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000811 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000812 }
813
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000814 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000815 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000816 if (DemandedMask == 0) { // Not demanding any bits from V.
817 if (isa<UndefValue>(V))
818 return 0;
819 return UndefValue::get(VTy);
820 } else if (!V->hasOneUse()) { // Other users may use these bits.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000821 if (Depth != 0) { // Not at the root.
822 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
823 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner676c78e2009-01-31 08:15:18 +0000824 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000825 }
826 // If this is the root being simplified, allow it to have multiple uses,
827 // just set the DemandedMask to all bits.
828 DemandedMask = APInt::getAllOnesValue(BitWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000829 } else if (Depth == 6) { // Limit search depth.
Chris Lattner676c78e2009-01-31 08:15:18 +0000830 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000831 }
832
833 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner676c78e2009-01-31 08:15:18 +0000834 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835
836 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
837 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
838 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000839 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000840 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000841 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000842 case Instruction::And:
843 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000844 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
845 RHSKnownZero, RHSKnownOne, Depth+1) ||
846 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000848 return I;
849 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
850 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851
852 // If all of the demanded bits are known 1 on one side, return the other.
853 // These bits cannot contribute to the result of the 'and'.
854 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
855 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000856 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000857 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
858 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000859 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000860
861 // If all of the demanded bits in the inputs are known zeros, return zero.
862 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000863 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000864
865 // If the RHS is a constant, see if we can simplify it.
866 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000867 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868
869 // Output known-1 bits are only known if set in both the LHS & RHS.
870 RHSKnownOne &= LHSKnownOne;
871 // Output known-0 are known to be clear if zero in either the LHS | RHS.
872 RHSKnownZero |= LHSKnownZero;
873 break;
874 case Instruction::Or:
875 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +0000876 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
877 RHSKnownZero, RHSKnownOne, Depth+1) ||
878 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000879 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000880 return I;
881 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
882 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000883
884 // If all of the demanded bits are known zero on one side, return the other.
885 // These bits cannot contribute to the result of the 'or'.
886 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
887 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000888 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000889 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
890 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000891 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892
893 // If all of the potentially set bits on one side are known to be set on
894 // the other side, just use the 'other' side.
895 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
896 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000897 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000898 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
899 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000900 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000901
902 // If the RHS is a constant, see if we can simplify it.
903 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +0000904 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000905
906 // Output known-0 bits are only known if clear in both the LHS & RHS.
907 RHSKnownZero &= LHSKnownZero;
908 // Output known-1 are known to be set if set in either the LHS | RHS.
909 RHSKnownOne |= LHSKnownOne;
910 break;
911 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +0000912 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
913 RHSKnownZero, RHSKnownOne, Depth+1) ||
914 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000915 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000916 return I;
917 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
918 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000919
920 // If all of the demanded bits are known zero on one side, return the other.
921 // These bits cannot contribute to the result of the 'xor'.
922 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000923 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000924 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000925 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000926
927 // Output known-0 bits are known if clear or set in both the LHS & RHS.
928 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
929 (RHSKnownOne & LHSKnownOne);
930 // Output known-1 are known to be set if set in only one of the LHS, RHS.
931 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
932 (RHSKnownOne & LHSKnownZero);
933
934 // If all of the demanded bits are known to be zero on one side or the
935 // other, turn this into an *inclusive* or.
936 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
937 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
938 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +0000939 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000940 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +0000941 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942 }
943
944 // If all of the demanded bits on one side are known, and all of the set
945 // bits on that side are also known to be set on the other side, turn this
946 // into an AND, as we know the bits will be cleared.
947 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
948 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
949 // all known
950 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
951 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
952 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +0000953 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +0000954 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000955 }
956 }
957
958 // If the RHS is a constant, see if we can simplify it.
959 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
960 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +0000961 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962
963 RHSKnownZero = KnownZeroOut;
964 RHSKnownOne = KnownOneOut;
965 break;
966 }
967 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +0000968 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
969 RHSKnownZero, RHSKnownOne, Depth+1) ||
970 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000971 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000972 return I;
973 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
974 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000975
976 // If the operands are constants, see if we can simplify them.
Chris Lattner676c78e2009-01-31 08:15:18 +0000977 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
978 ShrinkDemandedConstant(I, 2, DemandedMask))
979 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000980
981 // Only known if known in both the LHS and RHS.
982 RHSKnownOne &= LHSKnownOne;
983 RHSKnownZero &= LHSKnownZero;
984 break;
985 case Instruction::Trunc: {
Chris Lattner676c78e2009-01-31 08:15:18 +0000986 unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000987 DemandedMask.zext(truncBf);
988 RHSKnownZero.zext(truncBf);
989 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +0000990 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000992 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993 DemandedMask.trunc(BitWidth);
994 RHSKnownZero.trunc(BitWidth);
995 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +0000996 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000997 break;
998 }
999 case Instruction::BitCast:
1000 if (!I->getOperand(0)->getType()->isInteger())
Chris Lattner676c78e2009-01-31 08:15:18 +00001001 return false; // vector->int or fp->int?
1002 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001003 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001004 return I;
1005 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006 break;
1007 case Instruction::ZExt: {
1008 // Compute the bits in the result that are not present in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001009 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001010
1011 DemandedMask.trunc(SrcBitWidth);
1012 RHSKnownZero.trunc(SrcBitWidth);
1013 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001014 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001016 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001017 DemandedMask.zext(BitWidth);
1018 RHSKnownZero.zext(BitWidth);
1019 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001020 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021 // The top bits are known to be zero.
1022 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1023 break;
1024 }
1025 case Instruction::SExt: {
1026 // Compute the bits in the result that are not present in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001027 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028
1029 APInt InputDemandedBits = DemandedMask &
1030 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1031
1032 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1033 // If any of the sign extended bits are demanded, we know that the sign
1034 // bit is demanded.
1035 if ((NewBits & DemandedMask) != 0)
1036 InputDemandedBits.set(SrcBitWidth-1);
1037
1038 InputDemandedBits.trunc(SrcBitWidth);
1039 RHSKnownZero.trunc(SrcBitWidth);
1040 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001041 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001042 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001043 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044 InputDemandedBits.zext(BitWidth);
1045 RHSKnownZero.zext(BitWidth);
1046 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001047 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048
1049 // If the sign bit of the input is known set or clear, then we know the
1050 // top bits of the result.
1051
1052 // If the input sign bit is known zero, or if the NewBits are not demanded
1053 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001054 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001055 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001056 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1057 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1059 RHSKnownOne |= NewBits;
1060 }
1061 break;
1062 }
1063 case Instruction::Add: {
1064 // Figure out what the input bits are. If the top bits of the and result
1065 // are not demanded, then the add doesn't demand them from its input
1066 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001067 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001068
1069 // If there is a constant on the RHS, there are a variety of xformations
1070 // we can do.
1071 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1072 // If null, this should be simplified elsewhere. Some of the xforms here
1073 // won't work if the RHS is zero.
1074 if (RHS->isZero())
1075 break;
1076
1077 // If the top bit of the output is demanded, demand everything from the
1078 // input. Otherwise, we demand all the input bits except NLZ top bits.
1079 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1080
1081 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001082 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001083 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001084 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001085
1086 // If the RHS of the add has bits set that can't affect the input, reduce
1087 // the constant.
1088 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001089 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090
1091 // Avoid excess work.
1092 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1093 break;
1094
1095 // Turn it into OR if input bits are zero.
1096 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1097 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001098 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001099 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001100 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001101 }
1102
1103 // We can say something about the output known-zero and known-one bits,
1104 // depending on potential carries from the input constant and the
1105 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1106 // bits set and the RHS constant is 0x01001, then we know we have a known
1107 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1108
1109 // To compute this, we first compute the potential carry bits. These are
1110 // the bits which may be modified. I'm not aware of a better way to do
1111 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001112 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1114
1115 // Now that we know which bits have carries, compute the known-1/0 sets.
1116
1117 // Bits are known one if they are known zero in one operand and one in the
1118 // other, and there is no input carry.
1119 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1120 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1121
1122 // Bits are known zero if they are known zero in both operands and there
1123 // is no input carry.
1124 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1125 } else {
1126 // If the high-bits of this ADD are not demanded, then it does not demand
1127 // the high bits of its LHS or RHS.
1128 if (DemandedMask[BitWidth-1] == 0) {
1129 // Right fill the mask of bits for this ADD to demand the most
1130 // significant bit and all those below it.
1131 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001132 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1133 LHSKnownZero, LHSKnownOne, Depth+1) ||
1134 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001136 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001137 }
1138 }
1139 break;
1140 }
1141 case Instruction::Sub:
1142 // If the high-bits of this SUB are not demanded, then it does not demand
1143 // the high bits of its LHS or RHS.
1144 if (DemandedMask[BitWidth-1] == 0) {
1145 // Right fill the mask of bits for this SUB to demand the most
1146 // significant bit and all those below it.
1147 uint32_t NLZ = DemandedMask.countLeadingZeros();
1148 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001149 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1150 LHSKnownZero, LHSKnownOne, Depth+1) ||
1151 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001152 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001153 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001154 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001155 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1156 // the known zeros and ones.
1157 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158 break;
1159 case Instruction::Shl:
1160 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1161 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1162 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001163 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001165 return I;
1166 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001167 RHSKnownZero <<= ShiftAmt;
1168 RHSKnownOne <<= ShiftAmt;
1169 // low bits known zero.
1170 if (ShiftAmt)
1171 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1172 }
1173 break;
1174 case Instruction::LShr:
1175 // For a logical shift right
1176 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1177 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1178
1179 // Unsigned shift right.
1180 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001181 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001182 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001183 return I;
1184 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001185 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1186 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1187 if (ShiftAmt) {
1188 // Compute the new bits that are at the top now.
1189 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1190 RHSKnownZero |= HighBits; // high bits known zero.
1191 }
1192 }
1193 break;
1194 case Instruction::AShr:
1195 // If this is an arithmetic shift right and only the low-bit is set, we can
1196 // always convert this into a logical shr, even if the shift amount is
1197 // variable. The low bit of the shift cannot be an input sign bit unless
1198 // the shift amount is >= the size of the datatype, which is undefined.
1199 if (DemandedMask == 1) {
1200 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001201 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001202 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001203 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 }
1205
1206 // If the sign bit is the only bit demanded by this ashr, then there is no
1207 // need to do it, the shift doesn't change the high bit.
1208 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001209 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210
1211 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1212 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1213
1214 // Signed shift right.
1215 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1216 // If any of the "high bits" are demanded, we should set the sign bit as
1217 // demanded.
1218 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1219 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001220 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001221 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001222 return I;
1223 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001224 // Compute the new bits that are at the top now.
1225 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1226 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1227 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1228
1229 // Handle the sign bits.
1230 APInt SignBit(APInt::getSignBit(BitWidth));
1231 // Adjust to where it is now in the mask.
1232 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1233
1234 // If the input sign bit is known to be zero, or if none of the top bits
1235 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001236 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001237 (HighBits & ~DemandedMask) == HighBits) {
1238 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001239 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001241 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1243 RHSKnownOne |= HighBits;
1244 }
1245 }
1246 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001247 case Instruction::SRem:
1248 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001249 APInt RA = Rem->getValue().abs();
1250 if (RA.isPowerOf2()) {
Nick Lewycky245de422008-07-12 05:04:38 +00001251 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001252 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001253
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001254 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001255 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001256 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001257 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001258 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001259
1260 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1261 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001262
1263 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001264
Chris Lattner676c78e2009-01-31 08:15:18 +00001265 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001266 }
1267 }
1268 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001269 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001270 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1271 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001272 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1273 KnownZero2, KnownOne2, Depth+1) ||
1274 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001275 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001276 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001277
Chris Lattneree5417c2009-01-21 18:09:24 +00001278 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001279 Leaders = std::max(Leaders,
1280 KnownZero2.countLeadingOnes());
1281 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001282 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283 }
Chris Lattner989ba312008-06-18 04:33:20 +00001284 case Instruction::Call:
1285 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1286 switch (II->getIntrinsicID()) {
1287 default: break;
1288 case Intrinsic::bswap: {
1289 // If the only bits demanded come from one byte of the bswap result,
1290 // just shift the input byte into position to eliminate the bswap.
1291 unsigned NLZ = DemandedMask.countLeadingZeros();
1292 unsigned NTZ = DemandedMask.countTrailingZeros();
1293
1294 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1295 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1296 // have 14 leading zeros, round to 8.
1297 NLZ &= ~7;
1298 NTZ &= ~7;
1299 // If we need exactly one byte, we can do this transformation.
1300 if (BitWidth-NLZ-NTZ == 8) {
1301 unsigned ResultBit = NTZ;
1302 unsigned InputBit = BitWidth-NTZ-8;
1303
1304 // Replace this with either a left or right shift to get the byte into
1305 // the right place.
1306 Instruction *NewVal;
1307 if (InputBit > ResultBit)
1308 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1309 ConstantInt::get(I->getType(), InputBit-ResultBit));
1310 else
1311 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1312 ConstantInt::get(I->getType(), ResultBit-InputBit));
1313 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001314 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001315 }
1316
1317 // TODO: Could compute known zero/one bits based on the input.
1318 break;
1319 }
1320 }
1321 }
Chris Lattner4946e222008-06-18 18:11:55 +00001322 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001323 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001324 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325
1326 // If the client is only demanding bits that we know, return the known
1327 // constant.
1328 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001329 return ConstantInt::get(RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 return false;
1331}
1332
1333
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001334/// SimplifyDemandedVectorElts - The specified value produces a vector with
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335/// 64 or fewer elements. DemandedElts contains the set of elements that are
1336/// actually used by the caller. This method analyzes which elements of the
1337/// operand are undef and returns that information in UndefElts.
1338///
1339/// If the information about demanded elements can be used to simplify the
1340/// operation, the operation is simplified, then the resultant value is
1341/// returned. This returns null if no change was made.
1342Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1343 uint64_t &UndefElts,
1344 unsigned Depth) {
1345 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1346 assert(VWidth <= 64 && "Vector too wide to analyze!");
1347 uint64_t EltMask = ~0ULL >> (64-VWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001348 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349
1350 if (isa<UndefValue>(V)) {
1351 // If the entire vector is undefined, just return this info.
1352 UndefElts = EltMask;
1353 return 0;
1354 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1355 UndefElts = EltMask;
1356 return UndefValue::get(V->getType());
1357 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001358
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001359 UndefElts = 0;
1360 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1361 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1362 Constant *Undef = UndefValue::get(EltTy);
1363
1364 std::vector<Constant*> Elts;
1365 for (unsigned i = 0; i != VWidth; ++i)
1366 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1367 Elts.push_back(Undef);
1368 UndefElts |= (1ULL << i);
1369 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1370 Elts.push_back(Undef);
1371 UndefElts |= (1ULL << i);
1372 } else { // Otherwise, defined.
1373 Elts.push_back(CP->getOperand(i));
1374 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001375
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001376 // If we changed the constant, return it.
1377 Constant *NewCP = ConstantVector::get(Elts);
1378 return NewCP != CP ? NewCP : 0;
1379 } else if (isa<ConstantAggregateZero>(V)) {
1380 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1381 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001382
1383 // Check if this is identity. If so, return 0 since we are not simplifying
1384 // anything.
1385 if (DemandedElts == ((1ULL << VWidth) -1))
1386 return 0;
1387
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1389 Constant *Zero = Constant::getNullValue(EltTy);
1390 Constant *Undef = UndefValue::get(EltTy);
1391 std::vector<Constant*> Elts;
1392 for (unsigned i = 0; i != VWidth; ++i)
1393 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1394 UndefElts = DemandedElts ^ EltMask;
1395 return ConstantVector::get(Elts);
1396 }
1397
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001398 // Limit search depth.
1399 if (Depth == 10)
1400 return false;
1401
1402 // If multiple users are using the root value, procede with
1403 // simplification conservatively assuming that all elements
1404 // are needed.
1405 if (!V->hasOneUse()) {
1406 // Quit if we find multiple users of a non-root value though.
1407 // They'll be handled when it's their turn to be visited by
1408 // the main instcombine process.
1409 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001410 // TODO: Just compute the UndefElts information recursively.
1411 return false;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001412
1413 // Conservatively assume that all elements are needed.
1414 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001415 }
1416
1417 Instruction *I = dyn_cast<Instruction>(V);
1418 if (!I) return false; // Only analyze instructions.
1419
1420 bool MadeChange = false;
1421 uint64_t UndefElts2;
1422 Value *TmpV;
1423 switch (I->getOpcode()) {
1424 default: break;
1425
1426 case Instruction::InsertElement: {
1427 // If this is a variable index, we don't know which element it overwrites.
1428 // demand exactly the same input as we produce.
1429 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1430 if (Idx == 0) {
1431 // Note that we can't propagate undef elt info, because we don't know
1432 // which elt is getting updated.
1433 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1434 UndefElts2, Depth+1);
1435 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1436 break;
1437 }
1438
1439 // If this is inserting an element that isn't demanded, remove this
1440 // insertelement.
1441 unsigned IdxNo = Idx->getZExtValue();
1442 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1443 return AddSoonDeadInstToWorklist(*I, 0);
1444
1445 // Otherwise, the element inserted overwrites whatever was there, so the
1446 // input demanded set is simpler than the output set.
1447 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1448 DemandedElts & ~(1ULL << IdxNo),
1449 UndefElts, Depth+1);
1450 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1451
1452 // The inserted element is defined.
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001453 UndefElts &= ~(1ULL << IdxNo);
1454 break;
1455 }
1456 case Instruction::ShuffleVector: {
1457 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001458 uint64_t LHSVWidth =
1459 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001460 uint64_t LeftDemanded = 0, RightDemanded = 0;
1461 for (unsigned i = 0; i < VWidth; i++) {
1462 if (DemandedElts & (1ULL << i)) {
1463 unsigned MaskVal = Shuffle->getMaskValue(i);
1464 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001465 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001466 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001467 if (MaskVal < LHSVWidth)
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001468 LeftDemanded |= 1ULL << MaskVal;
1469 else
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001470 RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001471 }
1472 }
1473 }
1474
1475 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1476 UndefElts2, Depth+1);
1477 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1478
1479 uint64_t UndefElts3;
1480 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1481 UndefElts3, Depth+1);
1482 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1483
1484 bool NewUndefElts = false;
1485 for (unsigned i = 0; i < VWidth; i++) {
1486 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001487 if (MaskVal == -1u) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001488 uint64_t NewBit = 1ULL << i;
1489 UndefElts |= NewBit;
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001490 } else if (MaskVal < LHSVWidth) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001491 uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1492 NewUndefElts |= NewBit;
1493 UndefElts |= NewBit;
1494 } else {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001495 uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001496 NewUndefElts |= NewBit;
1497 UndefElts |= NewBit;
1498 }
1499 }
1500
1501 if (NewUndefElts) {
1502 // Add additional discovered undefs.
1503 std::vector<Constant*> Elts;
1504 for (unsigned i = 0; i < VWidth; ++i) {
1505 if (UndefElts & (1ULL << i))
1506 Elts.push_back(UndefValue::get(Type::Int32Ty));
1507 else
1508 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1509 Shuffle->getMaskValue(i)));
1510 }
1511 I->setOperand(2, ConstantVector::get(Elts));
1512 MadeChange = true;
1513 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001514 break;
1515 }
1516 case Instruction::BitCast: {
1517 // Vector->vector casts only.
1518 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1519 if (!VTy) break;
1520 unsigned InVWidth = VTy->getNumElements();
1521 uint64_t InputDemandedElts = 0;
1522 unsigned Ratio;
1523
1524 if (VWidth == InVWidth) {
1525 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1526 // elements as are demanded of us.
1527 Ratio = 1;
1528 InputDemandedElts = DemandedElts;
1529 } else if (VWidth > InVWidth) {
1530 // Untested so far.
1531 break;
1532
1533 // If there are more elements in the result than there are in the source,
1534 // then an input element is live if any of the corresponding output
1535 // elements are live.
1536 Ratio = VWidth/InVWidth;
1537 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1538 if (DemandedElts & (1ULL << OutIdx))
1539 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1540 }
1541 } else {
1542 // Untested so far.
1543 break;
1544
1545 // If there are more elements in the source than there are in the result,
1546 // then an input element is live if the corresponding output element is
1547 // live.
1548 Ratio = InVWidth/VWidth;
1549 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1550 if (DemandedElts & (1ULL << InIdx/Ratio))
1551 InputDemandedElts |= 1ULL << InIdx;
1552 }
1553
1554 // div/rem demand all inputs, because they don't want divide by zero.
1555 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1556 UndefElts2, Depth+1);
1557 if (TmpV) {
1558 I->setOperand(0, TmpV);
1559 MadeChange = true;
1560 }
1561
1562 UndefElts = UndefElts2;
1563 if (VWidth > InVWidth) {
1564 assert(0 && "Unimp");
1565 // If there are more elements in the result than there are in the source,
1566 // then an output element is undef if the corresponding input element is
1567 // undef.
1568 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1569 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1570 UndefElts |= 1ULL << OutIdx;
1571 } else if (VWidth < InVWidth) {
1572 assert(0 && "Unimp");
1573 // If there are more elements in the source than there are in the result,
1574 // then a result element is undef if all of the corresponding input
1575 // elements are undef.
1576 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1577 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1578 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1579 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1580 }
1581 break;
1582 }
1583 case Instruction::And:
1584 case Instruction::Or:
1585 case Instruction::Xor:
1586 case Instruction::Add:
1587 case Instruction::Sub:
1588 case Instruction::Mul:
1589 // div/rem demand all inputs, because they don't want divide by zero.
1590 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1591 UndefElts, Depth+1);
1592 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1593 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1594 UndefElts2, Depth+1);
1595 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1596
1597 // Output elements are undefined if both are undefined. Consider things
1598 // like undef&0. The result is known zero, not undef.
1599 UndefElts &= UndefElts2;
1600 break;
1601
1602 case Instruction::Call: {
1603 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1604 if (!II) break;
1605 switch (II->getIntrinsicID()) {
1606 default: break;
1607
1608 // Binary vector operations that work column-wise. A dest element is a
1609 // function of the corresponding input elements from the two inputs.
1610 case Intrinsic::x86_sse_sub_ss:
1611 case Intrinsic::x86_sse_mul_ss:
1612 case Intrinsic::x86_sse_min_ss:
1613 case Intrinsic::x86_sse_max_ss:
1614 case Intrinsic::x86_sse2_sub_sd:
1615 case Intrinsic::x86_sse2_mul_sd:
1616 case Intrinsic::x86_sse2_min_sd:
1617 case Intrinsic::x86_sse2_max_sd:
1618 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1619 UndefElts, Depth+1);
1620 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1621 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1622 UndefElts2, Depth+1);
1623 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1624
1625 // If only the low elt is demanded and this is a scalarizable intrinsic,
1626 // scalarize it now.
1627 if (DemandedElts == 1) {
1628 switch (II->getIntrinsicID()) {
1629 default: break;
1630 case Intrinsic::x86_sse_sub_ss:
1631 case Intrinsic::x86_sse_mul_ss:
1632 case Intrinsic::x86_sse2_sub_sd:
1633 case Intrinsic::x86_sse2_mul_sd:
1634 // TODO: Lower MIN/MAX/ABS/etc
1635 Value *LHS = II->getOperand(1);
1636 Value *RHS = II->getOperand(2);
1637 // Extract the element as scalars.
1638 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1639 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1640
1641 switch (II->getIntrinsicID()) {
1642 default: assert(0 && "Case stmts out of sync!");
1643 case Intrinsic::x86_sse_sub_ss:
1644 case Intrinsic::x86_sse2_sub_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001645 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001646 II->getName()), *II);
1647 break;
1648 case Intrinsic::x86_sse_mul_ss:
1649 case Intrinsic::x86_sse2_mul_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001650 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001651 II->getName()), *II);
1652 break;
1653 }
1654
1655 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00001656 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1657 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001658 InsertNewInstBefore(New, *II);
1659 AddSoonDeadInstToWorklist(*II, 0);
1660 return New;
1661 }
1662 }
1663
1664 // Output elements are undefined if both are undefined. Consider things
1665 // like undef&0. The result is known zero, not undef.
1666 UndefElts &= UndefElts2;
1667 break;
1668 }
1669 break;
1670 }
1671 }
1672 return MadeChange ? I : 0;
1673}
1674
Dan Gohman5d56fd42008-05-19 22:14:15 +00001675
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001676/// AssociativeOpt - Perform an optimization on an associative operator. This
1677/// function is designed to check a chain of associative operators for a
1678/// potential to apply a certain optimization. Since the optimization may be
1679/// applicable if the expression was reassociated, this checks the chain, then
1680/// reassociates the expression as necessary to expose the optimization
1681/// opportunity. This makes use of a special Functor, which must define
1682/// 'shouldApply' and 'apply' methods.
1683///
1684template<typename Functor>
Dan Gohmand8bcf5b2008-05-20 01:14:05 +00001685static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001686 unsigned Opcode = Root.getOpcode();
1687 Value *LHS = Root.getOperand(0);
1688
1689 // Quick check, see if the immediate LHS matches...
1690 if (F.shouldApply(LHS))
1691 return F.apply(Root);
1692
1693 // Otherwise, if the LHS is not of the same opcode as the root, return.
1694 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1695 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1696 // Should we apply this transform to the RHS?
1697 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1698
1699 // If not to the RHS, check to see if we should apply to the LHS...
1700 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1701 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1702 ShouldApply = true;
1703 }
1704
1705 // If the functor wants to apply the optimization to the RHS of LHSI,
1706 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1707 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001708 // Now all of the instructions are in the current basic block, go ahead
1709 // and perform the reassociation.
1710 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1711
1712 // First move the selected RHS to the LHS of the root...
1713 Root.setOperand(0, LHSI->getOperand(1));
1714
1715 // Make what used to be the LHS of the root be the user of the root...
1716 Value *ExtraOperand = TmpLHSI->getOperand(1);
1717 if (&Root == TmpLHSI) {
1718 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1719 return 0;
1720 }
1721 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1722 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001723 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001724 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001725 ARI = Root;
1726
1727 // Now propagate the ExtraOperand down the chain of instructions until we
1728 // get to LHSI.
1729 while (TmpLHSI != LHSI) {
1730 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1731 // Move the instruction to immediately before the chain we are
1732 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001733 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001734 ARI = NextLHSI;
1735
1736 Value *NextOp = NextLHSI->getOperand(1);
1737 NextLHSI->setOperand(1, ExtraOperand);
1738 TmpLHSI = NextLHSI;
1739 ExtraOperand = NextOp;
1740 }
1741
1742 // Now that the instructions are reassociated, have the functor perform
1743 // the transformation...
1744 return F.apply(Root);
1745 }
1746
1747 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1748 }
1749 return 0;
1750}
1751
Dan Gohman089efff2008-05-13 00:00:25 +00001752namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001753
Nick Lewycky27f6c132008-05-23 04:34:58 +00001754// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001755struct AddRHS {
1756 Value *RHS;
1757 AddRHS(Value *rhs) : RHS(rhs) {}
1758 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1759 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001760 return BinaryOperator::CreateShl(Add.getOperand(0),
1761 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001762 }
1763};
1764
1765// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1766// iff C1&C2 == 0
1767struct AddMaskingAnd {
1768 Constant *C2;
1769 AddMaskingAnd(Constant *c) : C2(c) {}
1770 bool shouldApply(Value *LHS) const {
1771 ConstantInt *C1;
1772 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1773 ConstantExpr::getAnd(C1, C2)->isNullValue();
1774 }
1775 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001776 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001777 }
1778};
1779
Dan Gohman089efff2008-05-13 00:00:25 +00001780}
1781
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001782static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1783 InstCombiner *IC) {
1784 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedman722b4792008-11-30 21:09:11 +00001785 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001786 }
1787
1788 // Figure out if the constant is the left or the right argument.
1789 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1790 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1791
1792 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1793 if (ConstIsRHS)
1794 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1795 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1796 }
1797
1798 Value *Op0 = SO, *Op1 = ConstOperand;
1799 if (!ConstIsRHS)
1800 std::swap(Op0, Op1);
1801 Instruction *New;
1802 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001803 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001804 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001805 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001806 SO->getName()+".cmp");
1807 else {
1808 assert(0 && "Unknown binary instruction type!");
1809 abort();
1810 }
1811 return IC->InsertNewInstBefore(New, I);
1812}
1813
1814// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1815// constant as the other operand, try to fold the binary operator into the
1816// select arguments. This also works for Cast instructions, which obviously do
1817// not have a second operand.
1818static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1819 InstCombiner *IC) {
1820 // Don't modify shared select instructions
1821 if (!SI->hasOneUse()) return 0;
1822 Value *TV = SI->getOperand(1);
1823 Value *FV = SI->getOperand(2);
1824
1825 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1826 // Bool selects with constant operands can be folded to logical ops.
1827 if (SI->getType() == Type::Int1Ty) return 0;
1828
1829 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1830 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1831
Gabor Greifd6da1d02008-04-06 20:25:17 +00001832 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1833 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001834 }
1835 return 0;
1836}
1837
1838
1839/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1840/// node as operand #0, see if we can fold the instruction into the PHI (which
1841/// is only possible if all operands to the PHI are constants).
1842Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1843 PHINode *PN = cast<PHINode>(I.getOperand(0));
1844 unsigned NumPHIValues = PN->getNumIncomingValues();
1845 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1846
1847 // Check to see if all of the operands of the PHI are constants. If there is
1848 // one non-constant value, remember the BB it is. If there is more than one
1849 // or if *it* is a PHI, bail out.
1850 BasicBlock *NonConstBB = 0;
1851 for (unsigned i = 0; i != NumPHIValues; ++i)
1852 if (!isa<Constant>(PN->getIncomingValue(i))) {
1853 if (NonConstBB) return 0; // More than one non-const value.
1854 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1855 NonConstBB = PN->getIncomingBlock(i);
1856
1857 // If the incoming non-constant value is in I's block, we have an infinite
1858 // loop.
1859 if (NonConstBB == I.getParent())
1860 return 0;
1861 }
1862
1863 // If there is exactly one non-constant value, we can insert a copy of the
1864 // operation in that block. However, if this is a critical edge, we would be
1865 // inserting the computation one some other paths (e.g. inside a loop). Only
1866 // do this if the pred block is unconditionally branching into the phi block.
1867 if (NonConstBB) {
1868 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1869 if (!BI || !BI->isUnconditional()) return 0;
1870 }
1871
1872 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001873 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001874 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1875 InsertNewInstBefore(NewPN, *PN);
1876 NewPN->takeName(PN);
1877
1878 // Next, add all of the operands to the PHI.
1879 if (I.getNumOperands() == 2) {
1880 Constant *C = cast<Constant>(I.getOperand(1));
1881 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001882 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001883 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1884 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1885 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1886 else
1887 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1888 } else {
1889 assert(PN->getIncomingBlock(i) == NonConstBB);
1890 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001891 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001892 PN->getIncomingValue(i), C, "phitmp",
1893 NonConstBB->getTerminator());
1894 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001895 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001896 CI->getPredicate(),
1897 PN->getIncomingValue(i), C, "phitmp",
1898 NonConstBB->getTerminator());
1899 else
1900 assert(0 && "Unknown binop!");
1901
1902 AddToWorkList(cast<Instruction>(InV));
1903 }
1904 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1905 }
1906 } else {
1907 CastInst *CI = cast<CastInst>(&I);
1908 const Type *RetTy = CI->getType();
1909 for (unsigned i = 0; i != NumPHIValues; ++i) {
1910 Value *InV;
1911 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1912 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1913 } else {
1914 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00001915 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001916 I.getType(), "phitmp",
1917 NonConstBB->getTerminator());
1918 AddToWorkList(cast<Instruction>(InV));
1919 }
1920 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1921 }
1922 }
1923 return ReplaceInstUsesWith(I, NewPN);
1924}
1925
Chris Lattner55476162008-01-29 06:52:45 +00001926
Chris Lattner3554f972008-05-20 05:46:13 +00001927/// WillNotOverflowSignedAdd - Return true if we can prove that:
1928/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1929/// This basically requires proving that the add in the original type would not
1930/// overflow to change the sign bit or have a carry out.
1931bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1932 // There are different heuristics we can use for this. Here are some simple
1933 // ones.
1934
1935 // Add has the property that adding any two 2's complement numbers can only
1936 // have one carry bit which can change a sign. As such, if LHS and RHS each
1937 // have at least two sign bits, we know that the addition of the two values will
1938 // sign extend fine.
1939 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1940 return true;
1941
1942
1943 // If one of the operands only has one non-zero bit, and if the other operand
1944 // has a known-zero bit in a more significant place than it (not including the
1945 // sign bit) the ripple may go up to and fill the zero, but won't change the
1946 // sign. For example, (X & ~4) + 1.
1947
1948 // TODO: Implement.
1949
1950 return false;
1951}
1952
Chris Lattner55476162008-01-29 06:52:45 +00001953
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001954Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1955 bool Changed = SimplifyCommutative(I);
1956 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1957
1958 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1959 // X + undef -> undef
1960 if (isa<UndefValue>(RHS))
1961 return ReplaceInstUsesWith(I, RHS);
1962
1963 // X + 0 --> X
1964 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1965 if (RHSC->isNullValue())
1966 return ReplaceInstUsesWith(I, LHS);
1967 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00001968 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1969 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001970 return ReplaceInstUsesWith(I, LHS);
1971 }
1972
1973 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1974 // X + (signbit) --> X ^ signbit
1975 const APInt& Val = CI->getValue();
1976 uint32_t BitWidth = Val.getBitWidth();
1977 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00001978 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001979
1980 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1981 // (X & 254)+1 -> (X&254)|1
Chris Lattner676c78e2009-01-31 08:15:18 +00001982 if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
1983 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00001984
1985 // zext(i1) - 1 -> select i1, 0, -1
1986 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
1987 if (CI->isAllOnesValue() &&
1988 ZI->getOperand(0)->getType() == Type::Int1Ty)
1989 return SelectInst::Create(ZI->getOperand(0),
1990 Constant::getNullValue(I.getType()),
1991 ConstantInt::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001992 }
1993
1994 if (isa<PHINode>(LHS))
1995 if (Instruction *NV = FoldOpIntoPhi(I))
1996 return NV;
1997
1998 ConstantInt *XorRHS = 0;
1999 Value *XorLHS = 0;
2000 if (isa<ConstantInt>(RHSC) &&
2001 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2002 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2003 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2004
2005 uint32_t Size = TySizeBits / 2;
2006 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2007 APInt CFF80Val(-C0080Val);
2008 do {
2009 if (TySizeBits > Size) {
2010 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2011 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2012 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2013 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2014 // This is a sign extend if the top bits are known zero.
2015 if (!MaskedValueIsZero(XorLHS,
2016 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2017 Size = 0; // Not a sign ext, but can't be any others either.
2018 break;
2019 }
2020 }
2021 Size >>= 1;
2022 C0080Val = APIntOps::lshr(C0080Val, Size);
2023 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2024 } while (Size >= 1);
2025
2026 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002027 // with funny bit widths then this switch statement should be removed. It
2028 // is just here to get the size of the "middle" type back up to something
2029 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002030 const Type *MiddleType = 0;
2031 switch (Size) {
2032 default: break;
2033 case 32: MiddleType = Type::Int32Ty; break;
2034 case 16: MiddleType = Type::Int16Ty; break;
2035 case 8: MiddleType = Type::Int8Ty; break;
2036 }
2037 if (MiddleType) {
2038 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2039 InsertNewInstBefore(NewTrunc, I);
2040 return new SExtInst(NewTrunc, I.getType(), I.getName());
2041 }
2042 }
2043 }
2044
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002045 if (I.getType() == Type::Int1Ty)
2046 return BinaryOperator::CreateXor(LHS, RHS);
2047
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002048 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002049 if (I.getType()->isInteger()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002050 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2051
2052 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2053 if (RHSI->getOpcode() == Instruction::Sub)
2054 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2055 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2056 }
2057 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2058 if (LHSI->getOpcode() == Instruction::Sub)
2059 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2060 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2061 }
2062 }
2063
2064 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002065 // -A + -B --> -(A + B)
2066 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002067 if (LHS->getType()->isIntOrIntVector()) {
2068 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002069 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002070 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002071 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002072 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002073 }
2074
Gabor Greifa645dd32008-05-16 19:29:10 +00002075 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002076 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002077
2078 // A + -B --> A - B
2079 if (!isa<Constant>(RHS))
2080 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002081 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002082
2083
2084 ConstantInt *C2;
2085 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2086 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002087 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002088
2089 // X*C1 + X*C2 --> X * (C1+C2)
2090 ConstantInt *C1;
2091 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002092 return BinaryOperator::CreateMul(X, Add(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002093 }
2094
2095 // X + X*C --> X * (C+1)
2096 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greifa645dd32008-05-16 19:29:10 +00002097 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002098
2099 // X + ~X --> -1 since ~X = -X-1
2100 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2101 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2102
2103
2104 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2105 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2106 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2107 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002108
2109 // A+B --> A|B iff A and B have no bits set in common.
2110 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2111 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2112 APInt LHSKnownOne(IT->getBitWidth(), 0);
2113 APInt LHSKnownZero(IT->getBitWidth(), 0);
2114 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2115 if (LHSKnownZero != 0) {
2116 APInt RHSKnownOne(IT->getBitWidth(), 0);
2117 APInt RHSKnownZero(IT->getBitWidth(), 0);
2118 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2119
2120 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002121 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002122 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002123 }
2124 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002125
Nick Lewycky83598a72008-02-03 07:42:09 +00002126 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002127 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002128 Value *W, *X, *Y, *Z;
2129 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2130 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2131 if (W != Y) {
2132 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002133 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002134 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002135 std::swap(W, X);
2136 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002137 std::swap(Y, Z);
2138 std::swap(W, X);
2139 }
2140 }
2141
2142 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002143 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002144 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002145 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002146 }
2147 }
2148 }
2149
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002150 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2151 Value *X = 0;
2152 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002153 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002154
2155 // (X & FF00) + xx00 -> (X+xx00) & FF00
2156 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2157 Constant *Anded = And(CRHS, C2);
2158 if (Anded == CRHS) {
2159 // See if all bits from the first bit set in the Add RHS up are included
2160 // in the mask. First, get the rightmost bit.
2161 const APInt& AddRHSV = CRHS->getValue();
2162
2163 // Form a mask of all bits from the lowest bit added through the top.
2164 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2165
2166 // See if the and mask includes all of these bits.
2167 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2168
2169 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2170 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002171 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002172 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002173 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002174 }
2175 }
2176 }
2177
2178 // Try to fold constant add into select arguments.
2179 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2180 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2181 return R;
2182 }
2183
2184 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002185 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002186 {
2187 CastInst *CI = dyn_cast<CastInst>(LHS);
2188 Value *Other = RHS;
2189 if (!CI) {
2190 CI = dyn_cast<CastInst>(RHS);
2191 Other = LHS;
2192 }
2193 if (CI && CI->getType()->isSized() &&
2194 (CI->getType()->getPrimitiveSizeInBits() ==
2195 TD->getIntPtrType()->getPrimitiveSizeInBits())
2196 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002197 unsigned AS =
2198 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002199 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2200 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002201 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002202 return new PtrToIntInst(I2, CI->getType());
2203 }
2204 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002205
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002206 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002207 {
2208 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002209 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002210 if (!SI) {
2211 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002212 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002213 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002214 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002215 Value *TV = SI->getTrueValue();
2216 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002217 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002218
2219 // Can we fold the add into the argument of the select?
2220 // We check both true and false select arguments for a matching subtract.
Chris Lattner641ea462008-11-16 04:46:19 +00002221 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2222 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002223 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner641ea462008-11-16 04:46:19 +00002224 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2225 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002226 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002227 }
2228 }
Chris Lattner55476162008-01-29 06:52:45 +00002229
2230 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2231 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2232 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2233 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002234
Chris Lattner3554f972008-05-20 05:46:13 +00002235 // Check for (add (sext x), y), see if we can merge this into an
2236 // integer add followed by a sext.
2237 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2238 // (add (sext x), cst) --> (sext (add x, cst'))
2239 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2240 Constant *CI =
2241 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2242 if (LHSConv->hasOneUse() &&
2243 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2244 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2245 // Insert the new, smaller add.
2246 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2247 CI, "addconv");
2248 InsertNewInstBefore(NewAdd, I);
2249 return new SExtInst(NewAdd, I.getType());
2250 }
2251 }
2252
2253 // (add (sext x), (sext y)) --> (sext (add int x, y))
2254 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2255 // Only do this if x/y have the same type, if at last one of them has a
2256 // single use (so we don't increase the number of sexts), and if the
2257 // integer add will not overflow.
2258 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2259 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2260 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2261 RHSConv->getOperand(0))) {
2262 // Insert the new integer add.
2263 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2264 RHSConv->getOperand(0),
2265 "addconv");
2266 InsertNewInstBefore(NewAdd, I);
2267 return new SExtInst(NewAdd, I.getType());
2268 }
2269 }
2270 }
2271
2272 // Check for (add double (sitofp x), y), see if we can merge this into an
2273 // integer add followed by a promotion.
2274 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2275 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2276 // ... if the constant fits in the integer value. This is useful for things
2277 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2278 // requires a constant pool load, and generally allows the add to be better
2279 // instcombined.
2280 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2281 Constant *CI =
2282 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2283 if (LHSConv->hasOneUse() &&
2284 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2285 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2286 // Insert the new integer add.
2287 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2288 CI, "addconv");
2289 InsertNewInstBefore(NewAdd, I);
2290 return new SIToFPInst(NewAdd, I.getType());
2291 }
2292 }
2293
2294 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2295 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2296 // Only do this if x/y have the same type, if at last one of them has a
2297 // single use (so we don't increase the number of int->fp conversions),
2298 // and if the integer add will not overflow.
2299 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2300 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2301 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2302 RHSConv->getOperand(0))) {
2303 // Insert the new integer add.
2304 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2305 RHSConv->getOperand(0),
2306 "addconv");
2307 InsertNewInstBefore(NewAdd, I);
2308 return new SIToFPInst(NewAdd, I.getType());
2309 }
2310 }
2311 }
2312
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002313 return Changed ? &I : 0;
2314}
2315
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002316Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2317 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2318
Chris Lattner27fbef42008-07-17 06:07:20 +00002319 if (Op0 == Op1 && // sub X, X -> 0
2320 !I.getType()->isFPOrFPVector())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002321 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2322
2323 // If this is a 'B = x-(-A)', change to B = x+A...
2324 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002325 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002326
2327 if (isa<UndefValue>(Op0))
2328 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2329 if (isa<UndefValue>(Op1))
2330 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2331
2332 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2333 // Replace (-1 - A) with (~A)...
2334 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002335 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002336
2337 // C - ~X == X + (1+C)
2338 Value *X = 0;
2339 if (match(Op1, m_Not(m_Value(X))))
Gabor Greifa645dd32008-05-16 19:29:10 +00002340 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002341
2342 // -(X >>u 31) -> (X >>s 31)
2343 // -(X >>s 31) -> (X >>u 31)
2344 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002345 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002346 if (SI->getOpcode() == Instruction::LShr) {
2347 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2348 // Check to see if we are shifting out everything but the sign bit.
2349 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2350 SI->getType()->getPrimitiveSizeInBits()-1) {
2351 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002352 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002353 SI->getOperand(0), CU, SI->getName());
2354 }
2355 }
2356 }
2357 else if (SI->getOpcode() == Instruction::AShr) {
2358 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2359 // Check to see if we are shifting out everything but the sign bit.
2360 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2361 SI->getType()->getPrimitiveSizeInBits()-1) {
2362 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002363 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002364 SI->getOperand(0), CU, SI->getName());
2365 }
2366 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002367 }
2368 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002369 }
2370
2371 // Try to fold constant sub into select arguments.
2372 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2373 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2374 return R;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002375 }
2376
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002377 if (I.getType() == Type::Int1Ty)
2378 return BinaryOperator::CreateXor(Op0, Op1);
2379
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002380 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2381 if (Op1I->getOpcode() == Instruction::Add &&
2382 !Op0->getType()->isFPOrFPVector()) {
2383 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002384 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002385 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002386 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002387 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2388 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2389 // C1-(X+C2) --> (C1-C2)-X
Gabor Greifa645dd32008-05-16 19:29:10 +00002390 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002391 Op1I->getOperand(0));
2392 }
2393 }
2394
2395 if (Op1I->hasOneUse()) {
2396 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2397 // is not used by anyone else...
2398 //
2399 if (Op1I->getOpcode() == Instruction::Sub &&
2400 !Op1I->getType()->isFPOrFPVector()) {
2401 // Swap the two operands of the subexpr...
2402 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2403 Op1I->setOperand(0, IIOp1);
2404 Op1I->setOperand(1, IIOp0);
2405
2406 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002407 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002408 }
2409
2410 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2411 //
2412 if (Op1I->getOpcode() == Instruction::And &&
2413 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2414 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2415
2416 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00002417 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2418 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002419 }
2420
2421 // 0 - (X sdiv C) -> (X sdiv -C)
2422 if (Op1I->getOpcode() == Instruction::SDiv)
2423 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2424 if (CSI->isZero())
2425 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002426 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002427 ConstantExpr::getNeg(DivRHS));
2428
2429 // X - X*C --> X * (1-C)
2430 ConstantInt *C2 = 0;
2431 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2432 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002433 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002434 }
2435 }
2436 }
2437
2438 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002439 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002440 if (Op0I->getOpcode() == Instruction::Add) {
2441 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2442 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2443 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2444 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2445 } else if (Op0I->getOpcode() == Instruction::Sub) {
2446 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002447 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002448 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002449 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002450
2451 ConstantInt *C1;
2452 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2453 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002454 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002455
2456 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2457 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greifa645dd32008-05-16 19:29:10 +00002458 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002459 }
2460 return 0;
2461}
2462
2463/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2464/// comparison only checks the sign bit. If it only checks the sign bit, set
2465/// TrueIfSigned if the result of the comparison is true when the input value is
2466/// signed.
2467static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2468 bool &TrueIfSigned) {
2469 switch (pred) {
2470 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2471 TrueIfSigned = true;
2472 return RHS->isZero();
2473 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2474 TrueIfSigned = true;
2475 return RHS->isAllOnesValue();
2476 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2477 TrueIfSigned = false;
2478 return RHS->isAllOnesValue();
2479 case ICmpInst::ICMP_UGT:
2480 // True if LHS u> RHS and RHS == high-bit-mask - 1
2481 TrueIfSigned = true;
2482 return RHS->getValue() ==
2483 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2484 case ICmpInst::ICMP_UGE:
2485 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2486 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002487 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002488 default:
2489 return false;
2490 }
2491}
2492
2493Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2494 bool Changed = SimplifyCommutative(I);
2495 Value *Op0 = I.getOperand(0);
2496
2497 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2498 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2499
2500 // Simplify mul instructions with a constant RHS...
2501 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2502 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2503
2504 // ((X << C1)*C2) == (X * (C2 << C1))
2505 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2506 if (SI->getOpcode() == Instruction::Shl)
2507 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002508 return BinaryOperator::CreateMul(SI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002509 ConstantExpr::getShl(CI, ShOp));
2510
2511 if (CI->isZero())
2512 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2513 if (CI->equalsInt(1)) // X * 1 == X
2514 return ReplaceInstUsesWith(I, Op0);
2515 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002516 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002517
2518 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2519 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002520 return BinaryOperator::CreateShl(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002521 ConstantInt::get(Op0->getType(), Val.logBase2()));
2522 }
2523 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2524 if (Op1F->isNullValue())
2525 return ReplaceInstUsesWith(I, Op1);
2526
2527 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2528 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattner6297fc72008-08-11 22:06:05 +00002529 if (Op1F->isExactlyValue(1.0))
2530 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2531 } else if (isa<VectorType>(Op1->getType())) {
2532 if (isa<ConstantAggregateZero>(Op1))
2533 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky94418732008-11-27 20:21:08 +00002534
2535 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2536 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2537 return BinaryOperator::CreateNeg(Op0, I.getName());
2538
2539 // As above, vector X*splat(1.0) -> X in all defined cases.
2540 if (Constant *Splat = Op1V->getSplatValue()) {
2541 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2542 if (F->isExactlyValue(1.0))
2543 return ReplaceInstUsesWith(I, Op0);
2544 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2545 if (CI->equalsInt(1))
2546 return ReplaceInstUsesWith(I, Op0);
2547 }
2548 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002549 }
2550
2551 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2552 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002553 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002554 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002555 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002556 Op1, "tmp");
2557 InsertNewInstBefore(Add, I);
2558 Value *C1C2 = ConstantExpr::getMul(Op1,
2559 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002560 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002561
2562 }
2563
2564 // Try to fold constant mul into select arguments.
2565 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2566 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2567 return R;
2568
2569 if (isa<PHINode>(Op0))
2570 if (Instruction *NV = FoldOpIntoPhi(I))
2571 return NV;
2572 }
2573
2574 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2575 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002576 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002577
Nick Lewycky1c246402008-11-21 07:33:58 +00002578 // (X / Y) * Y = X - (X % Y)
2579 // (X / Y) * -Y = (X % Y) - X
2580 {
2581 Value *Op1 = I.getOperand(1);
2582 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2583 if (!BO ||
2584 (BO->getOpcode() != Instruction::UDiv &&
2585 BO->getOpcode() != Instruction::SDiv)) {
2586 Op1 = Op0;
2587 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2588 }
2589 Value *Neg = dyn_castNegVal(Op1);
2590 if (BO && BO->hasOneUse() &&
2591 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2592 (BO->getOpcode() == Instruction::UDiv ||
2593 BO->getOpcode() == Instruction::SDiv)) {
2594 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2595
2596 Instruction *Rem;
2597 if (BO->getOpcode() == Instruction::UDiv)
2598 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2599 else
2600 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2601
2602 InsertNewInstBefore(Rem, I);
2603 Rem->takeName(BO);
2604
2605 if (Op1BO == Op1)
2606 return BinaryOperator::CreateSub(Op0BO, Rem);
2607 else
2608 return BinaryOperator::CreateSub(Rem, Op0BO);
2609 }
2610 }
2611
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002612 if (I.getType() == Type::Int1Ty)
2613 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2614
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002615 // If one of the operands of the multiply is a cast from a boolean value, then
2616 // we know the bool is either zero or one, so this is a 'masking' multiply.
2617 // See if we can simplify things based on how the boolean was originally
2618 // formed.
2619 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002620 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002621 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2622 BoolCast = CI;
2623 if (!BoolCast)
2624 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2625 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2626 BoolCast = CI;
2627 if (BoolCast) {
2628 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2629 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2630 const Type *SCOpTy = SCIOp0->getType();
2631 bool TIS = false;
2632
2633 // If the icmp is true iff the sign bit of X is set, then convert this
2634 // multiply into a shift/and combination.
2635 if (isa<ConstantInt>(SCIOp1) &&
2636 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2637 TIS) {
2638 // Shift the X value right to turn it into "all signbits".
2639 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2640 SCOpTy->getPrimitiveSizeInBits()-1);
2641 Value *V =
2642 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002643 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002644 BoolCast->getOperand(0)->getName()+
2645 ".mask"), I);
2646
2647 // If the multiply type is not the same as the source type, sign extend
2648 // or truncate to the multiply type.
2649 if (I.getType() != V->getType()) {
2650 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2651 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2652 Instruction::CastOps opcode =
2653 (SrcBits == DstBits ? Instruction::BitCast :
2654 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2655 V = InsertCastBefore(opcode, V, I.getType(), I);
2656 }
2657
2658 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002659 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002660 }
2661 }
2662 }
2663
2664 return Changed ? &I : 0;
2665}
2666
Chris Lattner76972db2008-07-14 00:15:52 +00002667/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2668/// instruction.
2669bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2670 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2671
2672 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2673 int NonNullOperand = -1;
2674 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2675 if (ST->isNullValue())
2676 NonNullOperand = 2;
2677 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2678 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2679 if (ST->isNullValue())
2680 NonNullOperand = 1;
2681
2682 if (NonNullOperand == -1)
2683 return false;
2684
2685 Value *SelectCond = SI->getOperand(0);
2686
2687 // Change the div/rem to use 'Y' instead of the select.
2688 I.setOperand(1, SI->getOperand(NonNullOperand));
2689
2690 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2691 // problem. However, the select, or the condition of the select may have
2692 // multiple uses. Based on our knowledge that the operand must be non-zero,
2693 // propagate the known value for the select into other uses of it, and
2694 // propagate a known value of the condition into its other users.
2695
2696 // If the select and condition only have a single use, don't bother with this,
2697 // early exit.
2698 if (SI->use_empty() && SelectCond->hasOneUse())
2699 return true;
2700
2701 // Scan the current block backward, looking for other uses of SI.
2702 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2703
2704 while (BBI != BBFront) {
2705 --BBI;
2706 // If we found a call to a function, we can't assume it will return, so
2707 // information from below it cannot be propagated above it.
2708 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2709 break;
2710
2711 // Replace uses of the select or its condition with the known values.
2712 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2713 I != E; ++I) {
2714 if (*I == SI) {
2715 *I = SI->getOperand(NonNullOperand);
2716 AddToWorkList(BBI);
2717 } else if (*I == SelectCond) {
2718 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2719 ConstantInt::getFalse();
2720 AddToWorkList(BBI);
2721 }
2722 }
2723
2724 // If we past the instruction, quit looking for it.
2725 if (&*BBI == SI)
2726 SI = 0;
2727 if (&*BBI == SelectCond)
2728 SelectCond = 0;
2729
2730 // If we ran out of things to eliminate, break out of the loop.
2731 if (SelectCond == 0 && SI == 0)
2732 break;
2733
2734 }
2735 return true;
2736}
2737
2738
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002739/// This function implements the transforms on div instructions that work
2740/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2741/// used by the visitors to those instructions.
2742/// @brief Transforms common to all three div instructions
2743Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2744 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2745
Chris Lattner653ef3c2008-02-19 06:12:18 +00002746 // undef / X -> 0 for integer.
2747 // undef / X -> undef for FP (the undef could be a snan).
2748 if (isa<UndefValue>(Op0)) {
2749 if (Op0->getType()->isFPOrFPVector())
2750 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002751 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002752 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002753
2754 // X / undef -> undef
2755 if (isa<UndefValue>(Op1))
2756 return ReplaceInstUsesWith(I, Op1);
2757
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002758 return 0;
2759}
2760
2761/// This function implements the transforms common to both integer division
2762/// instructions (udiv and sdiv). It is called by the visitors to those integer
2763/// division instructions.
2764/// @brief Common integer divide transforms
2765Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2766 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2767
Chris Lattnercefb36c2008-05-16 02:59:42 +00002768 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002769 if (Op0 == Op1) {
2770 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2771 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2772 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2773 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2774 }
2775
2776 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2777 return ReplaceInstUsesWith(I, CI);
2778 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002779
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002780 if (Instruction *Common = commonDivTransforms(I))
2781 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002782
2783 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2784 // This does not apply for fdiv.
2785 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2786 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002787
2788 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2789 // div X, 1 == X
2790 if (RHS->equalsInt(1))
2791 return ReplaceInstUsesWith(I, Op0);
2792
2793 // (X / C1) / C2 -> X / (C1*C2)
2794 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2795 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2796 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00002797 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2798 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2799 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002800 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewycky9d798f92008-02-18 22:48:05 +00002801 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002802 }
2803
2804 if (!RHS->isZero()) { // avoid X udiv 0
2805 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2806 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2807 return R;
2808 if (isa<PHINode>(Op0))
2809 if (Instruction *NV = FoldOpIntoPhi(I))
2810 return NV;
2811 }
2812 }
2813
2814 // 0 / X == 0, we don't need to preserve faults!
2815 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2816 if (LHS->equalsInt(0))
2817 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2818
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002819 // It can't be division by zero, hence it must be division by one.
2820 if (I.getType() == Type::Int1Ty)
2821 return ReplaceInstUsesWith(I, Op0);
2822
Nick Lewycky94418732008-11-27 20:21:08 +00002823 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2824 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2825 // div X, 1 == X
2826 if (X->isOne())
2827 return ReplaceInstUsesWith(I, Op0);
2828 }
2829
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002830 return 0;
2831}
2832
2833Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2834 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2835
2836 // Handle the integer div common cases
2837 if (Instruction *Common = commonIDivTransforms(I))
2838 return Common;
2839
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002840 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00002841 // X udiv C^2 -> X >> C
2842 // Check to see if this is an unsigned division with an exact power of 2,
2843 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002844 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00002845 return BinaryOperator::CreateLShr(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002846 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00002847
2848 // X udiv C, where C >= signbit
2849 if (C->getValue().isNegative()) {
2850 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2851 I);
2852 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2853 ConstantInt::get(I.getType(), 1));
2854 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002855 }
2856
2857 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2858 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2859 if (RHSI->getOpcode() == Instruction::Shl &&
2860 isa<ConstantInt>(RHSI->getOperand(0))) {
2861 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2862 if (C1.isPowerOf2()) {
2863 Value *N = RHSI->getOperand(1);
2864 const Type *NTy = N->getType();
2865 if (uint32_t C2 = C1.logBase2()) {
2866 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002867 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002868 }
Gabor Greifa645dd32008-05-16 19:29:10 +00002869 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002870 }
2871 }
2872 }
2873
2874 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2875 // where C1&C2 are powers of two.
2876 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2877 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2878 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2879 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2880 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2881 // Compute the shift amounts
2882 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2883 // Construct the "on true" case of the select
2884 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002885 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886 Op0, TC, SI->getName()+".t");
2887 TSI = InsertNewInstBefore(TSI, I);
2888
2889 // Construct the "on false" case of the select
2890 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002891 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002892 Op0, FC, SI->getName()+".f");
2893 FSI = InsertNewInstBefore(FSI, I);
2894
2895 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002896 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002897 }
2898 }
2899 return 0;
2900}
2901
2902Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2903 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2904
2905 // Handle the integer div common cases
2906 if (Instruction *Common = commonIDivTransforms(I))
2907 return Common;
2908
2909 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2910 // sdiv X, -1 == -X
2911 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002912 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002913 }
2914
2915 // If the sign bits of both operands are zero (i.e. we can prove they are
2916 // unsigned inputs), turn this into a udiv.
2917 if (I.getType()->isInteger()) {
2918 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2919 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00002920 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00002921 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002922 }
2923 }
2924
2925 return 0;
2926}
2927
2928Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2929 return commonDivTransforms(I);
2930}
2931
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002932/// This function implements the transforms on rem instructions that work
2933/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2934/// is used by the visitors to those instructions.
2935/// @brief Transforms common to all three rem instructions
2936Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2937 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2938
Chris Lattner653ef3c2008-02-19 06:12:18 +00002939 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2940 if (I.getType()->isFPOrFPVector())
2941 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002942 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002943 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002944 if (isa<UndefValue>(Op1))
2945 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2946
2947 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00002948 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2949 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002950
2951 return 0;
2952}
2953
2954/// This function implements the transforms common to both integer remainder
2955/// instructions (urem and srem). It is called by the visitors to those integer
2956/// remainder instructions.
2957/// @brief Common integer remainder transforms
2958Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2959 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2960
2961 if (Instruction *common = commonRemTransforms(I))
2962 return common;
2963
Dale Johannesena51f7372009-01-21 00:35:19 +00002964 // 0 % X == 0 for integer, we don't need to preserve faults!
2965 if (Constant *LHS = dyn_cast<Constant>(Op0))
2966 if (LHS->isNullValue())
2967 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2968
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002969 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2970 // X % 0 == undef, we don't need to preserve faults!
2971 if (RHS->equalsInt(0))
2972 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2973
2974 if (RHS->equalsInt(1)) // X % 1 == 0
2975 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2976
2977 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2978 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2979 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2980 return R;
2981 } else if (isa<PHINode>(Op0I)) {
2982 if (Instruction *NV = FoldOpIntoPhi(I))
2983 return NV;
2984 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00002985
2986 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00002987 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00002988 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002989 }
2990 }
2991
2992 return 0;
2993}
2994
2995Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2996 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2997
2998 if (Instruction *common = commonIRemTransforms(I))
2999 return common;
3000
3001 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3002 // X urem C^2 -> X and C
3003 // Check to see if this is an unsigned remainder with an exact power of 2,
3004 // if so, convert to a bitwise and.
3005 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3006 if (C->getValue().isPowerOf2())
Gabor Greifa645dd32008-05-16 19:29:10 +00003007 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003008 }
3009
3010 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3011 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3012 if (RHSI->getOpcode() == Instruction::Shl &&
3013 isa<ConstantInt>(RHSI->getOperand(0))) {
3014 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3015 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003016 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003017 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003018 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003019 }
3020 }
3021 }
3022
3023 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and 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 // STO == 0 and SFO == 0 handled above.
3029 if ((STO->getValue().isPowerOf2()) &&
3030 (SFO->getValue().isPowerOf2())) {
3031 Value *TrueAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003032 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003033 Value *FalseAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003034 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003035 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003036 }
3037 }
3038 }
3039
3040 return 0;
3041}
3042
3043Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3044 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3045
Dan Gohmandb3dd962007-11-05 23:16:33 +00003046 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003047 if (Instruction *common = commonIRemTransforms(I))
3048 return common;
3049
3050 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003051 if (!isa<Constant>(RHSNeg) ||
3052 (isa<ConstantInt>(RHSNeg) &&
3053 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003054 // X % -Y -> X % Y
3055 AddUsesToWorkList(I);
3056 I.setOperand(1, RHSNeg);
3057 return &I;
3058 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003059
Dan Gohmandb3dd962007-11-05 23:16:33 +00003060 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003061 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003062 if (I.getType()->isInteger()) {
3063 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3064 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3065 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003066 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003067 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003068 }
3069
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003070 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003071 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3072 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003073
Nick Lewyckyfd746832008-12-20 16:48:00 +00003074 bool hasNegative = false;
3075 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3076 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3077 if (RHS->getValue().isNegative())
3078 hasNegative = true;
3079
3080 if (hasNegative) {
3081 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003082 for (unsigned i = 0; i != VWidth; ++i) {
3083 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3084 if (RHS->getValue().isNegative())
3085 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3086 else
3087 Elts[i] = RHS;
3088 }
3089 }
3090
3091 Constant *NewRHSV = ConstantVector::get(Elts);
3092 if (NewRHSV != RHSV) {
Nick Lewycky338ecd52008-12-18 06:42:28 +00003093 AddUsesToWorkList(I);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003094 I.setOperand(1, NewRHSV);
3095 return &I;
3096 }
3097 }
3098 }
3099
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003100 return 0;
3101}
3102
3103Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3104 return commonRemTransforms(I);
3105}
3106
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003107// isOneBitSet - Return true if there is exactly one bit set in the specified
3108// constant.
3109static bool isOneBitSet(const ConstantInt *CI) {
3110 return CI->getValue().isPowerOf2();
3111}
3112
3113// isHighOnes - Return true if the constant is of the form 1+0+.
3114// This is the same as lowones(~X).
3115static bool isHighOnes(const ConstantInt *CI) {
3116 return (~CI->getValue() + 1).isPowerOf2();
3117}
3118
3119/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3120/// are carefully arranged to allow folding of expressions such as:
3121///
3122/// (A < B) | (A > B) --> (A != B)
3123///
3124/// Note that this is only valid if the first and second predicates have the
3125/// same sign. Is illegal to do: (A u< B) | (A s> B)
3126///
3127/// Three bits are used to represent the condition, as follows:
3128/// 0 A > B
3129/// 1 A == B
3130/// 2 A < B
3131///
3132/// <=> Value Definition
3133/// 000 0 Always false
3134/// 001 1 A > B
3135/// 010 2 A == B
3136/// 011 3 A >= B
3137/// 100 4 A < B
3138/// 101 5 A != B
3139/// 110 6 A <= B
3140/// 111 7 Always true
3141///
3142static unsigned getICmpCode(const ICmpInst *ICI) {
3143 switch (ICI->getPredicate()) {
3144 // False -> 0
3145 case ICmpInst::ICMP_UGT: return 1; // 001
3146 case ICmpInst::ICMP_SGT: return 1; // 001
3147 case ICmpInst::ICMP_EQ: return 2; // 010
3148 case ICmpInst::ICMP_UGE: return 3; // 011
3149 case ICmpInst::ICMP_SGE: return 3; // 011
3150 case ICmpInst::ICMP_ULT: return 4; // 100
3151 case ICmpInst::ICMP_SLT: return 4; // 100
3152 case ICmpInst::ICMP_NE: return 5; // 101
3153 case ICmpInst::ICMP_ULE: return 6; // 110
3154 case ICmpInst::ICMP_SLE: return 6; // 110
3155 // True -> 7
3156 default:
3157 assert(0 && "Invalid ICmp predicate!");
3158 return 0;
3159 }
3160}
3161
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003162/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3163/// predicate into a three bit mask. It also returns whether it is an ordered
3164/// predicate by reference.
3165static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3166 isOrdered = false;
3167 switch (CC) {
3168 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3169 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003170 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3171 case FCmpInst::FCMP_UGT: return 1; // 001
3172 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3173 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003174 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3175 case FCmpInst::FCMP_UGE: return 3; // 011
3176 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3177 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003178 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3179 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003180 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3181 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003182 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003183 default:
3184 // Not expecting FCMP_FALSE and FCMP_TRUE;
3185 assert(0 && "Unexpected FCmp predicate!");
3186 return 0;
3187 }
3188}
3189
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003190/// getICmpValue - This is the complement of getICmpCode, which turns an
3191/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003192/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003193/// of predicate to use in the new icmp instruction.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003194static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3195 switch (code) {
3196 default: assert(0 && "Illegal ICmp code!");
3197 case 0: return ConstantInt::getFalse();
3198 case 1:
3199 if (sign)
3200 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3201 else
3202 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3203 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3204 case 3:
3205 if (sign)
3206 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3207 else
3208 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3209 case 4:
3210 if (sign)
3211 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3212 else
3213 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3214 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3215 case 6:
3216 if (sign)
3217 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3218 else
3219 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3220 case 7: return ConstantInt::getTrue();
3221 }
3222}
3223
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003224/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3225/// opcode and two operands into either a FCmp instruction. isordered is passed
3226/// in to determine which kind of predicate to use in the new fcmp instruction.
3227static Value *getFCmpValue(bool isordered, unsigned code,
3228 Value *LHS, Value *RHS) {
3229 switch (code) {
Evan Chengf1f2cea2008-10-14 18:13:38 +00003230 default: assert(0 && "Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003231 case 0:
3232 if (isordered)
3233 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3234 else
3235 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3236 case 1:
3237 if (isordered)
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003238 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3239 else
3240 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003241 case 2:
3242 if (isordered)
3243 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3244 else
3245 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003246 case 3:
3247 if (isordered)
3248 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3249 else
3250 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3251 case 4:
3252 if (isordered)
3253 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3254 else
3255 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3256 case 5:
3257 if (isordered)
Evan Chengf1f2cea2008-10-14 18:13:38 +00003258 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3259 else
3260 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3261 case 6:
3262 if (isordered)
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003263 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3264 else
3265 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng72988052008-10-14 18:44:08 +00003266 case 7: return ConstantInt::getTrue();
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003267 }
3268}
3269
Chris Lattner2972b822008-11-16 04:55:20 +00003270/// PredicatesFoldable - Return true if both predicates match sign or if at
3271/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003272static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3273 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattner2972b822008-11-16 04:55:20 +00003274 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3275 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003276}
3277
3278namespace {
3279// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3280struct FoldICmpLogical {
3281 InstCombiner &IC;
3282 Value *LHS, *RHS;
3283 ICmpInst::Predicate pred;
3284 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3285 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3286 pred(ICI->getPredicate()) {}
3287 bool shouldApply(Value *V) const {
3288 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3289 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003290 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3291 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003292 return false;
3293 }
3294 Instruction *apply(Instruction &Log) const {
3295 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3296 if (ICI->getOperand(0) != LHS) {
3297 assert(ICI->getOperand(1) == LHS);
3298 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3299 }
3300
3301 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3302 unsigned LHSCode = getICmpCode(ICI);
3303 unsigned RHSCode = getICmpCode(RHSICI);
3304 unsigned Code;
3305 switch (Log.getOpcode()) {
3306 case Instruction::And: Code = LHSCode & RHSCode; break;
3307 case Instruction::Or: Code = LHSCode | RHSCode; break;
3308 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3309 default: assert(0 && "Illegal logical opcode!"); return 0;
3310 }
3311
3312 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3313 ICmpInst::isSignedPredicate(ICI->getPredicate());
3314
3315 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3316 if (Instruction *I = dyn_cast<Instruction>(RV))
3317 return I;
3318 // Otherwise, it's a constant boolean value...
3319 return IC.ReplaceInstUsesWith(Log, RV);
3320 }
3321};
3322} // end anonymous namespace
3323
3324// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3325// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3326// guaranteed to be a binary operator.
3327Instruction *InstCombiner::OptAndOp(Instruction *Op,
3328 ConstantInt *OpRHS,
3329 ConstantInt *AndRHS,
3330 BinaryOperator &TheAnd) {
3331 Value *X = Op->getOperand(0);
3332 Constant *Together = 0;
3333 if (!Op->isShift())
3334 Together = And(AndRHS, OpRHS);
3335
3336 switch (Op->getOpcode()) {
3337 case Instruction::Xor:
3338 if (Op->hasOneUse()) {
3339 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003340 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003341 InsertNewInstBefore(And, TheAnd);
3342 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003343 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003344 }
3345 break;
3346 case Instruction::Or:
3347 if (Together == AndRHS) // (X | C) & C --> C
3348 return ReplaceInstUsesWith(TheAnd, AndRHS);
3349
3350 if (Op->hasOneUse() && Together != OpRHS) {
3351 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003352 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003353 InsertNewInstBefore(Or, TheAnd);
3354 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003355 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003356 }
3357 break;
3358 case Instruction::Add:
3359 if (Op->hasOneUse()) {
3360 // Adding a one to a single bit bit-field should be turned into an XOR
3361 // of the bit. First thing to check is to see if this AND is with a
3362 // single bit constant.
3363 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3364
3365 // If there is only one bit set...
3366 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3367 // Ok, at this point, we know that we are masking the result of the
3368 // ADD down to exactly one bit. If the constant we are adding has
3369 // no bits set below this bit, then we can eliminate the ADD.
3370 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3371
3372 // Check to see if any bits below the one bit set in AndRHSV are set.
3373 if ((AddRHS & (AndRHSV-1)) == 0) {
3374 // If not, the only thing that can effect the output of the AND is
3375 // the bit specified by AndRHSV. If that bit is set, the effect of
3376 // the XOR is to toggle the bit. If it is clear, then the ADD has
3377 // no effect.
3378 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3379 TheAnd.setOperand(0, X);
3380 return &TheAnd;
3381 } else {
3382 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003383 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003384 InsertNewInstBefore(NewAnd, TheAnd);
3385 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003386 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003387 }
3388 }
3389 }
3390 }
3391 break;
3392
3393 case Instruction::Shl: {
3394 // We know that the AND will not produce any of the bits shifted in, so if
3395 // the anded constant includes them, clear them now!
3396 //
3397 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3398 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3399 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3400 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3401
3402 if (CI->getValue() == ShlMask) {
3403 // Masking out bits that the shift already masks
3404 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3405 } else if (CI != AndRHS) { // Reducing bits set in and.
3406 TheAnd.setOperand(1, CI);
3407 return &TheAnd;
3408 }
3409 break;
3410 }
3411 case Instruction::LShr:
3412 {
3413 // We know that the AND will not produce any of the bits shifted in, so if
3414 // the anded constant includes them, clear them now! This only applies to
3415 // unsigned shifts, because a signed shr may bring in set bits!
3416 //
3417 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3418 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3419 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3420 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3421
3422 if (CI->getValue() == ShrMask) {
3423 // Masking out bits that the shift already masks.
3424 return ReplaceInstUsesWith(TheAnd, Op);
3425 } else if (CI != AndRHS) {
3426 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3427 return &TheAnd;
3428 }
3429 break;
3430 }
3431 case Instruction::AShr:
3432 // Signed shr.
3433 // See if this is shifting in some sign extension, then masking it out
3434 // with an and.
3435 if (Op->hasOneUse()) {
3436 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3437 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3438 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3439 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3440 if (C == AndRHS) { // Masking out bits shifted in.
3441 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3442 // Make the argument unsigned.
3443 Value *ShVal = Op->getOperand(0);
3444 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003445 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003446 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003447 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003448 }
3449 }
3450 break;
3451 }
3452 return 0;
3453}
3454
3455
3456/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3457/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3458/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3459/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3460/// insert new instructions.
3461Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3462 bool isSigned, bool Inside,
3463 Instruction &IB) {
3464 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3465 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3466 "Lo is not <= Hi in range emission code!");
3467
3468 if (Inside) {
3469 if (Lo == Hi) // Trivially false.
3470 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3471
3472 // V >= Min && V < Hi --> V < Hi
3473 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3474 ICmpInst::Predicate pred = (isSigned ?
3475 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3476 return new ICmpInst(pred, V, Hi);
3477 }
3478
3479 // Emit V-Lo <u Hi-Lo
3480 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003481 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003482 InsertNewInstBefore(Add, IB);
3483 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3484 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3485 }
3486
3487 if (Lo == Hi) // Trivially true.
3488 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3489
3490 // V < Min || V >= Hi -> V > Hi-1
3491 Hi = SubOne(cast<ConstantInt>(Hi));
3492 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3493 ICmpInst::Predicate pred = (isSigned ?
3494 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3495 return new ICmpInst(pred, V, Hi);
3496 }
3497
3498 // Emit V-Lo >u Hi-1-Lo
3499 // Note that Hi has already had one subtracted from it, above.
3500 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003501 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003502 InsertNewInstBefore(Add, IB);
3503 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3504 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3505}
3506
3507// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3508// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3509// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3510// not, since all 1s are not contiguous.
3511static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3512 const APInt& V = Val->getValue();
3513 uint32_t BitWidth = Val->getType()->getBitWidth();
3514 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3515
3516 // look for the first zero bit after the run of ones
3517 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3518 // look for the first non-zero bit
3519 ME = V.getActiveBits();
3520 return true;
3521}
3522
3523/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3524/// where isSub determines whether the operator is a sub. If we can fold one of
3525/// the following xforms:
3526///
3527/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3528/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3529/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3530///
3531/// return (A +/- B).
3532///
3533Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3534 ConstantInt *Mask, bool isSub,
3535 Instruction &I) {
3536 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3537 if (!LHSI || LHSI->getNumOperands() != 2 ||
3538 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3539
3540 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3541
3542 switch (LHSI->getOpcode()) {
3543 default: return 0;
3544 case Instruction::And:
3545 if (And(N, Mask) == Mask) {
3546 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3547 if ((Mask->getValue().countLeadingZeros() +
3548 Mask->getValue().countPopulation()) ==
3549 Mask->getValue().getBitWidth())
3550 break;
3551
3552 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3553 // part, we don't need any explicit masks to take them out of A. If that
3554 // is all N is, ignore it.
3555 uint32_t MB = 0, ME = 0;
3556 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3557 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3558 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3559 if (MaskedValueIsZero(RHS, Mask))
3560 break;
3561 }
3562 }
3563 return 0;
3564 case Instruction::Or:
3565 case Instruction::Xor:
3566 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3567 if ((Mask->getValue().countLeadingZeros() +
3568 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3569 && And(N, Mask)->isZero())
3570 break;
3571 return 0;
3572 }
3573
3574 Instruction *New;
3575 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003576 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003577 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003578 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003579 return InsertNewInstBefore(New, I);
3580}
3581
Chris Lattner0631ea72008-11-16 05:06:21 +00003582/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3583Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3584 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00003585 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00003586 ConstantInt *LHSCst, *RHSCst;
3587 ICmpInst::Predicate LHSCC, RHSCC;
3588
Chris Lattnerf3803482008-11-16 05:10:52 +00003589 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner0631ea72008-11-16 05:06:21 +00003590 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerf3803482008-11-16 05:10:52 +00003591 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00003592 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003593
3594 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3595 // where C is a power of 2
3596 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3597 LHSCst->getValue().isPowerOf2()) {
3598 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3599 InsertNewInstBefore(NewOr, I);
3600 return new ICmpInst(LHSCC, NewOr, LHSCst);
3601 }
3602
3603 // From here on, we only handle:
3604 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3605 if (Val != Val2) return 0;
3606
Chris Lattner0631ea72008-11-16 05:06:21 +00003607 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3608 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3609 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3610 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3611 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3612 return 0;
3613
3614 // We can't fold (ugt x, C) & (sgt x, C2).
3615 if (!PredicatesFoldable(LHSCC, RHSCC))
3616 return 0;
3617
3618 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003619 bool ShouldSwap;
Chris Lattner0631ea72008-11-16 05:06:21 +00003620 if (ICmpInst::isSignedPredicate(LHSCC) ||
3621 (ICmpInst::isEquality(LHSCC) &&
3622 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003623 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003624 else
Chris Lattner665298f2008-11-16 05:14:43 +00003625 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3626
3627 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003628 std::swap(LHS, RHS);
3629 std::swap(LHSCst, RHSCst);
3630 std::swap(LHSCC, RHSCC);
3631 }
3632
3633 // At this point, we know we have have two icmp instructions
3634 // comparing a value against two constants and and'ing the result
3635 // together. Because of the above check, we know that we only have
3636 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3637 // (from the FoldICmpLogical check above), that the two constants
3638 // are not equal and that the larger constant is on the RHS
3639 assert(LHSCst != RHSCst && "Compares not folded above?");
3640
3641 switch (LHSCC) {
3642 default: assert(0 && "Unknown integer condition code!");
3643 case ICmpInst::ICMP_EQ:
3644 switch (RHSCC) {
3645 default: assert(0 && "Unknown integer condition code!");
3646 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3647 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3648 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3649 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3650 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3651 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3652 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3653 return ReplaceInstUsesWith(I, LHS);
3654 }
3655 case ICmpInst::ICMP_NE:
3656 switch (RHSCC) {
3657 default: assert(0 && "Unknown integer condition code!");
3658 case ICmpInst::ICMP_ULT:
3659 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3660 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3661 break; // (X != 13 & X u< 15) -> no change
3662 case ICmpInst::ICMP_SLT:
3663 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3664 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3665 break; // (X != 13 & X s< 15) -> no change
3666 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3667 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3668 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3669 return ReplaceInstUsesWith(I, RHS);
3670 case ICmpInst::ICMP_NE:
3671 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3672 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3673 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3674 Val->getName()+".off");
3675 InsertNewInstBefore(Add, I);
3676 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3677 ConstantInt::get(Add->getType(), 1));
3678 }
3679 break; // (X != 13 & X != 15) -> no change
3680 }
3681 break;
3682 case ICmpInst::ICMP_ULT:
3683 switch (RHSCC) {
3684 default: assert(0 && "Unknown integer condition code!");
3685 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3686 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3687 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3688 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3689 break;
3690 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3691 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3692 return ReplaceInstUsesWith(I, LHS);
3693 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3694 break;
3695 }
3696 break;
3697 case ICmpInst::ICMP_SLT:
3698 switch (RHSCC) {
3699 default: assert(0 && "Unknown integer condition code!");
3700 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3701 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3702 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3703 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3704 break;
3705 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3706 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3707 return ReplaceInstUsesWith(I, LHS);
3708 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3709 break;
3710 }
3711 break;
3712 case ICmpInst::ICMP_UGT:
3713 switch (RHSCC) {
3714 default: assert(0 && "Unknown integer condition code!");
3715 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3716 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3717 return ReplaceInstUsesWith(I, RHS);
3718 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3719 break;
3720 case ICmpInst::ICMP_NE:
3721 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3722 return new ICmpInst(LHSCC, Val, RHSCst);
3723 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003724 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner0631ea72008-11-16 05:06:21 +00003725 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3726 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3727 break;
3728 }
3729 break;
3730 case ICmpInst::ICMP_SGT:
3731 switch (RHSCC) {
3732 default: assert(0 && "Unknown integer condition code!");
3733 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3734 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3735 return ReplaceInstUsesWith(I, RHS);
3736 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3737 break;
3738 case ICmpInst::ICMP_NE:
3739 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3740 return new ICmpInst(LHSCC, Val, RHSCst);
3741 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003742 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner0631ea72008-11-16 05:06:21 +00003743 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3744 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3745 break;
3746 }
3747 break;
3748 }
Chris Lattner0631ea72008-11-16 05:06:21 +00003749
3750 return 0;
3751}
3752
3753
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003754Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3755 bool Changed = SimplifyCommutative(I);
3756 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3757
3758 if (isa<UndefValue>(Op1)) // X & undef -> 0
3759 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3760
3761 // and X, X = X
3762 if (Op0 == Op1)
3763 return ReplaceInstUsesWith(I, Op1);
3764
3765 // See if we can simplify any instructions used by the instruction whose sole
3766 // purpose is to compute bits we don't care about.
3767 if (!isa<VectorType>(I.getType())) {
Chris Lattner676c78e2009-01-31 08:15:18 +00003768 if (SimplifyDemandedInstructionBits(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003769 return &I;
3770 } else {
3771 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3772 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3773 return ReplaceInstUsesWith(I, I.getOperand(0));
3774 } else if (isa<ConstantAggregateZero>(Op1)) {
3775 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3776 }
3777 }
3778
3779 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3780 const APInt& AndRHSMask = AndRHS->getValue();
3781 APInt NotAndRHS(~AndRHSMask);
3782
3783 // Optimize a variety of ((val OP C1) & C2) combinations...
3784 if (isa<BinaryOperator>(Op0)) {
3785 Instruction *Op0I = cast<Instruction>(Op0);
3786 Value *Op0LHS = Op0I->getOperand(0);
3787 Value *Op0RHS = Op0I->getOperand(1);
3788 switch (Op0I->getOpcode()) {
3789 case Instruction::Xor:
3790 case Instruction::Or:
3791 // If the mask is only needed on one incoming arm, push it up.
3792 if (Op0I->hasOneUse()) {
3793 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3794 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003795 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003796 Op0RHS->getName()+".masked");
3797 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003798 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003799 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3800 }
3801 if (!isa<Constant>(Op0RHS) &&
3802 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3803 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003804 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003805 Op0LHS->getName()+".masked");
3806 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003807 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003808 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3809 }
3810 }
3811
3812 break;
3813 case Instruction::Add:
3814 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3815 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3816 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3817 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003818 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003819 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003820 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003821 break;
3822
3823 case Instruction::Sub:
3824 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3825 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3826 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3827 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003828 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003829
Nick Lewyckya349ba42008-07-10 05:51:40 +00003830 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3831 // has 1's for all bits that the subtraction with A might affect.
3832 if (Op0I->hasOneUse()) {
3833 uint32_t BitWidth = AndRHSMask.getBitWidth();
3834 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3835 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3836
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003837 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00003838 if (!(A && A->isZero()) && // avoid infinite recursion.
3839 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003840 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3841 InsertNewInstBefore(NewNeg, I);
3842 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3843 }
3844 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003845 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00003846
3847 case Instruction::Shl:
3848 case Instruction::LShr:
3849 // (1 << x) & 1 --> zext(x == 0)
3850 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00003851 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewycky659ed4d2008-07-09 05:20:13 +00003852 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3853 Constant::getNullValue(I.getType()));
3854 InsertNewInstBefore(NewICmp, I);
3855 return new ZExtInst(NewICmp, I.getType());
3856 }
3857 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003858 }
3859
3860 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3861 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3862 return Res;
3863 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3864 // If this is an integer truncation or change from signed-to-unsigned, and
3865 // if the source is an and/or with immediate, transform it. This
3866 // frequently occurs for bitfield accesses.
3867 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3868 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3869 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003870 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003871 if (CastOp->getOpcode() == Instruction::And) {
3872 // Change: and (cast (and X, C1) to T), C2
3873 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3874 // This will fold the two constants together, which may allow
3875 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00003876 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003877 CastOp->getOperand(0), I.getType(),
3878 CastOp->getName()+".shrunk");
3879 NewCast = InsertNewInstBefore(NewCast, I);
3880 // trunc_or_bitcast(C1)&C2
3881 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3882 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00003883 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003884 } else if (CastOp->getOpcode() == Instruction::Or) {
3885 // Change: and (cast (or X, C1) to T), C2
3886 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3887 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3888 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3889 return ReplaceInstUsesWith(I, AndRHS);
3890 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003891 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003892 }
3893 }
3894
3895 // Try to fold constant and into select arguments.
3896 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3897 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3898 return R;
3899 if (isa<PHINode>(Op0))
3900 if (Instruction *NV = FoldOpIntoPhi(I))
3901 return NV;
3902 }
3903
3904 Value *Op0NotVal = dyn_castNotVal(Op0);
3905 Value *Op1NotVal = dyn_castNotVal(Op1);
3906
3907 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3908 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3909
3910 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3911 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003912 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003913 I.getName()+".demorgan");
3914 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003915 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003916 }
3917
3918 {
3919 Value *A = 0, *B = 0, *C = 0, *D = 0;
3920 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3921 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3922 return ReplaceInstUsesWith(I, Op1);
3923
3924 // (A|B) & ~(A&B) -> A^B
3925 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3926 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003927 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003928 }
3929 }
3930
3931 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3932 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3933 return ReplaceInstUsesWith(I, Op0);
3934
3935 // ~(A&B) & (A|B) -> A^B
3936 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3937 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003938 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003939 }
3940 }
3941
3942 if (Op0->hasOneUse() &&
3943 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3944 if (A == Op1) { // (A^B)&A -> A&(A^B)
3945 I.swapOperands(); // Simplify below
3946 std::swap(Op0, Op1);
3947 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3948 cast<BinaryOperator>(Op0)->swapOperands();
3949 I.swapOperands(); // Simplify below
3950 std::swap(Op0, Op1);
3951 }
3952 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00003953
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003954 if (Op1->hasOneUse() &&
3955 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3956 if (B == Op0) { // B&(A^B) -> B&(B^A)
3957 cast<BinaryOperator>(Op1)->swapOperands();
3958 std::swap(A, B);
3959 }
3960 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00003961 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003962 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003963 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003964 }
3965 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00003966
3967 // (A&((~A)|B)) -> A&B
Chris Lattner9db479f2008-12-01 05:16:26 +00003968 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
3969 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
3970 return BinaryOperator::CreateAnd(A, Op1);
3971 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
3972 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
3973 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003974 }
3975
3976 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3977 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3978 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3979 return R;
3980
Chris Lattner0631ea72008-11-16 05:06:21 +00003981 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
3982 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
3983 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003984 }
3985
3986 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3987 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3988 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3989 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3990 const Type *SrcTy = Op0C->getOperand(0)->getType();
3991 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3992 // Only do this if the casts both really cause code to be generated.
3993 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3994 I.getType(), TD) &&
3995 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3996 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003997 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003998 Op1C->getOperand(0),
3999 I.getName());
4000 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004001 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004002 }
4003 }
4004
4005 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4006 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4007 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4008 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4009 SI0->getOperand(1) == SI1->getOperand(1) &&
4010 (SI0->hasOneUse() || SI1->hasOneUse())) {
4011 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004012 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004013 SI1->getOperand(0),
4014 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004015 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004016 SI1->getOperand(1));
4017 }
4018 }
4019
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004020 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004021 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4022 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4023 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004024 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4025 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner91882432007-10-24 05:38:08 +00004026 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4027 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4028 // If either of the constants are nans, then the whole thing returns
4029 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004030 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004031 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4032 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4033 RHS->getOperand(0));
4034 }
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004035 } else {
4036 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4037 FCmpInst::Predicate Op0CC, Op1CC;
4038 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4039 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Chengf1f2cea2008-10-14 18:13:38 +00004040 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4041 // Swap RHS operands to match LHS.
4042 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4043 std::swap(Op1LHS, Op1RHS);
4044 }
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004045 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4046 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4047 if (Op0CC == Op1CC)
4048 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4049 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4050 Op1CC == FCmpInst::FCMP_FALSE)
4051 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4052 else if (Op0CC == FCmpInst::FCMP_TRUE)
4053 return ReplaceInstUsesWith(I, Op1);
4054 else if (Op1CC == FCmpInst::FCMP_TRUE)
4055 return ReplaceInstUsesWith(I, Op0);
4056 bool Op0Ordered;
4057 bool Op1Ordered;
4058 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4059 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4060 if (Op1Pred == 0) {
4061 std::swap(Op0, Op1);
4062 std::swap(Op0Pred, Op1Pred);
4063 std::swap(Op0Ordered, Op1Ordered);
4064 }
4065 if (Op0Pred == 0) {
4066 // uno && ueq -> uno && (uno || eq) -> ueq
4067 // ord && olt -> ord && (ord && lt) -> olt
4068 if (Op0Ordered == Op1Ordered)
4069 return ReplaceInstUsesWith(I, Op1);
4070 // uno && oeq -> uno && (ord && eq) -> false
4071 // uno && ord -> false
4072 if (!Op0Ordered)
4073 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4074 // ord && ueq -> ord && (uno || eq) -> oeq
4075 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4076 Op0LHS, Op0RHS));
4077 }
4078 }
4079 }
4080 }
Chris Lattner91882432007-10-24 05:38:08 +00004081 }
4082 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004083
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004084 return Changed ? &I : 0;
4085}
4086
Chris Lattner567f5112008-10-05 02:13:19 +00004087/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4088/// capable of providing pieces of a bswap. The subexpression provides pieces
4089/// of a bswap if it is proven that each of the non-zero bytes in the output of
4090/// the expression came from the corresponding "byte swapped" byte in some other
4091/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4092/// we know that the expression deposits the low byte of %X into the high byte
4093/// of the bswap result and that all other bytes are zero. This expression is
4094/// accepted, the high byte of ByteValues is set to X to indicate a correct
4095/// match.
4096///
4097/// This function returns true if the match was unsuccessful and false if so.
4098/// On entry to the function the "OverallLeftShift" is a signed integer value
4099/// indicating the number of bytes that the subexpression is later shifted. For
4100/// example, if the expression is later right shifted by 16 bits, the
4101/// OverallLeftShift value would be -2 on entry. This is used to specify which
4102/// byte of ByteValues is actually being set.
4103///
4104/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4105/// byte is masked to zero by a user. For example, in (X & 255), X will be
4106/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4107/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4108/// always in the local (OverallLeftShift) coordinate space.
4109///
4110static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4111 SmallVector<Value*, 8> &ByteValues) {
4112 if (Instruction *I = dyn_cast<Instruction>(V)) {
4113 // If this is an or instruction, it may be an inner node of the bswap.
4114 if (I->getOpcode() == Instruction::Or) {
4115 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4116 ByteValues) ||
4117 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4118 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004119 }
Chris Lattner567f5112008-10-05 02:13:19 +00004120
4121 // If this is a logical shift by a constant multiple of 8, recurse with
4122 // OverallLeftShift and ByteMask adjusted.
4123 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4124 unsigned ShAmt =
4125 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4126 // Ensure the shift amount is defined and of a byte value.
4127 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4128 return true;
4129
4130 unsigned ByteShift = ShAmt >> 3;
4131 if (I->getOpcode() == Instruction::Shl) {
4132 // X << 2 -> collect(X, +2)
4133 OverallLeftShift += ByteShift;
4134 ByteMask >>= ByteShift;
4135 } else {
4136 // X >>u 2 -> collect(X, -2)
4137 OverallLeftShift -= ByteShift;
4138 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004139 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004140 }
4141
4142 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4143 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4144
4145 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4146 ByteValues);
4147 }
4148
4149 // If this is a logical 'and' with a mask that clears bytes, clear the
4150 // corresponding bytes in ByteMask.
4151 if (I->getOpcode() == Instruction::And &&
4152 isa<ConstantInt>(I->getOperand(1))) {
4153 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4154 unsigned NumBytes = ByteValues.size();
4155 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4156 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4157
4158 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4159 // If this byte is masked out by a later operation, we don't care what
4160 // the and mask is.
4161 if ((ByteMask & (1 << i)) == 0)
4162 continue;
4163
4164 // If the AndMask is all zeros for this byte, clear the bit.
4165 APInt MaskB = AndMask & Byte;
4166 if (MaskB == 0) {
4167 ByteMask &= ~(1U << i);
4168 continue;
4169 }
4170
4171 // If the AndMask is not all ones for this byte, it's not a bytezap.
4172 if (MaskB != Byte)
4173 return true;
4174
4175 // Otherwise, this byte is kept.
4176 }
4177
4178 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4179 ByteValues);
4180 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004181 }
4182
Chris Lattner567f5112008-10-05 02:13:19 +00004183 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4184 // the input value to the bswap. Some observations: 1) if more than one byte
4185 // is demanded from this input, then it could not be successfully assembled
4186 // into a byteswap. At least one of the two bytes would not be aligned with
4187 // their ultimate destination.
4188 if (!isPowerOf2_32(ByteMask)) return true;
4189 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004190
Chris Lattner567f5112008-10-05 02:13:19 +00004191 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4192 // is demanded, it needs to go into byte 0 of the result. This means that the
4193 // byte needs to be shifted until it lands in the right byte bucket. The
4194 // shift amount depends on the position: if the byte is coming from the high
4195 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4196 // low part, it must be shifted left.
4197 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4198 if (InputByteNo < ByteValues.size()/2) {
4199 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4200 return true;
4201 } else {
4202 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4203 return true;
4204 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004205
4206 // If the destination byte value is already defined, the values are or'd
4207 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004208 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004209 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004210 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004211 return false;
4212}
4213
4214/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4215/// If so, insert the new bswap intrinsic and return it.
4216Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4217 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004218 if (!ITy || ITy->getBitWidth() % 16 ||
4219 // ByteMask only allows up to 32-byte values.
4220 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004221 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4222
4223 /// ByteValues - For each byte of the result, we keep track of which value
4224 /// defines each byte.
4225 SmallVector<Value*, 8> ByteValues;
4226 ByteValues.resize(ITy->getBitWidth()/8);
4227
4228 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004229 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4230 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004231 return 0;
4232
4233 // Check to see if all of the bytes come from the same value.
4234 Value *V = ByteValues[0];
4235 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4236
4237 // Check to make sure that all of the bytes come from the same value.
4238 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4239 if (ByteValues[i] != V)
4240 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004241 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004242 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004243 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004244 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004245}
4246
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004247/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4248/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4249/// we can simplify this expression to "cond ? C : D or B".
4250static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4251 Value *C, Value *D) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004252 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004253 Value *Cond = 0;
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004254 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004255 return 0;
4256
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004257 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004258 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004259 return SelectInst::Create(Cond, C, B);
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004260 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004261 return SelectInst::Create(Cond, C, B);
4262 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004263 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004264 return SelectInst::Create(Cond, C, D);
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004265 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004266 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004267 return 0;
4268}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004269
Chris Lattner0c678e52008-11-16 05:20:07 +00004270/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4271Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4272 ICmpInst *LHS, ICmpInst *RHS) {
4273 Value *Val, *Val2;
4274 ConstantInt *LHSCst, *RHSCst;
4275 ICmpInst::Predicate LHSCC, RHSCC;
4276
4277 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4278 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4279 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4280 return 0;
4281
4282 // From here on, we only handle:
4283 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4284 if (Val != Val2) return 0;
4285
4286 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4287 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4288 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4289 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4290 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4291 return 0;
4292
4293 // We can't fold (ugt x, C) | (sgt x, C2).
4294 if (!PredicatesFoldable(LHSCC, RHSCC))
4295 return 0;
4296
4297 // Ensure that the larger constant is on the RHS.
4298 bool ShouldSwap;
4299 if (ICmpInst::isSignedPredicate(LHSCC) ||
4300 (ICmpInst::isEquality(LHSCC) &&
4301 ICmpInst::isSignedPredicate(RHSCC)))
4302 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4303 else
4304 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4305
4306 if (ShouldSwap) {
4307 std::swap(LHS, RHS);
4308 std::swap(LHSCst, RHSCst);
4309 std::swap(LHSCC, RHSCC);
4310 }
4311
4312 // At this point, we know we have have two icmp instructions
4313 // comparing a value against two constants and or'ing the result
4314 // together. Because of the above check, we know that we only have
4315 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4316 // FoldICmpLogical check above), that the two constants are not
4317 // equal.
4318 assert(LHSCst != RHSCst && "Compares not folded above?");
4319
4320 switch (LHSCC) {
4321 default: assert(0 && "Unknown integer condition code!");
4322 case ICmpInst::ICMP_EQ:
4323 switch (RHSCC) {
4324 default: assert(0 && "Unknown integer condition code!");
4325 case ICmpInst::ICMP_EQ:
4326 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4327 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4328 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4329 Val->getName()+".off");
4330 InsertNewInstBefore(Add, I);
4331 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4332 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4333 }
4334 break; // (X == 13 | X == 15) -> no change
4335 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4336 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4337 break;
4338 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4339 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4340 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4341 return ReplaceInstUsesWith(I, RHS);
4342 }
4343 break;
4344 case ICmpInst::ICMP_NE:
4345 switch (RHSCC) {
4346 default: assert(0 && "Unknown integer condition code!");
4347 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4348 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4349 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4350 return ReplaceInstUsesWith(I, LHS);
4351 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4352 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4353 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4354 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4355 }
4356 break;
4357 case ICmpInst::ICMP_ULT:
4358 switch (RHSCC) {
4359 default: assert(0 && "Unknown integer condition code!");
4360 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4361 break;
4362 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4363 // If RHSCst is [us]MAXINT, it is always false. Not handling
4364 // this can cause overflow.
4365 if (RHSCst->isMaxValue(false))
4366 return ReplaceInstUsesWith(I, LHS);
4367 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4368 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4369 break;
4370 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4371 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4372 return ReplaceInstUsesWith(I, RHS);
4373 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4374 break;
4375 }
4376 break;
4377 case ICmpInst::ICMP_SLT:
4378 switch (RHSCC) {
4379 default: assert(0 && "Unknown integer condition code!");
4380 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4381 break;
4382 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4383 // If RHSCst is [us]MAXINT, it is always false. Not handling
4384 // this can cause overflow.
4385 if (RHSCst->isMaxValue(true))
4386 return ReplaceInstUsesWith(I, LHS);
4387 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4388 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4389 break;
4390 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4391 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4392 return ReplaceInstUsesWith(I, RHS);
4393 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4394 break;
4395 }
4396 break;
4397 case ICmpInst::ICMP_UGT:
4398 switch (RHSCC) {
4399 default: assert(0 && "Unknown integer condition code!");
4400 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4401 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4402 return ReplaceInstUsesWith(I, LHS);
4403 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4404 break;
4405 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4406 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4407 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4408 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4409 break;
4410 }
4411 break;
4412 case ICmpInst::ICMP_SGT:
4413 switch (RHSCC) {
4414 default: assert(0 && "Unknown integer condition code!");
4415 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4416 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4417 return ReplaceInstUsesWith(I, LHS);
4418 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4419 break;
4420 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4421 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4422 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4423 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4424 break;
4425 }
4426 break;
4427 }
4428 return 0;
4429}
4430
Bill Wendlingdae376a2008-12-01 08:23:25 +00004431/// FoldOrWithConstants - This helper function folds:
4432///
Bill Wendling236a1192008-12-02 05:09:00 +00004433/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004434///
4435/// into:
4436///
Bill Wendling236a1192008-12-02 05:09:00 +00004437/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004438///
Bill Wendling236a1192008-12-02 05:09:00 +00004439/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004440Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004441 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004442 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4443 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004444
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004445 Value *V1 = 0;
4446 ConstantInt *CI2 = 0;
4447 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004448
Bill Wendling86ee3162008-12-02 06:18:11 +00004449 APInt Xor = CI1->getValue() ^ CI2->getValue();
4450 if (!Xor.isAllOnesValue()) return 0;
4451
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004452 if (V1 == A || V1 == B) {
Bill Wendling86ee3162008-12-02 06:18:11 +00004453 Instruction *NewOp =
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004454 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4455 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004456 }
4457
4458 return 0;
4459}
4460
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004461Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4462 bool Changed = SimplifyCommutative(I);
4463 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4464
4465 if (isa<UndefValue>(Op1)) // X | undef -> -1
4466 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4467
4468 // or X, X = X
4469 if (Op0 == Op1)
4470 return ReplaceInstUsesWith(I, Op0);
4471
4472 // See if we can simplify any instructions used by the instruction whose sole
4473 // purpose is to compute bits we don't care about.
4474 if (!isa<VectorType>(I.getType())) {
Chris Lattner676c78e2009-01-31 08:15:18 +00004475 if (SimplifyDemandedInstructionBits(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004476 return &I;
4477 } else if (isa<ConstantAggregateZero>(Op1)) {
4478 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4479 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4480 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4481 return ReplaceInstUsesWith(I, I.getOperand(1));
4482 }
4483
4484
4485
4486 // or X, -1 == -1
4487 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4488 ConstantInt *C1 = 0; Value *X = 0;
4489 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4490 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004491 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004492 InsertNewInstBefore(Or, I);
4493 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004494 return BinaryOperator::CreateAnd(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004495 ConstantInt::get(RHS->getValue() | C1->getValue()));
4496 }
4497
4498 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4499 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004500 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004501 InsertNewInstBefore(Or, I);
4502 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004503 return BinaryOperator::CreateXor(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004504 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4505 }
4506
4507 // Try to fold constant and into select arguments.
4508 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4509 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4510 return R;
4511 if (isa<PHINode>(Op0))
4512 if (Instruction *NV = FoldOpIntoPhi(I))
4513 return NV;
4514 }
4515
4516 Value *A = 0, *B = 0;
4517 ConstantInt *C1 = 0, *C2 = 0;
4518
4519 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4520 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4521 return ReplaceInstUsesWith(I, Op1);
4522 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4523 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4524 return ReplaceInstUsesWith(I, Op0);
4525
4526 // (A | B) | C and A | (B | C) -> bswap if possible.
4527 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4528 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4529 match(Op1, m_Or(m_Value(), m_Value())) ||
4530 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4531 match(Op1, m_Shift(m_Value(), m_Value())))) {
4532 if (Instruction *BSwap = MatchBSwap(I))
4533 return BSwap;
4534 }
4535
4536 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4537 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4538 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004539 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004540 InsertNewInstBefore(NOr, I);
4541 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004542 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004543 }
4544
4545 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4546 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4547 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004548 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004549 InsertNewInstBefore(NOr, I);
4550 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004551 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004552 }
4553
4554 // (A & C)|(B & D)
4555 Value *C = 0, *D = 0;
4556 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4557 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4558 Value *V1 = 0, *V2 = 0, *V3 = 0;
4559 C1 = dyn_cast<ConstantInt>(C);
4560 C2 = dyn_cast<ConstantInt>(D);
4561 if (C1 && C2) { // (A & C1)|(B & C2)
4562 // If we have: ((V + N) & C1) | (V & C2)
4563 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4564 // replace with V+N.
4565 if (C1->getValue() == ~C2->getValue()) {
4566 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4567 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4568 // Add commutes, try both ways.
4569 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4570 return ReplaceInstUsesWith(I, A);
4571 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4572 return ReplaceInstUsesWith(I, A);
4573 }
4574 // Or commutes, try both ways.
4575 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4576 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4577 // Add commutes, try both ways.
4578 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4579 return ReplaceInstUsesWith(I, B);
4580 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4581 return ReplaceInstUsesWith(I, B);
4582 }
4583 }
4584 V1 = 0; V2 = 0; V3 = 0;
4585 }
4586
4587 // Check to see if we have any common things being and'ed. If so, find the
4588 // terms for V1 & (V2|V3).
4589 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4590 if (A == B) // (A & C)|(A & D) == A & (C|D)
4591 V1 = A, V2 = C, V3 = D;
4592 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4593 V1 = A, V2 = B, V3 = C;
4594 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4595 V1 = C, V2 = A, V3 = D;
4596 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4597 V1 = C, V2 = A, V3 = B;
4598
4599 if (V1) {
4600 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004601 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4602 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004603 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004604 }
Dan Gohman279952c2008-10-28 22:38:57 +00004605
Dan Gohman35b76162008-10-30 20:40:10 +00004606 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004607 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4608 return Match;
4609 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4610 return Match;
4611 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4612 return Match;
4613 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4614 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004615
Bill Wendling22ca8352008-11-30 13:52:49 +00004616 // ((A&~B)|(~A&B)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004617 if ((match(C, m_Not(m_Specific(D))) &&
4618 match(B, m_Not(m_Specific(A)))))
4619 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004620 // ((~B&A)|(~A&B)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004621 if ((match(A, m_Not(m_Specific(D))) &&
4622 match(B, m_Not(m_Specific(C)))))
4623 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004624 // ((A&~B)|(B&~A)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004625 if ((match(C, m_Not(m_Specific(B))) &&
4626 match(D, m_Not(m_Specific(A)))))
4627 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004628 // ((~B&A)|(B&~A)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004629 if ((match(A, m_Not(m_Specific(B))) &&
4630 match(D, m_Not(m_Specific(C)))))
4631 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004632 }
4633
4634 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4635 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4636 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4637 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4638 SI0->getOperand(1) == SI1->getOperand(1) &&
4639 (SI0->hasOneUse() || SI1->hasOneUse())) {
4640 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004641 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004642 SI1->getOperand(0),
4643 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004644 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004645 SI1->getOperand(1));
4646 }
4647 }
4648
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004649 // ((A|B)&1)|(B&-2) -> (A&1) | B
4650 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4651 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004652 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004653 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004654 }
4655 // (B&-2)|((A|B)&1) -> (A&1) | B
4656 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4657 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004658 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004659 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004660 }
4661
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004662 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4663 if (A == Op1) // ~A | A == -1
4664 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4665 } else {
4666 A = 0;
4667 }
4668 // Note, A is still live here!
4669 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4670 if (Op0 == B)
4671 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4672
4673 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4674 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004675 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004676 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004677 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004678 }
4679 }
4680
4681 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4682 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4683 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4684 return R;
4685
Chris Lattner0c678e52008-11-16 05:20:07 +00004686 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4687 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4688 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004689 }
4690
4691 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004692 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004693 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4694 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004695 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4696 !isa<ICmpInst>(Op1C->getOperand(0))) {
4697 const Type *SrcTy = Op0C->getOperand(0)->getType();
4698 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4699 // Only do this if the casts both really cause code to be
4700 // generated.
4701 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4702 I.getType(), TD) &&
4703 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4704 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004705 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004706 Op1C->getOperand(0),
4707 I.getName());
4708 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004709 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004710 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004711 }
4712 }
Chris Lattner91882432007-10-24 05:38:08 +00004713 }
4714
4715
4716 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4717 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4718 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4719 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004720 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng72988052008-10-14 18:44:08 +00004721 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner91882432007-10-24 05:38:08 +00004722 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4723 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4724 // If either of the constants are nans, then the whole thing returns
4725 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004726 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004727 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4728
4729 // Otherwise, no need to compare the two constants, compare the
4730 // rest.
4731 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4732 RHS->getOperand(0));
4733 }
Evan Cheng72988052008-10-14 18:44:08 +00004734 } else {
4735 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4736 FCmpInst::Predicate Op0CC, Op1CC;
4737 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4738 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4739 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4740 // Swap RHS operands to match LHS.
4741 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4742 std::swap(Op1LHS, Op1RHS);
4743 }
4744 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4745 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4746 if (Op0CC == Op1CC)
4747 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4748 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4749 Op1CC == FCmpInst::FCMP_TRUE)
4750 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4751 else if (Op0CC == FCmpInst::FCMP_FALSE)
4752 return ReplaceInstUsesWith(I, Op1);
4753 else if (Op1CC == FCmpInst::FCMP_FALSE)
4754 return ReplaceInstUsesWith(I, Op0);
4755 bool Op0Ordered;
4756 bool Op1Ordered;
4757 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4758 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4759 if (Op0Ordered == Op1Ordered) {
4760 // If both are ordered or unordered, return a new fcmp with
4761 // or'ed predicates.
4762 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4763 Op0LHS, Op0RHS);
4764 if (Instruction *I = dyn_cast<Instruction>(RV))
4765 return I;
4766 // Otherwise, it's a constant boolean value...
4767 return ReplaceInstUsesWith(I, RV);
4768 }
4769 }
4770 }
4771 }
Chris Lattner91882432007-10-24 05:38:08 +00004772 }
4773 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004774
4775 return Changed ? &I : 0;
4776}
4777
Dan Gohman089efff2008-05-13 00:00:25 +00004778namespace {
4779
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004780// XorSelf - Implements: X ^ X --> 0
4781struct XorSelf {
4782 Value *RHS;
4783 XorSelf(Value *rhs) : RHS(rhs) {}
4784 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4785 Instruction *apply(BinaryOperator &Xor) const {
4786 return &Xor;
4787 }
4788};
4789
Dan Gohman089efff2008-05-13 00:00:25 +00004790}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004791
4792Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4793 bool Changed = SimplifyCommutative(I);
4794 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4795
Evan Chenge5cd8032008-03-25 20:07:13 +00004796 if (isa<UndefValue>(Op1)) {
4797 if (isa<UndefValue>(Op0))
4798 // Handle undef ^ undef -> 0 special case. This is a common
4799 // idiom (misuse).
4800 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004801 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004802 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004803
4804 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4805 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004806 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004807 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4808 }
4809
4810 // See if we can simplify any instructions used by the instruction whose sole
4811 // purpose is to compute bits we don't care about.
4812 if (!isa<VectorType>(I.getType())) {
Chris Lattner676c78e2009-01-31 08:15:18 +00004813 if (SimplifyDemandedInstructionBits(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004814 return &I;
4815 } else if (isa<ConstantAggregateZero>(Op1)) {
4816 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4817 }
4818
4819 // Is this a ~ operation?
4820 if (Value *NotOp = dyn_castNotVal(&I)) {
4821 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4822 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4823 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4824 if (Op0I->getOpcode() == Instruction::And ||
4825 Op0I->getOpcode() == Instruction::Or) {
4826 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4827 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4828 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00004829 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004830 Op0I->getOperand(1)->getName()+".not");
4831 InsertNewInstBefore(NotY, I);
4832 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00004833 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004834 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004835 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004836 }
4837 }
4838 }
4839 }
4840
4841
4842 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004843 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00004844 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00004845 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004846 return new ICmpInst(ICI->getInversePredicate(),
4847 ICI->getOperand(0), ICI->getOperand(1));
4848
Nick Lewycky1405e922007-08-06 20:04:16 +00004849 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4850 return new FCmpInst(FCI->getInversePredicate(),
4851 FCI->getOperand(0), FCI->getOperand(1));
4852 }
4853
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00004854 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4855 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4856 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4857 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4858 Instruction::CastOps Opcode = Op0C->getOpcode();
4859 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4860 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4861 Op0C->getDestTy())) {
4862 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4863 CI->getOpcode(), CI->getInversePredicate(),
4864 CI->getOperand(0), CI->getOperand(1)), I);
4865 NewCI->takeName(CI);
4866 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4867 }
4868 }
4869 }
4870 }
4871 }
4872
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004873 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4874 // ~(c-X) == X-c-1 == X+(-c-1)
4875 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4876 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4877 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4878 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4879 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00004880 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004881 }
4882
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004883 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004884 if (Op0I->getOpcode() == Instruction::Add) {
4885 // ~(X-c) --> (-c-1)-X
4886 if (RHS->isAllOnesValue()) {
4887 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00004888 return BinaryOperator::CreateSub(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004889 ConstantExpr::getSub(NegOp0CI,
4890 ConstantInt::get(I.getType(), 1)),
4891 Op0I->getOperand(0));
4892 } else if (RHS->getValue().isSignBit()) {
4893 // (X + C) ^ signbit -> (X + C + signbit)
4894 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00004895 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004896
4897 }
4898 } else if (Op0I->getOpcode() == Instruction::Or) {
4899 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4900 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4901 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4902 // Anything in both C1 and C2 is known to be zero, remove it from
4903 // NewRHS.
4904 Constant *CommonBits = And(Op0CI, RHS);
4905 NewRHS = ConstantExpr::getAnd(NewRHS,
4906 ConstantExpr::getNot(CommonBits));
4907 AddToWorkList(Op0I);
4908 I.setOperand(0, Op0I->getOperand(0));
4909 I.setOperand(1, NewRHS);
4910 return &I;
4911 }
4912 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004913 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004914 }
4915
4916 // Try to fold constant and into select arguments.
4917 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4918 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4919 return R;
4920 if (isa<PHINode>(Op0))
4921 if (Instruction *NV = FoldOpIntoPhi(I))
4922 return NV;
4923 }
4924
4925 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4926 if (X == Op1)
4927 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4928
4929 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4930 if (X == Op0)
4931 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4932
4933
4934 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4935 if (Op1I) {
4936 Value *A, *B;
4937 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4938 if (A == Op0) { // B^(B|A) == (A|B)^B
4939 Op1I->swapOperands();
4940 I.swapOperands();
4941 std::swap(Op0, Op1);
4942 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4943 I.swapOperands(); // Simplified below.
4944 std::swap(Op0, Op1);
4945 }
Chris Lattner3b874082008-11-16 05:38:51 +00004946 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
4947 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
4948 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
4949 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004950 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4951 if (A == Op0) { // A^(A&B) -> A^(B&A)
4952 Op1I->swapOperands();
4953 std::swap(A, B);
4954 }
4955 if (B == Op0) { // A^(B&A) -> (B&A)^A
4956 I.swapOperands(); // Simplified below.
4957 std::swap(Op0, Op1);
4958 }
4959 }
4960 }
4961
4962 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4963 if (Op0I) {
4964 Value *A, *B;
4965 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4966 if (A == Op1) // (B|A)^B == (A|B)^B
4967 std::swap(A, B);
4968 if (B == Op1) { // (A|B)^B == A & ~B
4969 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00004970 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4971 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004972 }
Chris Lattner3b874082008-11-16 05:38:51 +00004973 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
4974 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
4975 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
4976 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004977 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4978 if (A == Op1) // (A&B)^A -> (B&A)^A
4979 std::swap(A, B);
4980 if (B == Op1 && // (B&A)^A == ~B & A
4981 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4982 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00004983 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4984 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004985 }
4986 }
4987 }
4988
4989 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4990 if (Op0I && Op1I && Op0I->isShift() &&
4991 Op0I->getOpcode() == Op1I->getOpcode() &&
4992 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4993 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4994 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004995 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004996 Op1I->getOperand(0),
4997 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004998 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004999 Op1I->getOperand(1));
5000 }
5001
5002 if (Op0I && Op1I) {
5003 Value *A, *B, *C, *D;
5004 // (A & B)^(A | B) -> A ^ B
5005 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5006 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5007 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005008 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005009 }
5010 // (A | B)^(A & B) -> A ^ B
5011 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5012 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5013 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005014 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005015 }
5016
5017 // (A & B)^(C & D)
5018 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5019 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5020 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5021 // (X & Y)^(X & Y) -> (Y^Z) & X
5022 Value *X = 0, *Y = 0, *Z = 0;
5023 if (A == C)
5024 X = A, Y = B, Z = D;
5025 else if (A == D)
5026 X = A, Y = B, Z = C;
5027 else if (B == C)
5028 X = B, Y = A, Z = D;
5029 else if (B == D)
5030 X = B, Y = A, Z = C;
5031
5032 if (X) {
5033 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005034 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5035 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005036 }
5037 }
5038 }
5039
5040 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5041 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5042 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5043 return R;
5044
5045 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005046 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005047 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5048 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5049 const Type *SrcTy = Op0C->getOperand(0)->getType();
5050 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5051 // Only do this if the casts both really cause code to be generated.
5052 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5053 I.getType(), TD) &&
5054 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5055 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00005056 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005057 Op1C->getOperand(0),
5058 I.getName());
5059 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005060 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005061 }
5062 }
Chris Lattner91882432007-10-24 05:38:08 +00005063 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005064
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005065 return Changed ? &I : 0;
5066}
5067
5068/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5069/// overflowed for this type.
5070static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5071 ConstantInt *In2, bool IsSigned = false) {
5072 Result = cast<ConstantInt>(Add(In1, In2));
5073
5074 if (IsSigned)
5075 if (In2->getValue().isNegative())
5076 return Result->getValue().sgt(In1->getValue());
5077 else
5078 return Result->getValue().slt(In1->getValue());
5079 else
5080 return Result->getValue().ult(In1->getValue());
5081}
5082
Dan Gohmanb80d5612008-09-10 23:30:57 +00005083/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5084/// overflowed for this type.
5085static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5086 ConstantInt *In2, bool IsSigned = false) {
Dan Gohman2c3b4892008-09-11 18:53:02 +00005087 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohmanb80d5612008-09-10 23:30:57 +00005088
5089 if (IsSigned)
5090 if (In2->getValue().isNegative())
5091 return Result->getValue().slt(In1->getValue());
5092 else
5093 return Result->getValue().sgt(In1->getValue());
5094 else
5095 return Result->getValue().ugt(In1->getValue());
5096}
5097
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005098/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5099/// code necessary to compute the offset from the base pointer (without adding
5100/// in the base pointer). Return the result as a signed integer of intptr size.
5101static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5102 TargetData &TD = IC.getTargetData();
5103 gep_type_iterator GTI = gep_type_begin(GEP);
5104 const Type *IntPtrTy = TD.getIntPtrType();
5105 Value *Result = Constant::getNullValue(IntPtrTy);
5106
5107 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005108 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005109 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5110
Gabor Greif17396002008-06-12 21:37:33 +00005111 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5112 ++i, ++GTI) {
5113 Value *Op = *i;
Duncan Sandsd68f13b2009-01-12 20:38:59 +00005114 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005115 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5116 if (OpC->isZero()) continue;
5117
5118 // Handle a struct index, which adds its field offset to the pointer.
5119 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5120 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5121
5122 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5123 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5124 else
5125 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005126 BinaryOperator::CreateAdd(Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005127 ConstantInt::get(IntPtrTy, Size),
5128 GEP->getName()+".offs"), I);
5129 continue;
5130 }
5131
5132 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5133 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5134 Scale = ConstantExpr::getMul(OC, Scale);
5135 if (Constant *RC = dyn_cast<Constant>(Result))
5136 Result = ConstantExpr::getAdd(RC, Scale);
5137 else {
5138 // Emit an add instruction.
5139 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005140 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005141 GEP->getName()+".offs"), I);
5142 }
5143 continue;
5144 }
5145 // Convert to correct type.
5146 if (Op->getType() != IntPtrTy) {
5147 if (Constant *OpC = dyn_cast<Constant>(Op))
5148 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5149 else
5150 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5151 Op->getName()+".c"), I);
5152 }
5153 if (Size != 1) {
5154 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5155 if (Constant *OpC = dyn_cast<Constant>(Op))
5156 Op = ConstantExpr::getMul(OpC, Scale);
5157 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00005158 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005159 GEP->getName()+".idx"), I);
5160 }
5161
5162 // Emit an add instruction.
5163 if (isa<Constant>(Op) && isa<Constant>(Result))
5164 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5165 cast<Constant>(Result));
5166 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005167 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005168 GEP->getName()+".offs"), I);
5169 }
5170 return Result;
5171}
5172
Chris Lattnereba75862008-04-22 02:53:33 +00005173
5174/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5175/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5176/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5177/// complex, and scales are involved. The above expression would also be legal
5178/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5179/// later form is less amenable to optimization though, and we are allowed to
5180/// generate the first by knowing that pointer arithmetic doesn't overflow.
5181///
5182/// If we can't emit an optimized form for this expression, this returns null.
5183///
5184static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5185 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00005186 TargetData &TD = IC.getTargetData();
5187 gep_type_iterator GTI = gep_type_begin(GEP);
5188
5189 // Check to see if this gep only has a single variable index. If so, and if
5190 // any constant indices are a multiple of its scale, then we can compute this
5191 // in terms of the scale of the variable index. For example, if the GEP
5192 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5193 // because the expression will cross zero at the same point.
5194 unsigned i, e = GEP->getNumOperands();
5195 int64_t Offset = 0;
5196 for (i = 1; i != e; ++i, ++GTI) {
5197 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5198 // Compute the aggregate offset of constant indices.
5199 if (CI->isZero()) continue;
5200
5201 // Handle a struct index, which adds its field offset to the pointer.
5202 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5203 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5204 } else {
Duncan Sandsd68f13b2009-01-12 20:38:59 +00005205 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005206 Offset += Size*CI->getSExtValue();
5207 }
5208 } else {
5209 // Found our variable index.
5210 break;
5211 }
5212 }
5213
5214 // If there are no variable indices, we must have a constant offset, just
5215 // evaluate it the general way.
5216 if (i == e) return 0;
5217
5218 Value *VariableIdx = GEP->getOperand(i);
5219 // Determine the scale factor of the variable element. For example, this is
5220 // 4 if the variable index is into an array of i32.
Duncan Sandsd68f13b2009-01-12 20:38:59 +00005221 uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005222
5223 // Verify that there are no other variable indices. If so, emit the hard way.
5224 for (++i, ++GTI; i != e; ++i, ++GTI) {
5225 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5226 if (!CI) return 0;
5227
5228 // Compute the aggregate offset of constant indices.
5229 if (CI->isZero()) continue;
5230
5231 // Handle a struct index, which adds its field offset to the pointer.
5232 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5233 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5234 } else {
Duncan Sandsd68f13b2009-01-12 20:38:59 +00005235 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005236 Offset += Size*CI->getSExtValue();
5237 }
5238 }
5239
5240 // Okay, we know we have a single variable index, which must be a
5241 // pointer/array/vector index. If there is no offset, life is simple, return
5242 // the index.
5243 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5244 if (Offset == 0) {
5245 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5246 // we don't need to bother extending: the extension won't affect where the
5247 // computation crosses zero.
5248 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5249 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5250 VariableIdx->getNameStart(), &I);
5251 return VariableIdx;
5252 }
5253
5254 // Otherwise, there is an index. The computation we will do will be modulo
5255 // the pointer size, so get it.
5256 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5257
5258 Offset &= PtrSizeMask;
5259 VariableScale &= PtrSizeMask;
5260
5261 // To do this transformation, any constant index must be a multiple of the
5262 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5263 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5264 // multiple of the variable scale.
5265 int64_t NewOffs = Offset / (int64_t)VariableScale;
5266 if (Offset != NewOffs*(int64_t)VariableScale)
5267 return 0;
5268
5269 // Okay, we can do this evaluation. Start by converting the index to intptr.
5270 const Type *IntPtrTy = TD.getIntPtrType();
5271 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005272 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005273 true /*SExt*/,
5274 VariableIdx->getNameStart(), &I);
5275 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005276 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005277}
5278
5279
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005280/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5281/// else. At this point we know that the GEP is on the LHS of the comparison.
5282Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5283 ICmpInst::Predicate Cond,
5284 Instruction &I) {
5285 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5286
Chris Lattnereba75862008-04-22 02:53:33 +00005287 // Look through bitcasts.
5288 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5289 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005290
5291 Value *PtrBase = GEPLHS->getOperand(0);
5292 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005293 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005294 // This transformation (ignoring the base and scales) is valid because we
5295 // know pointers can't overflow. See if we can output an optimized form.
5296 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5297
5298 // If not, synthesize the offset the hard way.
5299 if (Offset == 0)
5300 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattneraf97d022008-02-05 04:45:32 +00005301 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5302 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005303 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5304 // If the base pointers are different, but the indices are the same, just
5305 // compare the base pointer.
5306 if (PtrBase != GEPRHS->getOperand(0)) {
5307 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5308 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5309 GEPRHS->getOperand(0)->getType();
5310 if (IndicesTheSame)
5311 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5312 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5313 IndicesTheSame = false;
5314 break;
5315 }
5316
5317 // If all indices are the same, just compare the base pointers.
5318 if (IndicesTheSame)
5319 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5320 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5321
5322 // Otherwise, the base pointers are different and the indices are
5323 // different, bail out.
5324 return 0;
5325 }
5326
5327 // If one of the GEPs has all zero indices, recurse.
5328 bool AllZeros = true;
5329 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5330 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5331 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5332 AllZeros = false;
5333 break;
5334 }
5335 if (AllZeros)
5336 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5337 ICmpInst::getSwappedPredicate(Cond), I);
5338
5339 // If the other GEP has all zero indices, recurse.
5340 AllZeros = true;
5341 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5342 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5343 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5344 AllZeros = false;
5345 break;
5346 }
5347 if (AllZeros)
5348 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5349
5350 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5351 // If the GEPs only differ by one index, compare it.
5352 unsigned NumDifferences = 0; // Keep track of # differences.
5353 unsigned DiffOperand = 0; // The operand that differs.
5354 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5355 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5356 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5357 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5358 // Irreconcilable differences.
5359 NumDifferences = 2;
5360 break;
5361 } else {
5362 if (NumDifferences++) break;
5363 DiffOperand = i;
5364 }
5365 }
5366
5367 if (NumDifferences == 0) // SAME GEP?
5368 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00005369 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005370 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005371
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005372 else if (NumDifferences == 1) {
5373 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5374 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5375 // Make sure we do a signed comparison here.
5376 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5377 }
5378 }
5379
5380 // Only lower this if the icmp is the only user of the GEP or if we expect
5381 // the result to fold to a constant!
5382 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5383 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5384 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5385 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5386 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5387 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5388 }
5389 }
5390 return 0;
5391}
5392
Chris Lattnere6b62d92008-05-19 20:18:56 +00005393/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5394///
5395Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5396 Instruction *LHSI,
5397 Constant *RHSC) {
5398 if (!isa<ConstantFP>(RHSC)) return 0;
5399 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5400
5401 // Get the width of the mantissa. We don't want to hack on conversions that
5402 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005403 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005404 if (MantissaWidth == -1) return 0; // Unknown.
5405
5406 // Check to see that the input is converted from an integer type that is small
5407 // enough that preserves all bits. TODO: check here for "known" sign bits.
5408 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5409 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5410
5411 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005412 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5413 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005414 ++InputSize;
5415
5416 // If the conversion would lose info, don't hack on this.
5417 if ((int)InputSize > MantissaWidth)
5418 return 0;
5419
5420 // Otherwise, we can potentially simplify the comparison. We know that it
5421 // will always come through as an integer value and we know the constant is
5422 // not a NAN (it would have been previously simplified).
5423 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5424
5425 ICmpInst::Predicate Pred;
5426 switch (I.getPredicate()) {
5427 default: assert(0 && "Unexpected predicate!");
5428 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005429 case FCmpInst::FCMP_OEQ:
5430 Pred = ICmpInst::ICMP_EQ;
5431 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005432 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005433 case FCmpInst::FCMP_OGT:
5434 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5435 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005436 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005437 case FCmpInst::FCMP_OGE:
5438 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5439 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005440 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005441 case FCmpInst::FCMP_OLT:
5442 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5443 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005444 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005445 case FCmpInst::FCMP_OLE:
5446 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5447 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005448 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005449 case FCmpInst::FCMP_ONE:
5450 Pred = ICmpInst::ICMP_NE;
5451 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005452 case FCmpInst::FCMP_ORD:
Eli Friedmanc9c96242008-11-30 22:48:49 +00005453 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005454 case FCmpInst::FCMP_UNO:
Eli Friedmanc9c96242008-11-30 22:48:49 +00005455 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005456 }
5457
5458 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5459
5460 // Now we know that the APFloat is a normal number, zero or inf.
5461
Chris Lattnerf13ff492008-05-20 03:50:52 +00005462 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005463 // comparing an i8 to 300.0.
5464 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5465
Bill Wendling20636df2008-11-09 04:26:50 +00005466 if (!LHSUnsigned) {
5467 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5468 // and large values.
5469 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5470 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5471 APFloat::rmNearestTiesToEven);
5472 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5473 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5474 Pred == ICmpInst::ICMP_SLE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005475 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5476 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005477 }
5478 } else {
5479 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5480 // +INF and large values.
5481 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5482 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5483 APFloat::rmNearestTiesToEven);
5484 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5485 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5486 Pred == ICmpInst::ICMP_ULE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005487 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5488 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005489 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005490 }
5491
Bill Wendling20636df2008-11-09 04:26:50 +00005492 if (!LHSUnsigned) {
5493 // See if the RHS value is < SignedMin.
5494 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5495 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5496 APFloat::rmNearestTiesToEven);
5497 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5498 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5499 Pred == ICmpInst::ICMP_SGE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005500 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5501 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005502 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005503 }
5504
Bill Wendling20636df2008-11-09 04:26:50 +00005505 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5506 // [0, UMAX], but it may still be fractional. See if it is fractional by
5507 // casting the FP value to the integer value and back, checking for equality.
5508 // Don't do this for zero, because -0.0 is not fractional.
Chris Lattnere6b62d92008-05-19 20:18:56 +00005509 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5510 if (!RHS.isZero() &&
5511 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
Bill Wendling20636df2008-11-09 04:26:50 +00005512 // If we had a comparison against a fractional value, we have to adjust the
5513 // compare predicate and sometimes the value. RHSC is rounded towards zero
5514 // at this point.
Chris Lattnere6b62d92008-05-19 20:18:56 +00005515 switch (Pred) {
5516 default: assert(0 && "Unexpected integer comparison!");
5517 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedmanc9c96242008-11-30 22:48:49 +00005518 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005519 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Eli Friedmanc9c96242008-11-30 22:48:49 +00005520 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005521 case ICmpInst::ICMP_ULE:
5522 // (float)int <= 4.4 --> int <= 4
5523 // (float)int <= -4.4 --> false
5524 if (RHS.isNegative())
Eli Friedmanc9c96242008-11-30 22:48:49 +00005525 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005526 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005527 case ICmpInst::ICMP_SLE:
5528 // (float)int <= 4.4 --> int <= 4
5529 // (float)int <= -4.4 --> int < -4
5530 if (RHS.isNegative())
5531 Pred = ICmpInst::ICMP_SLT;
5532 break;
Bill Wendling20636df2008-11-09 04:26:50 +00005533 case ICmpInst::ICMP_ULT:
5534 // (float)int < -4.4 --> false
5535 // (float)int < 4.4 --> int <= 4
5536 if (RHS.isNegative())
Eli Friedmanc9c96242008-11-30 22:48:49 +00005537 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005538 Pred = ICmpInst::ICMP_ULE;
5539 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005540 case ICmpInst::ICMP_SLT:
5541 // (float)int < -4.4 --> int < -4
5542 // (float)int < 4.4 --> int <= 4
5543 if (!RHS.isNegative())
5544 Pred = ICmpInst::ICMP_SLE;
5545 break;
Bill Wendling20636df2008-11-09 04:26:50 +00005546 case ICmpInst::ICMP_UGT:
5547 // (float)int > 4.4 --> int > 4
5548 // (float)int > -4.4 --> true
5549 if (RHS.isNegative())
Eli Friedmanc9c96242008-11-30 22:48:49 +00005550 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendling20636df2008-11-09 04:26:50 +00005551 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005552 case ICmpInst::ICMP_SGT:
5553 // (float)int > 4.4 --> int > 4
5554 // (float)int > -4.4 --> int >= -4
5555 if (RHS.isNegative())
5556 Pred = ICmpInst::ICMP_SGE;
5557 break;
Bill Wendling20636df2008-11-09 04:26:50 +00005558 case ICmpInst::ICMP_UGE:
5559 // (float)int >= -4.4 --> true
5560 // (float)int >= 4.4 --> int > 4
5561 if (!RHS.isNegative())
Eli Friedmanc9c96242008-11-30 22:48:49 +00005562 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendling20636df2008-11-09 04:26:50 +00005563 Pred = ICmpInst::ICMP_UGT;
5564 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005565 case ICmpInst::ICMP_SGE:
5566 // (float)int >= -4.4 --> int >= -4
5567 // (float)int >= 4.4 --> int > 4
5568 if (!RHS.isNegative())
5569 Pred = ICmpInst::ICMP_SGT;
5570 break;
5571 }
5572 }
5573
5574 // Lower this FP comparison into an appropriate integer version of the
5575 // comparison.
5576 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5577}
5578
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005579Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5580 bool Changed = SimplifyCompare(I);
5581 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5582
5583 // Fold trivial predicates.
5584 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005585 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005586 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005587 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005588
5589 // Simplify 'fcmp pred X, X'
5590 if (Op0 == Op1) {
5591 switch (I.getPredicate()) {
5592 default: assert(0 && "Unknown predicate!");
5593 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5594 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5595 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedmanc9c96242008-11-30 22:48:49 +00005596 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005597 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5598 case FCmpInst::FCMP_OLT: // True if ordered and less than
5599 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedmanc9c96242008-11-30 22:48:49 +00005600 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005601
5602 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5603 case FCmpInst::FCMP_ULT: // True if unordered or less than
5604 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5605 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5606 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5607 I.setPredicate(FCmpInst::FCMP_UNO);
5608 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5609 return &I;
5610
5611 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5612 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5613 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5614 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5615 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5616 I.setPredicate(FCmpInst::FCMP_ORD);
5617 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5618 return &I;
5619 }
5620 }
5621
5622 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5623 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5624
5625 // Handle fcmp with constant RHS
5626 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005627 // If the constant is a nan, see if we can fold the comparison based on it.
5628 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5629 if (CFP->getValueAPF().isNaN()) {
5630 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedmanc9c96242008-11-30 22:48:49 +00005631 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnerf13ff492008-05-20 03:50:52 +00005632 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5633 "Comparison must be either ordered or unordered!");
5634 // True if unordered.
Eli Friedmanc9c96242008-11-30 22:48:49 +00005635 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005636 }
5637 }
5638
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005639 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5640 switch (LHSI->getOpcode()) {
5641 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005642 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5643 // block. If in the same block, we're encouraging jump threading. If
5644 // not, we are just pessimizing the code by making an i1 phi.
5645 if (LHSI->getParent() == I.getParent())
5646 if (Instruction *NV = FoldOpIntoPhi(I))
5647 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005648 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005649 case Instruction::SIToFP:
5650 case Instruction::UIToFP:
5651 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5652 return NV;
5653 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005654 case Instruction::Select:
5655 // If either operand of the select is a constant, we can fold the
5656 // comparison into the select arms, which will cause one to be
5657 // constant folded and the select turned into a bitwise or.
5658 Value *Op1 = 0, *Op2 = 0;
5659 if (LHSI->hasOneUse()) {
5660 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5661 // Fold the known value into the constant operand.
5662 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5663 // Insert a new FCmp of the other select operand.
5664 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5665 LHSI->getOperand(2), RHSC,
5666 I.getName()), I);
5667 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5668 // Fold the known value into the constant operand.
5669 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5670 // Insert a new FCmp of the other select operand.
5671 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5672 LHSI->getOperand(1), RHSC,
5673 I.getName()), I);
5674 }
5675 }
5676
5677 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005678 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005679 break;
5680 }
5681 }
5682
5683 return Changed ? &I : 0;
5684}
5685
5686Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5687 bool Changed = SimplifyCompare(I);
5688 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5689 const Type *Ty = Op0->getType();
5690
5691 // icmp X, X
5692 if (Op0 == Op1)
5693 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005694 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005695
5696 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5697 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005698
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005699 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5700 // addresses never equal each other! We already know that Op0 != Op1.
5701 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5702 isa<ConstantPointerNull>(Op0)) &&
5703 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5704 isa<ConstantPointerNull>(Op1)))
5705 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005706 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005707
5708 // icmp's with boolean values can always be turned into bitwise operations
5709 if (Ty == Type::Int1Ty) {
5710 switch (I.getPredicate()) {
5711 default: assert(0 && "Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00005712 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005713 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005714 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005715 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005716 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005717 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005718 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005719
5720 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00005721 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005722 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005723 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greifa645dd32008-05-16 19:29:10 +00005724 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005725 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005726 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005727 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005728 case ICmpInst::ICMP_SGT:
5729 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005730 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005731 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5732 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5733 InsertNewInstBefore(Not, I);
5734 return BinaryOperator::CreateAnd(Not, Op0);
5735 }
5736 case ICmpInst::ICMP_UGE:
5737 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5738 // FALL THROUGH
5739 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00005740 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005741 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005742 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005743 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005744 case ICmpInst::ICMP_SGE:
5745 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5746 // FALL THROUGH
5747 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5748 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5749 InsertNewInstBefore(Not, I);
5750 return BinaryOperator::CreateOr(Not, Op0);
5751 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005752 }
5753 }
5754
Dan Gohman58c09632008-09-16 18:46:06 +00005755 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005756 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3d816532008-07-11 04:09:09 +00005757 Value *A, *B;
Christopher Lambfa6b3102007-12-20 07:21:11 +00005758
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005759 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5760 if (I.isEquality() && CI->isNullValue() &&
5761 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5762 // (icmp cond A B) if cond is equality
5763 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005764 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005765
Dan Gohman58c09632008-09-16 18:46:06 +00005766 // If we have an icmp le or icmp ge instruction, turn it into the
5767 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5768 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00005769 switch (I.getPredicate()) {
5770 default: break;
5771 case ICmpInst::ICMP_ULE:
5772 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5773 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5774 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5775 case ICmpInst::ICMP_SLE:
5776 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5777 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5778 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5779 case ICmpInst::ICMP_UGE:
5780 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5781 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5782 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5783 case ICmpInst::ICMP_SGE:
5784 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5785 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5786 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5787 }
5788
Chris Lattnera1308652008-07-11 05:40:05 +00005789 // See if we can fold the comparison based on range information we can get
5790 // by checking whether bits are known to be zero or one in the input.
5791 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5792 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5793
5794 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005795 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005796 bool UnusedBit;
5797 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5798
Chris Lattner676c78e2009-01-31 08:15:18 +00005799 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005800 isSignBit ? APInt::getSignBit(BitWidth)
5801 : APInt::getAllOnesValue(BitWidth),
5802 KnownZero, KnownOne, 0))
5803 return &I;
5804
5805 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00005806 // in. Compute the Min, Max and RHS values based on the known bits. For the
5807 // EQ and NE we use unsigned values.
5808 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner62d0f232008-07-11 05:08:55 +00005809 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5810 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5811 else
5812 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5813
Chris Lattnera1308652008-07-11 05:40:05 +00005814 // If Min and Max are known to be the same, then SimplifyDemandedBits
5815 // figured out that the LHS is a constant. Just constant fold this now so
5816 // that code below can assume that Min != Max.
5817 if (Min == Max)
5818 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5819 ConstantInt::get(Min),
5820 CI));
5821
5822 // Based on the range information we know about the LHS, see if we can
5823 // simplify this comparison. For example, (x&4) < 8 is always true.
5824 const APInt &RHSVal = CI->getValue();
Chris Lattner62d0f232008-07-11 05:08:55 +00005825 switch (I.getPredicate()) { // LE/GE have been folded already.
5826 default: assert(0 && "Unknown icmp opcode!");
5827 case ICmpInst::ICMP_EQ:
5828 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5829 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5830 break;
5831 case ICmpInst::ICMP_NE:
5832 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5833 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5834 break;
5835 case ICmpInst::ICMP_ULT:
Chris Lattnera1308652008-07-11 05:40:05 +00005836 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner62d0f232008-07-11 05:08:55 +00005837 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera1308652008-07-11 05:40:05 +00005838 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005839 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005840 if (RHSVal == Max) // A <u MAX -> A != MAX
5841 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5842 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5843 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5844
5845 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5846 if (CI->isMinValue(true))
5847 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5848 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner62d0f232008-07-11 05:08:55 +00005849 break;
5850 case ICmpInst::ICMP_UGT:
Chris Lattnera1308652008-07-11 05:40:05 +00005851 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner62d0f232008-07-11 05:08:55 +00005852 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera1308652008-07-11 05:40:05 +00005853 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005854 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005855
5856 if (RHSVal == Min) // A >u MIN -> A != MIN
5857 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5858 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5859 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5860
5861 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5862 if (CI->isMaxValue(true))
5863 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5864 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner62d0f232008-07-11 05:08:55 +00005865 break;
5866 case ICmpInst::ICMP_SLT:
Chris Lattnera1308652008-07-11 05:40:05 +00005867 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner62d0f232008-07-11 05:08:55 +00005868 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner611b43e2008-07-11 06:40:29 +00005869 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005870 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005871 if (RHSVal == Max) // A <s MAX -> A != MAX
5872 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattner3496f3e2008-07-11 06:36:01 +00005873 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattner55ab3152008-07-11 06:38:16 +00005874 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00005875 break;
5876 case ICmpInst::ICMP_SGT:
Chris Lattnera1308652008-07-11 05:40:05 +00005877 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner62d0f232008-07-11 05:08:55 +00005878 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera1308652008-07-11 05:40:05 +00005879 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005880 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005881
5882 if (RHSVal == Min) // A >s MIN -> A != MIN
5883 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5884 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5885 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00005886 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005887 }
Dan Gohman58c09632008-09-16 18:46:06 +00005888 }
5889
5890 // Test if the ICmpInst instruction is used exclusively by a select as
5891 // part of a minimum or maximum operation. If so, refrain from doing
5892 // any other folding. This helps out other analyses which understand
5893 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5894 // and CodeGen. And in this case, at least one of the comparison
5895 // operands has at least one user besides the compare (the select),
5896 // which would often largely negate the benefit of folding anyway.
5897 if (I.hasOneUse())
5898 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5899 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5900 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5901 return 0;
5902
5903 // See if we are doing a comparison between a constant and an instruction that
5904 // can be folded into the comparison.
5905 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005906 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5907 // instruction, see if that instruction also has constants so that the
5908 // instruction can be folded into the icmp
5909 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5910 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5911 return Res;
5912 }
5913
5914 // Handle icmp with constant (but not simple integer constant) RHS
5915 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5916 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5917 switch (LHSI->getOpcode()) {
5918 case Instruction::GetElementPtr:
5919 if (RHSC->isNullValue()) {
5920 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5921 bool isAllZeros = true;
5922 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5923 if (!isa<Constant>(LHSI->getOperand(i)) ||
5924 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5925 isAllZeros = false;
5926 break;
5927 }
5928 if (isAllZeros)
5929 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5930 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5931 }
5932 break;
5933
5934 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005935 // Only fold icmp into the PHI if the phi and fcmp are in the same
5936 // block. If in the same block, we're encouraging jump threading. If
5937 // not, we are just pessimizing the code by making an i1 phi.
5938 if (LHSI->getParent() == I.getParent())
5939 if (Instruction *NV = FoldOpIntoPhi(I))
5940 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005941 break;
5942 case Instruction::Select: {
5943 // If either operand of the select is a constant, we can fold the
5944 // comparison into the select arms, which will cause one to be
5945 // constant folded and the select turned into a bitwise or.
5946 Value *Op1 = 0, *Op2 = 0;
5947 if (LHSI->hasOneUse()) {
5948 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5949 // Fold the known value into the constant operand.
5950 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5951 // Insert a new ICmp of the other select operand.
5952 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5953 LHSI->getOperand(2), RHSC,
5954 I.getName()), I);
5955 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5956 // Fold the known value into the constant operand.
5957 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5958 // Insert a new ICmp of the other select operand.
5959 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5960 LHSI->getOperand(1), RHSC,
5961 I.getName()), I);
5962 }
5963 }
5964
5965 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005966 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005967 break;
5968 }
5969 case Instruction::Malloc:
5970 // If we have (malloc != null), and if the malloc has a single use, we
5971 // can assume it is successful and remove the malloc.
5972 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5973 AddToWorkList(LHSI);
5974 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005975 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005976 }
5977 break;
5978 }
5979 }
5980
5981 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5982 if (User *GEP = dyn_castGetElementPtr(Op0))
5983 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5984 return NI;
5985 if (User *GEP = dyn_castGetElementPtr(Op1))
5986 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5987 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5988 return NI;
5989
5990 // Test to see if the operands of the icmp are casted versions of other
5991 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5992 // now.
5993 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5994 if (isa<PointerType>(Op0->getType()) &&
5995 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5996 // We keep moving the cast from the left operand over to the right
5997 // operand, where it can often be eliminated completely.
5998 Op0 = CI->getOperand(0);
5999
6000 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6001 // so eliminate it as well.
6002 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6003 Op1 = CI2->getOperand(0);
6004
6005 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006006 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006007 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6008 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6009 } else {
6010 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006011 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006012 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006013 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006014 return new ICmpInst(I.getPredicate(), Op0, Op1);
6015 }
6016 }
6017
6018 if (isa<CastInst>(Op0)) {
6019 // Handle the special case of: icmp (cast bool to X), <cst>
6020 // This comes up when you have code like
6021 // int X = A < B;
6022 // if (X) ...
6023 // For generality, we handle any zero-extension of any operand comparison
6024 // with a constant or another cast from the same type.
6025 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6026 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6027 return R;
6028 }
6029
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006030 // See if it's the same type of instruction on the left and right.
6031 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6032 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006033 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6034 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
6035 I.isEquality()) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006036 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006037 default: break;
6038 case Instruction::Add:
6039 case Instruction::Sub:
6040 case Instruction::Xor:
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006041 // a+x icmp eq/ne b+x --> a icmp b
6042 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6043 Op1I->getOperand(0));
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006044 break;
6045 case Instruction::Mul:
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006046 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6047 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6048 // Mask = -1 >> count-trailing-zeros(Cst).
6049 if (!CI->isZero() && !CI->isOne()) {
6050 const APInt &AP = CI->getValue();
6051 ConstantInt *Mask = ConstantInt::get(
6052 APInt::getLowBitsSet(AP.getBitWidth(),
6053 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006054 AP.countTrailingZeros()));
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006055 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6056 Mask);
6057 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6058 Mask);
6059 InsertNewInstBefore(And1, I);
6060 InsertNewInstBefore(And2, I);
6061 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006062 }
6063 }
6064 break;
6065 }
6066 }
6067 }
6068 }
6069
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006070 // ~x < ~y --> y < x
6071 { Value *A, *B;
6072 if (match(Op0, m_Not(m_Value(A))) &&
6073 match(Op1, m_Not(m_Value(B))))
6074 return new ICmpInst(I.getPredicate(), B, A);
6075 }
6076
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006077 if (I.isEquality()) {
6078 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006079
6080 // -x == -y --> x == y
6081 if (match(Op0, m_Neg(m_Value(A))) &&
6082 match(Op1, m_Neg(m_Value(B))))
6083 return new ICmpInst(I.getPredicate(), A, B);
6084
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006085 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6086 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6087 Value *OtherVal = A == Op1 ? B : A;
6088 return new ICmpInst(I.getPredicate(), OtherVal,
6089 Constant::getNullValue(A->getType()));
6090 }
6091
6092 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6093 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006094 ConstantInt *C1, *C2;
6095 if (match(B, m_ConstantInt(C1)) &&
6096 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6097 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6098 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6099 return new ICmpInst(I.getPredicate(), A,
6100 InsertNewInstBefore(Xor, I));
6101 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006102
6103 // A^B == A^D -> B == D
6104 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6105 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6106 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6107 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6108 }
6109 }
6110
6111 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6112 (A == Op0 || B == Op0)) {
6113 // A == (A^B) -> B == 0
6114 Value *OtherVal = A == Op0 ? B : A;
6115 return new ICmpInst(I.getPredicate(), OtherVal,
6116 Constant::getNullValue(A->getType()));
6117 }
Chris Lattner3b874082008-11-16 05:38:51 +00006118
6119 // (A-B) == A -> B == 0
6120 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6121 return new ICmpInst(I.getPredicate(), B,
6122 Constant::getNullValue(B->getType()));
6123
6124 // A == (A-B) -> B == 0
6125 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006126 return new ICmpInst(I.getPredicate(), B,
6127 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006128
6129 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6130 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6131 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6132 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6133 Value *X = 0, *Y = 0, *Z = 0;
6134
6135 if (A == C) {
6136 X = B; Y = D; Z = A;
6137 } else if (A == D) {
6138 X = B; Y = C; Z = A;
6139 } else if (B == C) {
6140 X = A; Y = D; Z = B;
6141 } else if (B == D) {
6142 X = A; Y = C; Z = B;
6143 }
6144
6145 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00006146 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6147 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006148 I.setOperand(0, Op1);
6149 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6150 return &I;
6151 }
6152 }
6153 }
6154 return Changed ? &I : 0;
6155}
6156
6157
6158/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6159/// and CmpRHS are both known to be integer constants.
6160Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6161 ConstantInt *DivRHS) {
6162 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6163 const APInt &CmpRHSV = CmpRHS->getValue();
6164
6165 // FIXME: If the operand types don't match the type of the divide
6166 // then don't attempt this transform. The code below doesn't have the
6167 // logic to deal with a signed divide and an unsigned compare (and
6168 // vice versa). This is because (x /s C1) <s C2 produces different
6169 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6170 // (x /u C1) <u C2. Simply casting the operands and result won't
6171 // work. :( The if statement below tests that condition and bails
6172 // if it finds it.
6173 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6174 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6175 return 0;
6176 if (DivRHS->isZero())
6177 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006178 if (DivIsSigned && DivRHS->isAllOnesValue())
6179 return 0; // The overflow computation also screws up here
6180 if (DivRHS->isOne())
6181 return 0; // Not worth bothering, and eliminates some funny cases
6182 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006183
6184 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6185 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6186 // C2 (CI). By solving for X we can turn this into a range check
6187 // instead of computing a divide.
6188 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6189
6190 // Determine if the product overflows by seeing if the product is
6191 // not equal to the divide. Make sure we do the same kind of divide
6192 // as in the LHS instruction that we're folding.
6193 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6194 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6195
6196 // Get the ICmp opcode
6197 ICmpInst::Predicate Pred = ICI.getPredicate();
6198
6199 // Figure out the interval that is being checked. For example, a comparison
6200 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6201 // Compute this interval based on the constants involved and the signedness of
6202 // the compare/divide. This computes a half-open interval, keeping track of
6203 // whether either value in the interval overflows. After analysis each
6204 // overflow variable is set to 0 if it's corresponding bound variable is valid
6205 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6206 int LoOverflow = 0, HiOverflow = 0;
6207 ConstantInt *LoBound = 0, *HiBound = 0;
6208
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006209 if (!DivIsSigned) { // udiv
6210 // e.g. X/5 op 3 --> [15, 20)
6211 LoBound = Prod;
6212 HiOverflow = LoOverflow = ProdOV;
6213 if (!HiOverflow)
6214 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006215 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006216 if (CmpRHSV == 0) { // (X / pos) op 0
6217 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6218 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6219 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006220 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006221 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6222 HiOverflow = LoOverflow = ProdOV;
6223 if (!HiOverflow)
6224 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6225 } else { // (X / pos) op neg
6226 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006227 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006228 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6229 if (!LoOverflow) {
6230 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6231 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6232 true) ? -1 : 0;
6233 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006234 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006235 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006236 if (CmpRHSV == 0) { // (X / neg) op 0
6237 // e.g. X/-5 op 0 --> [-4, 5)
6238 LoBound = AddOne(DivRHS);
6239 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6240 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6241 HiOverflow = 1; // [INTMIN+1, overflow)
6242 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6243 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006244 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006245 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006246 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006247 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6248 if (!LoOverflow)
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006249 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006250 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006251 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6252 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006253 if (!HiOverflow)
6254 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006255 }
6256
6257 // Dividing by a negative swaps the condition. LT <-> GT
6258 Pred = ICmpInst::getSwappedPredicate(Pred);
6259 }
6260
6261 Value *X = DivI->getOperand(0);
6262 switch (Pred) {
6263 default: assert(0 && "Unhandled icmp opcode!");
6264 case ICmpInst::ICMP_EQ:
6265 if (LoOverflow && HiOverflow)
6266 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6267 else if (HiOverflow)
6268 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6269 ICmpInst::ICMP_UGE, X, LoBound);
6270 else if (LoOverflow)
6271 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6272 ICmpInst::ICMP_ULT, X, HiBound);
6273 else
6274 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6275 case ICmpInst::ICMP_NE:
6276 if (LoOverflow && HiOverflow)
6277 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6278 else if (HiOverflow)
6279 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6280 ICmpInst::ICMP_ULT, X, LoBound);
6281 else if (LoOverflow)
6282 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6283 ICmpInst::ICMP_UGE, X, HiBound);
6284 else
6285 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6286 case ICmpInst::ICMP_ULT:
6287 case ICmpInst::ICMP_SLT:
6288 if (LoOverflow == +1) // Low bound is greater than input range.
6289 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6290 if (LoOverflow == -1) // Low bound is less than input range.
6291 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6292 return new ICmpInst(Pred, X, LoBound);
6293 case ICmpInst::ICMP_UGT:
6294 case ICmpInst::ICMP_SGT:
6295 if (HiOverflow == +1) // High bound greater than input range.
6296 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6297 else if (HiOverflow == -1) // High bound less than input range.
6298 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6299 if (Pred == ICmpInst::ICMP_UGT)
6300 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6301 else
6302 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6303 }
6304}
6305
6306
6307/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6308///
6309Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6310 Instruction *LHSI,
6311 ConstantInt *RHS) {
6312 const APInt &RHSV = RHS->getValue();
6313
6314 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006315 case Instruction::Trunc:
6316 if (ICI.isEquality() && LHSI->hasOneUse()) {
6317 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6318 // of the high bits truncated out of x are known.
6319 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6320 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6321 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6322 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6323 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6324
6325 // If all the high bits are known, we can do this xform.
6326 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6327 // Pull in the high bits from known-ones set.
6328 APInt NewRHS(RHS->getValue());
6329 NewRHS.zext(SrcBits);
6330 NewRHS |= KnownOne;
6331 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6332 ConstantInt::get(NewRHS));
6333 }
6334 }
6335 break;
6336
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006337 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6338 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6339 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6340 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006341 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6342 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006343 Value *CompareVal = LHSI->getOperand(0);
6344
6345 // If the sign bit of the XorCST is not set, there is no change to
6346 // the operation, just stop using the Xor.
6347 if (!XorCST->getValue().isNegative()) {
6348 ICI.setOperand(0, CompareVal);
6349 AddToWorkList(LHSI);
6350 return &ICI;
6351 }
6352
6353 // Was the old condition true if the operand is positive?
6354 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6355
6356 // If so, the new one isn't.
6357 isTrueIfPositive ^= true;
6358
6359 if (isTrueIfPositive)
6360 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6361 else
6362 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6363 }
6364 }
6365 break;
6366 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6367 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6368 LHSI->getOperand(0)->hasOneUse()) {
6369 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6370
6371 // If the LHS is an AND of a truncating cast, we can widen the
6372 // and/compare to be the input width without changing the value
6373 // produced, eliminating a cast.
6374 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6375 // We can do this transformation if either the AND constant does not
6376 // have its sign bit set or if it is an equality comparison.
6377 // Extending a relational comparison when we're checking the sign
6378 // bit would not work.
6379 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006380 (ICI.isEquality() ||
6381 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006382 uint32_t BitWidth =
6383 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6384 APInt NewCST = AndCST->getValue();
6385 NewCST.zext(BitWidth);
6386 APInt NewCI = RHSV;
6387 NewCI.zext(BitWidth);
6388 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006389 BinaryOperator::CreateAnd(Cast->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006390 ConstantInt::get(NewCST),LHSI->getName());
6391 InsertNewInstBefore(NewAnd, ICI);
6392 return new ICmpInst(ICI.getPredicate(), NewAnd,
6393 ConstantInt::get(NewCI));
6394 }
6395 }
6396
6397 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6398 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6399 // happens a LOT in code produced by the C front-end, for bitfield
6400 // access.
6401 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6402 if (Shift && !Shift->isShift())
6403 Shift = 0;
6404
6405 ConstantInt *ShAmt;
6406 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6407 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6408 const Type *AndTy = AndCST->getType(); // Type of the and.
6409
6410 // We can fold this as long as we can't shift unknown bits
6411 // into the mask. This can only happen with signed shift
6412 // rights, as they sign-extend.
6413 if (ShAmt) {
6414 bool CanFold = Shift->isLogicalShift();
6415 if (!CanFold) {
6416 // To test for the bad case of the signed shr, see if any
6417 // of the bits shifted in could be tested after the mask.
6418 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6419 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6420
6421 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6422 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6423 AndCST->getValue()) == 0)
6424 CanFold = true;
6425 }
6426
6427 if (CanFold) {
6428 Constant *NewCst;
6429 if (Shift->getOpcode() == Instruction::Shl)
6430 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6431 else
6432 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6433
6434 // Check to see if we are shifting out any of the bits being
6435 // compared.
6436 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6437 // If we shifted bits out, the fold is not going to work out.
6438 // As a special case, check to see if this means that the
6439 // result is always true or false now.
6440 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6441 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6442 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6443 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6444 } else {
6445 ICI.setOperand(1, NewCst);
6446 Constant *NewAndCST;
6447 if (Shift->getOpcode() == Instruction::Shl)
6448 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6449 else
6450 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6451 LHSI->setOperand(1, NewAndCST);
6452 LHSI->setOperand(0, Shift->getOperand(0));
6453 AddToWorkList(Shift); // Shift is dead.
6454 AddUsesToWorkList(ICI);
6455 return &ICI;
6456 }
6457 }
6458 }
6459
6460 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6461 // preferable because it allows the C<<Y expression to be hoisted out
6462 // of a loop if Y is invariant and X is not.
6463 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6464 ICI.isEquality() && !Shift->isArithmeticShift() &&
6465 isa<Instruction>(Shift->getOperand(0))) {
6466 // Compute C << Y.
6467 Value *NS;
6468 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006469 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006470 Shift->getOperand(1), "tmp");
6471 } else {
6472 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006473 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006474 Shift->getOperand(1), "tmp");
6475 }
6476 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6477
6478 // Compute X & (C << Y).
6479 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006480 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006481 InsertNewInstBefore(NewAnd, ICI);
6482
6483 ICI.setOperand(0, NewAnd);
6484 return &ICI;
6485 }
6486 }
6487 break;
6488
6489 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6490 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6491 if (!ShAmt) break;
6492
6493 uint32_t TypeBits = RHSV.getBitWidth();
6494
6495 // Check that the shift amount is in range. If not, don't perform
6496 // undefined shifts. When the shift is visited it will be
6497 // simplified.
6498 if (ShAmt->uge(TypeBits))
6499 break;
6500
6501 if (ICI.isEquality()) {
6502 // If we are comparing against bits always shifted out, the
6503 // comparison cannot succeed.
6504 Constant *Comp =
6505 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6506 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6507 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6508 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6509 return ReplaceInstUsesWith(ICI, Cst);
6510 }
6511
6512 if (LHSI->hasOneUse()) {
6513 // Otherwise strength reduce the shift into an and.
6514 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6515 Constant *Mask =
6516 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6517
6518 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006519 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006520 Mask, LHSI->getName()+".mask");
6521 Value *And = InsertNewInstBefore(AndI, ICI);
6522 return new ICmpInst(ICI.getPredicate(), And,
6523 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6524 }
6525 }
6526
6527 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6528 bool TrueIfSigned = false;
6529 if (LHSI->hasOneUse() &&
6530 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6531 // (X << 31) <s 0 --> (X&1) != 0
6532 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6533 (TypeBits-ShAmt->getZExtValue()-1));
6534 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006535 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006536 Mask, LHSI->getName()+".mask");
6537 Value *And = InsertNewInstBefore(AndI, ICI);
6538
6539 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6540 And, Constant::getNullValue(And->getType()));
6541 }
6542 break;
6543 }
6544
6545 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6546 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006547 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006548 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006549 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006550
Chris Lattner5ee84f82008-03-21 05:19:58 +00006551 // Check that the shift amount is in range. If not, don't perform
6552 // undefined shifts. When the shift is visited it will be
6553 // simplified.
6554 uint32_t TypeBits = RHSV.getBitWidth();
6555 if (ShAmt->uge(TypeBits))
6556 break;
6557
6558 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006559
Chris Lattner5ee84f82008-03-21 05:19:58 +00006560 // If we are comparing against bits always shifted out, the
6561 // comparison cannot succeed.
6562 APInt Comp = RHSV << ShAmtVal;
6563 if (LHSI->getOpcode() == Instruction::LShr)
6564 Comp = Comp.lshr(ShAmtVal);
6565 else
6566 Comp = Comp.ashr(ShAmtVal);
6567
6568 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6569 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6570 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6571 return ReplaceInstUsesWith(ICI, Cst);
6572 }
6573
6574 // Otherwise, check to see if the bits shifted out are known to be zero.
6575 // If so, we can compare against the unshifted value:
6576 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006577 if (LHSI->hasOneUse() &&
6578 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006579 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6580 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6581 ConstantExpr::getShl(RHS, ShAmt));
6582 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006583
Evan Chengfb9292a2008-04-23 00:38:06 +00006584 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006585 // Otherwise strength reduce the shift into an and.
6586 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6587 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006588
Chris Lattner5ee84f82008-03-21 05:19:58 +00006589 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006590 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006591 Mask, LHSI->getName()+".mask");
6592 Value *And = InsertNewInstBefore(AndI, ICI);
6593 return new ICmpInst(ICI.getPredicate(), And,
6594 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006595 }
6596 break;
6597 }
6598
6599 case Instruction::SDiv:
6600 case Instruction::UDiv:
6601 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6602 // Fold this div into the comparison, producing a range check.
6603 // Determine, based on the divide type, what the range is being
6604 // checked. If there is an overflow on the low or high side, remember
6605 // it, otherwise compute the range [low, hi) bounding the new value.
6606 // See: InsertRangeTest above for the kinds of replacements possible.
6607 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6608 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6609 DivRHS))
6610 return R;
6611 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006612
6613 case Instruction::Add:
6614 // Fold: icmp pred (add, X, C1), C2
6615
6616 if (!ICI.isEquality()) {
6617 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6618 if (!LHSC) break;
6619 const APInt &LHSV = LHSC->getValue();
6620
6621 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6622 .subtract(LHSV);
6623
6624 if (ICI.isSignedPredicate()) {
6625 if (CR.getLower().isSignBit()) {
6626 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6627 ConstantInt::get(CR.getUpper()));
6628 } else if (CR.getUpper().isSignBit()) {
6629 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6630 ConstantInt::get(CR.getLower()));
6631 }
6632 } else {
6633 if (CR.getLower().isMinValue()) {
6634 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6635 ConstantInt::get(CR.getUpper()));
6636 } else if (CR.getUpper().isMinValue()) {
6637 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6638 ConstantInt::get(CR.getLower()));
6639 }
6640 }
6641 }
6642 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006643 }
6644
6645 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6646 if (ICI.isEquality()) {
6647 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6648
6649 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6650 // the second operand is a constant, simplify a bit.
6651 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6652 switch (BO->getOpcode()) {
6653 case Instruction::SRem:
6654 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6655 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6656 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6657 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6658 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00006659 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006660 BO->getName());
6661 InsertNewInstBefore(NewRem, ICI);
6662 return new ICmpInst(ICI.getPredicate(), NewRem,
6663 Constant::getNullValue(BO->getType()));
6664 }
6665 }
6666 break;
6667 case Instruction::Add:
6668 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6669 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6670 if (BO->hasOneUse())
6671 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6672 Subtract(RHS, BOp1C));
6673 } else if (RHSV == 0) {
6674 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6675 // efficiently invertible, or if the add has just this one use.
6676 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6677
6678 if (Value *NegVal = dyn_castNegVal(BOp1))
6679 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6680 else if (Value *NegVal = dyn_castNegVal(BOp0))
6681 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6682 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006683 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006684 InsertNewInstBefore(Neg, ICI);
6685 Neg->takeName(BO);
6686 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6687 }
6688 }
6689 break;
6690 case Instruction::Xor:
6691 // For the xor case, we can xor two constants together, eliminating
6692 // the explicit xor.
6693 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6694 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6695 ConstantExpr::getXor(RHS, BOC));
6696
6697 // FALLTHROUGH
6698 case Instruction::Sub:
6699 // Replace (([sub|xor] A, B) != 0) with (A != B)
6700 if (RHSV == 0)
6701 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6702 BO->getOperand(1));
6703 break;
6704
6705 case Instruction::Or:
6706 // If bits are being or'd in that are not present in the constant we
6707 // are comparing against, then the comparison could never succeed!
6708 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6709 Constant *NotCI = ConstantExpr::getNot(RHS);
6710 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6711 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6712 isICMP_NE));
6713 }
6714 break;
6715
6716 case Instruction::And:
6717 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6718 // If bits are being compared against that are and'd out, then the
6719 // comparison can never succeed!
6720 if ((RHSV & ~BOC->getValue()) != 0)
6721 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6722 isICMP_NE));
6723
6724 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6725 if (RHS == BOC && RHSV.isPowerOf2())
6726 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6727 ICmpInst::ICMP_NE, LHSI,
6728 Constant::getNullValue(RHS->getType()));
6729
6730 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00006731 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006732 Value *X = BO->getOperand(0);
6733 Constant *Zero = Constant::getNullValue(X->getType());
6734 ICmpInst::Predicate pred = isICMP_NE ?
6735 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6736 return new ICmpInst(pred, X, Zero);
6737 }
6738
6739 // ((X & ~7) == 0) --> X < 8
6740 if (RHSV == 0 && isHighOnes(BOC)) {
6741 Value *X = BO->getOperand(0);
6742 Constant *NegX = ConstantExpr::getNeg(BOC);
6743 ICmpInst::Predicate pred = isICMP_NE ?
6744 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6745 return new ICmpInst(pred, X, NegX);
6746 }
6747 }
6748 default: break;
6749 }
6750 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6751 // Handle icmp {eq|ne} <intrinsic>, intcst.
6752 if (II->getIntrinsicID() == Intrinsic::bswap) {
6753 AddToWorkList(II);
6754 ICI.setOperand(0, II->getOperand(1));
6755 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6756 return &ICI;
6757 }
6758 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006759 }
6760 return 0;
6761}
6762
6763/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6764/// We only handle extending casts so far.
6765///
6766Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6767 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6768 Value *LHSCIOp = LHSCI->getOperand(0);
6769 const Type *SrcTy = LHSCIOp->getType();
6770 const Type *DestTy = LHSCI->getType();
6771 Value *RHSCIOp;
6772
6773 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6774 // integer type is the same size as the pointer type.
6775 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6776 getTargetData().getPointerSizeInBits() ==
6777 cast<IntegerType>(DestTy)->getBitWidth()) {
6778 Value *RHSOp = 0;
6779 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6780 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6781 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6782 RHSOp = RHSC->getOperand(0);
6783 // If the pointer types don't match, insert a bitcast.
6784 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006785 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006786 }
6787
6788 if (RHSOp)
6789 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6790 }
6791
6792 // The code below only handles extension cast instructions, so far.
6793 // Enforce this.
6794 if (LHSCI->getOpcode() != Instruction::ZExt &&
6795 LHSCI->getOpcode() != Instruction::SExt)
6796 return 0;
6797
6798 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6799 bool isSignedCmp = ICI.isSignedPredicate();
6800
6801 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6802 // Not an extension from the same type?
6803 RHSCIOp = CI->getOperand(0);
6804 if (RHSCIOp->getType() != LHSCIOp->getType())
6805 return 0;
6806
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006807 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006808 // and the other is a zext), then we can't handle this.
6809 if (CI->getOpcode() != LHSCI->getOpcode())
6810 return 0;
6811
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006812 // Deal with equality cases early.
6813 if (ICI.isEquality())
6814 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6815
6816 // A signed comparison of sign extended values simplifies into a
6817 // signed comparison.
6818 if (isSignedCmp && isSignedExt)
6819 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6820
6821 // The other three cases all fold into an unsigned comparison.
6822 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006823 }
6824
6825 // If we aren't dealing with a constant on the RHS, exit early
6826 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6827 if (!CI)
6828 return 0;
6829
6830 // Compute the constant that would happen if we truncated to SrcTy then
6831 // reextended to DestTy.
6832 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6833 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6834
6835 // If the re-extended constant didn't change...
6836 if (Res2 == CI) {
6837 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6838 // For example, we might have:
6839 // %A = sext short %X to uint
6840 // %B = icmp ugt uint %A, 1330
6841 // It is incorrect to transform this into
6842 // %B = icmp ugt short %X, 1330
6843 // because %A may have negative value.
6844 //
Chris Lattner3d816532008-07-11 04:09:09 +00006845 // However, we allow this when the compare is EQ/NE, because they are
6846 // signless.
6847 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006848 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00006849 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006850 }
6851
6852 // The re-extended constant changed so the constant cannot be represented
6853 // in the shorter type. Consequently, we cannot emit a simple comparison.
6854
6855 // First, handle some easy cases. We know the result cannot be equal at this
6856 // point so handle the ICI.isEquality() cases
6857 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6858 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6859 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6860 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6861
6862 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6863 // should have been folded away previously and not enter in here.
6864 Value *Result;
6865 if (isSignedCmp) {
6866 // We're performing a signed comparison.
6867 if (cast<ConstantInt>(CI)->getValue().isNegative())
6868 Result = ConstantInt::getFalse(); // X < (small) --> false
6869 else
6870 Result = ConstantInt::getTrue(); // X < (large) --> true
6871 } else {
6872 // We're performing an unsigned comparison.
6873 if (isSignedExt) {
6874 // We're performing an unsigned comp with a sign extended value.
6875 // This is true if the input is >= 0. [aka >s -1]
6876 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6877 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6878 NegOne, ICI.getName()), ICI);
6879 } else {
6880 // Unsigned extend & unsigned compare -> always true.
6881 Result = ConstantInt::getTrue();
6882 }
6883 }
6884
6885 // Finally, return the value computed.
6886 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00006887 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006888 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00006889
6890 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6891 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6892 "ICmp should be folded!");
6893 if (Constant *CI = dyn_cast<Constant>(Result))
6894 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6895 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006896}
6897
6898Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6899 return commonShiftTransforms(I);
6900}
6901
6902Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6903 return commonShiftTransforms(I);
6904}
6905
6906Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00006907 if (Instruction *R = commonShiftTransforms(I))
6908 return R;
6909
6910 Value *Op0 = I.getOperand(0);
6911
6912 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6913 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6914 if (CSI->isAllOnesValue())
6915 return ReplaceInstUsesWith(I, CSI);
6916
6917 // See if we can turn a signed shr into an unsigned shr.
Nate Begemanbb1ce942008-07-29 15:49:41 +00006918 if (!isa<VectorType>(I.getType()) &&
6919 MaskedValueIsZero(Op0,
Chris Lattnere3c504f2007-12-06 01:59:46 +00006920 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greifa645dd32008-05-16 19:29:10 +00006921 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattnere3c504f2007-12-06 01:59:46 +00006922
6923 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006924}
6925
6926Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6927 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6928 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6929
6930 // shl X, 0 == X and shr X, 0 == X
6931 // shl 0, X == 0 and shr 0, X == 0
6932 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6933 Op0 == Constant::getNullValue(Op0->getType()))
6934 return ReplaceInstUsesWith(I, Op0);
6935
6936 if (isa<UndefValue>(Op0)) {
6937 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6938 return ReplaceInstUsesWith(I, Op0);
6939 else // undef << X -> 0, undef >>u X -> 0
6940 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6941 }
6942 if (isa<UndefValue>(Op1)) {
6943 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6944 return ReplaceInstUsesWith(I, Op0);
6945 else // X << undef, X >>u undef -> 0
6946 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6947 }
6948
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006949 // Try to fold constant and into select arguments.
6950 if (isa<Constant>(Op0))
6951 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6952 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6953 return R;
6954
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006955 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6956 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6957 return Res;
6958 return 0;
6959}
6960
6961Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6962 BinaryOperator &I) {
6963 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6964
6965 // See if we can simplify any instructions used by the instruction whose sole
6966 // purpose is to compute bits we don't care about.
6967 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +00006968 if (SimplifyDemandedInstructionBits(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006969 return &I;
6970
6971 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6972 // of a signed value.
6973 //
6974 if (Op1->uge(TypeBits)) {
6975 if (I.getOpcode() != Instruction::AShr)
6976 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6977 else {
6978 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6979 return &I;
6980 }
6981 }
6982
6983 // ((X*C1) << C2) == (X * (C1 << C2))
6984 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6985 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6986 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00006987 return BinaryOperator::CreateMul(BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006988 ConstantExpr::getShl(BOOp, Op1));
6989
6990 // Try to fold constant and into select arguments.
6991 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6992 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6993 return R;
6994 if (isa<PHINode>(Op0))
6995 if (Instruction *NV = FoldOpIntoPhi(I))
6996 return NV;
6997
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006998 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6999 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7000 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7001 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7002 // place. Don't try to do this transformation in this case. Also, we
7003 // require that the input operand is a shift-by-constant so that we have
7004 // confidence that the shifts will get folded together. We could do this
7005 // xform in more cases, but it is unlikely to be profitable.
7006 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7007 isa<ConstantInt>(TrOp->getOperand(1))) {
7008 // Okay, we'll do this xform. Make the shift of shift.
7009 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00007010 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007011 I.getName());
7012 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7013
7014 // For logical shifts, the truncation has the effect of making the high
7015 // part of the register be zeros. Emulate this by inserting an AND to
7016 // clear the top bits as needed. This 'and' will usually be zapped by
7017 // other xforms later if dead.
7018 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7019 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7020 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7021
7022 // The mask we constructed says what the trunc would do if occurring
7023 // between the shifts. We want to know the effect *after* the second
7024 // shift. We know that it is a logical shift by a constant, so adjust the
7025 // mask as appropriate.
7026 if (I.getOpcode() == Instruction::Shl)
7027 MaskV <<= Op1->getZExtValue();
7028 else {
7029 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7030 MaskV = MaskV.lshr(Op1->getZExtValue());
7031 }
7032
Gabor Greifa645dd32008-05-16 19:29:10 +00007033 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007034 TI->getName());
7035 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7036
7037 // Return the value truncated to the interesting size.
7038 return new TruncInst(And, I.getType());
7039 }
7040 }
7041
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007042 if (Op0->hasOneUse()) {
7043 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7044 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7045 Value *V1, *V2;
7046 ConstantInt *CC;
7047 switch (Op0BO->getOpcode()) {
7048 default: break;
7049 case Instruction::Add:
7050 case Instruction::And:
7051 case Instruction::Or:
7052 case Instruction::Xor: {
7053 // These operators commute.
7054 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7055 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattner3b874082008-11-16 05:38:51 +00007056 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greifa645dd32008-05-16 19:29:10 +00007057 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007058 Op0BO->getOperand(0), Op1,
7059 Op0BO->getName());
7060 InsertNewInstBefore(YS, I); // (Y << C)
7061 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007062 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007063 Op0BO->getOperand(1)->getName());
7064 InsertNewInstBefore(X, I); // (X + (Y << C))
7065 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00007066 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007067 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7068 }
7069
7070 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7071 Value *Op0BOOp1 = Op0BO->getOperand(1);
7072 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7073 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007074 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7075 m_ConstantInt(CC))) &&
7076 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007077 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007078 Op0BO->getOperand(0), Op1,
7079 Op0BO->getName());
7080 InsertNewInstBefore(YS, I); // (Y << C)
7081 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00007082 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007083 V1->getName()+".mask");
7084 InsertNewInstBefore(XM, I); // X & (CC << C)
7085
Gabor Greifa645dd32008-05-16 19:29:10 +00007086 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007087 }
7088 }
7089
7090 // FALL THROUGH.
7091 case Instruction::Sub: {
7092 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7093 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattner3b874082008-11-16 05:38:51 +00007094 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greifa645dd32008-05-16 19:29:10 +00007095 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007096 Op0BO->getOperand(1), Op1,
7097 Op0BO->getName());
7098 InsertNewInstBefore(YS, I); // (Y << C)
7099 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007100 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007101 Op0BO->getOperand(0)->getName());
7102 InsertNewInstBefore(X, I); // (X + (Y << C))
7103 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00007104 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007105 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7106 }
7107
7108 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7109 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7110 match(Op0BO->getOperand(0),
7111 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7112 m_ConstantInt(CC))) && V2 == Op1 &&
7113 cast<BinaryOperator>(Op0BO->getOperand(0))
7114 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007115 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007116 Op0BO->getOperand(1), Op1,
7117 Op0BO->getName());
7118 InsertNewInstBefore(YS, I); // (Y << C)
7119 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00007120 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007121 V1->getName()+".mask");
7122 InsertNewInstBefore(XM, I); // X & (CC << C)
7123
Gabor Greifa645dd32008-05-16 19:29:10 +00007124 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007125 }
7126
7127 break;
7128 }
7129 }
7130
7131
7132 // If the operand is an bitwise operator with a constant RHS, and the
7133 // shift is the only use, we can pull it out of the shift.
7134 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7135 bool isValid = true; // Valid only for And, Or, Xor
7136 bool highBitSet = false; // Transform if high bit of constant set?
7137
7138 switch (Op0BO->getOpcode()) {
7139 default: isValid = false; break; // Do not perform transform!
7140 case Instruction::Add:
7141 isValid = isLeftShift;
7142 break;
7143 case Instruction::Or:
7144 case Instruction::Xor:
7145 highBitSet = false;
7146 break;
7147 case Instruction::And:
7148 highBitSet = true;
7149 break;
7150 }
7151
7152 // If this is a signed shift right, and the high bit is modified
7153 // by the logical operation, do not perform the transformation.
7154 // The highBitSet boolean indicates the value of the high bit of
7155 // the constant which would cause it to be modified for this
7156 // operation.
7157 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007158 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007159 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007160
7161 if (isValid) {
7162 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7163
7164 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007165 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007166 InsertNewInstBefore(NewShift, I);
7167 NewShift->takeName(Op0BO);
7168
Gabor Greifa645dd32008-05-16 19:29:10 +00007169 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007170 NewRHS);
7171 }
7172 }
7173 }
7174 }
7175
7176 // Find out if this is a shift of a shift by a constant.
7177 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7178 if (ShiftOp && !ShiftOp->isShift())
7179 ShiftOp = 0;
7180
7181 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7182 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7183 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7184 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7185 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7186 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7187 Value *X = ShiftOp->getOperand(0);
7188
7189 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7190 if (AmtSum > TypeBits)
7191 AmtSum = TypeBits;
7192
7193 const IntegerType *Ty = cast<IntegerType>(I.getType());
7194
7195 // Check for (X << c1) << c2 and (X >> c1) >> c2
7196 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007197 return BinaryOperator::Create(I.getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007198 ConstantInt::get(Ty, AmtSum));
7199 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7200 I.getOpcode() == Instruction::AShr) {
7201 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greifa645dd32008-05-16 19:29:10 +00007202 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007203 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7204 I.getOpcode() == Instruction::LShr) {
7205 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7206 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007207 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007208 InsertNewInstBefore(Shift, I);
7209
7210 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007211 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007212 }
7213
7214 // Okay, if we get here, one shift must be left, and the other shift must be
7215 // right. See if the amounts are equal.
7216 if (ShiftAmt1 == ShiftAmt2) {
7217 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7218 if (I.getOpcode() == Instruction::Shl) {
7219 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00007220 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007221 }
7222 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7223 if (I.getOpcode() == Instruction::LShr) {
7224 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00007225 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007226 }
7227 // We can simplify ((X << C) >>s C) into a trunc + sext.
7228 // NOTE: we could do this for any C, but that would make 'unusual' integer
7229 // types. For now, just stick to ones well-supported by the code
7230 // generators.
7231 const Type *SExtType = 0;
7232 switch (Ty->getBitWidth() - ShiftAmt1) {
7233 case 1 :
7234 case 8 :
7235 case 16 :
7236 case 32 :
7237 case 64 :
7238 case 128:
7239 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7240 break;
7241 default: break;
7242 }
7243 if (SExtType) {
7244 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7245 InsertNewInstBefore(NewTrunc, I);
7246 return new SExtInst(NewTrunc, Ty);
7247 }
7248 // Otherwise, we can't handle it yet.
7249 } else if (ShiftAmt1 < ShiftAmt2) {
7250 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7251
7252 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7253 if (I.getOpcode() == Instruction::Shl) {
7254 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7255 ShiftOp->getOpcode() == Instruction::AShr);
7256 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007257 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007258 InsertNewInstBefore(Shift, I);
7259
7260 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007261 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007262 }
7263
7264 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7265 if (I.getOpcode() == Instruction::LShr) {
7266 assert(ShiftOp->getOpcode() == Instruction::Shl);
7267 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007268 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007269 InsertNewInstBefore(Shift, I);
7270
7271 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007272 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007273 }
7274
7275 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7276 } else {
7277 assert(ShiftAmt2 < ShiftAmt1);
7278 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7279
7280 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7281 if (I.getOpcode() == Instruction::Shl) {
7282 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7283 ShiftOp->getOpcode() == Instruction::AShr);
7284 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007285 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007286 ConstantInt::get(Ty, ShiftDiff));
7287 InsertNewInstBefore(Shift, I);
7288
7289 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007290 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007291 }
7292
7293 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7294 if (I.getOpcode() == Instruction::LShr) {
7295 assert(ShiftOp->getOpcode() == Instruction::Shl);
7296 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007297 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007298 InsertNewInstBefore(Shift, I);
7299
7300 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007301 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007302 }
7303
7304 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7305 }
7306 }
7307 return 0;
7308}
7309
7310
7311/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7312/// expression. If so, decompose it, returning some value X, such that Val is
7313/// X*Scale+Offset.
7314///
7315static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7316 int &Offset) {
7317 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7318 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7319 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007320 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007321 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007322 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7323 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7324 if (I->getOpcode() == Instruction::Shl) {
7325 // This is a value scaled by '1 << the shift amt'.
7326 Scale = 1U << RHS->getZExtValue();
7327 Offset = 0;
7328 return I->getOperand(0);
7329 } else if (I->getOpcode() == Instruction::Mul) {
7330 // This value is scaled by 'RHS'.
7331 Scale = RHS->getZExtValue();
7332 Offset = 0;
7333 return I->getOperand(0);
7334 } else if (I->getOpcode() == Instruction::Add) {
7335 // We have X+C. Check to see if we really have (X*C2)+C1,
7336 // where C1 is divisible by C2.
7337 unsigned SubScale;
7338 Value *SubVal =
7339 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7340 Offset += RHS->getZExtValue();
7341 Scale = SubScale;
7342 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007343 }
7344 }
7345 }
7346
7347 // Otherwise, we can't look past this.
7348 Scale = 1;
7349 Offset = 0;
7350 return Val;
7351}
7352
7353
7354/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7355/// try to eliminate the cast by moving the type information into the alloc.
7356Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7357 AllocationInst &AI) {
7358 const PointerType *PTy = cast<PointerType>(CI.getType());
7359
7360 // Remove any uses of AI that are dead.
7361 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7362
7363 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7364 Instruction *User = cast<Instruction>(*UI++);
7365 if (isInstructionTriviallyDead(User)) {
7366 while (UI != E && *UI == User)
7367 ++UI; // If this instruction uses AI more than once, don't break UI.
7368
7369 ++NumDeadInst;
7370 DOUT << "IC: DCE: " << *User;
7371 EraseInstFromFunction(*User);
7372 }
7373 }
7374
7375 // Get the type really allocated and the type casted to.
7376 const Type *AllocElTy = AI.getAllocatedType();
7377 const Type *CastElTy = PTy->getElementType();
7378 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7379
7380 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7381 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7382 if (CastElTyAlign < AllocElTyAlign) return 0;
7383
7384 // If the allocation has multiple uses, only promote it if we are strictly
7385 // increasing the alignment of the resultant allocation. If we keep it the
7386 // same, we open the door to infinite loops of various kinds.
7387 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7388
Duncan Sandsd68f13b2009-01-12 20:38:59 +00007389 uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7390 uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007391 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7392
7393 // See if we can satisfy the modulus by pulling a scale out of the array
7394 // size argument.
7395 unsigned ArraySizeScale;
7396 int ArrayOffset;
7397 Value *NumElements = // See if the array size is a decomposable linear expr.
7398 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7399
7400 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7401 // do the xform.
7402 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7403 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7404
7405 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7406 Value *Amt = 0;
7407 if (Scale == 1) {
7408 Amt = NumElements;
7409 } else {
7410 // If the allocation size is constant, form a constant mul expression
7411 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7412 if (isa<ConstantInt>(NumElements))
7413 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7414 // otherwise multiply the amount and the number of elements
7415 else if (Scale != 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007416 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007417 Amt = InsertNewInstBefore(Tmp, AI);
7418 }
7419 }
7420
7421 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7422 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007423 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007424 Amt = InsertNewInstBefore(Tmp, AI);
7425 }
7426
7427 AllocationInst *New;
7428 if (isa<MallocInst>(AI))
7429 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7430 else
7431 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7432 InsertNewInstBefore(New, AI);
7433 New->takeName(&AI);
7434
7435 // If the allocation has multiple uses, insert a cast and change all things
7436 // that used it to use the new cast. This will also hack on CI, but it will
7437 // die soon.
7438 if (!AI.hasOneUse()) {
7439 AddUsesToWorkList(AI);
7440 // New is the allocation instruction, pointer typed. AI is the original
7441 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7442 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7443 InsertNewInstBefore(NewCast, AI);
7444 AI.replaceAllUsesWith(NewCast);
7445 }
7446 return ReplaceInstUsesWith(CI, New);
7447}
7448
7449/// CanEvaluateInDifferentType - Return true if we can take the specified value
7450/// and return it as type Ty without inserting any new casts and without
7451/// changing the computed value. This is used by code that tries to decide
7452/// whether promoting or shrinking integer operations to wider or smaller types
7453/// will allow us to eliminate a truncate or extend.
7454///
7455/// This is a truncation operation if Ty is smaller than V->getType(), or an
7456/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007457///
7458/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7459/// should return true if trunc(V) can be computed by computing V in the smaller
7460/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7461/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7462/// efficiently truncated.
7463///
7464/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7465/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7466/// the final result.
Evan Cheng814a00c2009-01-16 02:11:43 +00007467bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7468 unsigned CastOpc,
7469 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007470 // We can always evaluate constants in another type.
7471 if (isa<ConstantInt>(V))
7472 return true;
7473
7474 Instruction *I = dyn_cast<Instruction>(V);
7475 if (!I) return false;
7476
7477 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7478
Chris Lattneref70bb82007-08-02 06:11:14 +00007479 // If this is an extension or truncate, we can often eliminate it.
7480 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7481 // If this is a cast from the destination type, we can trivially eliminate
7482 // it, and this will remove a cast overall.
7483 if (I->getOperand(0)->getType() == Ty) {
7484 // If the first operand is itself a cast, and is eliminable, do not count
7485 // this as an eliminable cast. We would prefer to eliminate those two
7486 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007487 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007488 ++NumCastsRemoved;
7489 return true;
7490 }
7491 }
7492
7493 // We can't extend or shrink something that has multiple uses: doing so would
7494 // require duplicating the instruction in general, which isn't profitable.
7495 if (!I->hasOneUse()) return false;
7496
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007497 unsigned Opc = I->getOpcode();
7498 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007499 case Instruction::Add:
7500 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007501 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007502 case Instruction::And:
7503 case Instruction::Or:
7504 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007505 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007506 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007507 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007508 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007509 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007510
7511 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007512 // If we are truncating the result of this SHL, and if it's a shift of a
7513 // constant amount, we can always perform a SHL in a smaller type.
7514 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7515 uint32_t BitWidth = Ty->getBitWidth();
7516 if (BitWidth < OrigTy->getBitWidth() &&
7517 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007518 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007519 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007520 }
7521 break;
7522 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007523 // If this is a truncate of a logical shr, we can truncate it to a smaller
7524 // lshr iff we know that the bits we would otherwise be shifting in are
7525 // already zeros.
7526 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7527 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7528 uint32_t BitWidth = Ty->getBitWidth();
7529 if (BitWidth < OrigBitWidth &&
7530 MaskedValueIsZero(I->getOperand(0),
7531 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7532 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007533 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007534 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007535 }
7536 }
7537 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007538 case Instruction::ZExt:
7539 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007540 case Instruction::Trunc:
7541 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007542 // can safely replace it. Note that replacing it does not reduce the number
7543 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007544 if (Opc == CastOpc)
7545 return true;
7546
7547 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00007548 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007549 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007550 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007551 case Instruction::Select: {
7552 SelectInst *SI = cast<SelectInst>(I);
7553 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007554 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007555 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007556 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007557 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007558 case Instruction::PHI: {
7559 // We can change a phi if we can change all operands.
7560 PHINode *PN = cast<PHINode>(I);
7561 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7562 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007563 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00007564 return false;
7565 return true;
7566 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007567 default:
7568 // TODO: Can handle more cases here.
7569 break;
7570 }
7571
7572 return false;
7573}
7574
7575/// EvaluateInDifferentType - Given an expression that
7576/// CanEvaluateInDifferentType returns true for, actually insert the code to
7577/// evaluate the expression.
7578Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7579 bool isSigned) {
7580 if (Constant *C = dyn_cast<Constant>(V))
7581 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7582
7583 // Otherwise, it must be an instruction.
7584 Instruction *I = cast<Instruction>(V);
7585 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007586 unsigned Opc = I->getOpcode();
7587 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007588 case Instruction::Add:
7589 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007590 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007591 case Instruction::And:
7592 case Instruction::Or:
7593 case Instruction::Xor:
7594 case Instruction::AShr:
7595 case Instruction::LShr:
7596 case Instruction::Shl: {
7597 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7598 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007599 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007600 break;
7601 }
7602 case Instruction::Trunc:
7603 case Instruction::ZExt:
7604 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007605 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007606 // just return the source. There's no need to insert it because it is not
7607 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007608 if (I->getOperand(0)->getType() == Ty)
7609 return I->getOperand(0);
7610
Chris Lattner4200c2062008-06-18 04:00:49 +00007611 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007612 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00007613 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00007614 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007615 case Instruction::Select: {
7616 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7617 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7618 Res = SelectInst::Create(I->getOperand(0), True, False);
7619 break;
7620 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007621 case Instruction::PHI: {
7622 PHINode *OPN = cast<PHINode>(I);
7623 PHINode *NPN = PHINode::Create(Ty);
7624 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7625 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7626 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7627 }
7628 Res = NPN;
7629 break;
7630 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007631 default:
7632 // TODO: Can handle more cases here.
7633 assert(0 && "Unreachable!");
7634 break;
7635 }
7636
Chris Lattner4200c2062008-06-18 04:00:49 +00007637 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007638 return InsertNewInstBefore(Res, *I);
7639}
7640
7641/// @brief Implement the transforms common to all CastInst visitors.
7642Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7643 Value *Src = CI.getOperand(0);
7644
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007645 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7646 // eliminate it now.
7647 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7648 if (Instruction::CastOps opc =
7649 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7650 // The first cast (CSrc) is eliminable so we need to fix up or replace
7651 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00007652 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007653 }
7654 }
7655
7656 // If we are casting a select then fold the cast into the select
7657 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7658 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7659 return NV;
7660
7661 // If we are casting a PHI then fold the cast into the PHI
7662 if (isa<PHINode>(Src))
7663 if (Instruction *NV = FoldOpIntoPhi(CI))
7664 return NV;
7665
7666 return 0;
7667}
7668
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007669/// FindElementAtOffset - Given a type and a constant offset, determine whether
7670/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00007671/// the specified offset. If so, fill them into NewIndices and return the
7672/// resultant element type, otherwise return null.
7673static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7674 SmallVectorImpl<Value*> &NewIndices,
7675 const TargetData *TD) {
7676 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007677
7678 // Start with the index over the outer type. Note that the type size
7679 // might be zero (even if the offset isn't zero) if the indexed type
7680 // is something like [0 x {int, int}]
7681 const Type *IntPtrTy = TD->getIntPtrType();
7682 int64_t FirstIdx = 0;
Duncan Sandsd68f13b2009-01-12 20:38:59 +00007683 if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007684 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00007685 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007686
Chris Lattnerce48c462009-01-11 20:15:20 +00007687 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007688 if (Offset < 0) {
7689 --FirstIdx;
7690 Offset += TySize;
7691 assert(Offset >= 0);
7692 }
7693 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7694 }
7695
7696 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7697
7698 // Index into the types. If we fail, set OrigBase to null.
7699 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00007700 // Indexing into tail padding between struct/array elements.
7701 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00007702 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00007703
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007704 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7705 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00007706 assert(Offset < (int64_t)SL->getSizeInBytes() &&
7707 "Offset must stay within the indexed type");
7708
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007709 unsigned Elt = SL->getElementContainingOffset(Offset);
7710 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7711
7712 Offset -= SL->getElementOffset(Elt);
7713 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00007714 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsd68f13b2009-01-12 20:38:59 +00007715 uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00007716 assert(EltSize && "Cannot index into a zero-sized array");
7717 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7718 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00007719 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007720 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00007721 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00007722 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007723 }
7724 }
7725
Chris Lattner54dddc72009-01-24 01:00:13 +00007726 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007727}
7728
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007729/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7730Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7731 Value *Src = CI.getOperand(0);
7732
7733 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7734 // If casting the result of a getelementptr instruction with no offset, turn
7735 // this into a cast of the original pointer!
7736 if (GEP->hasAllZeroIndices()) {
7737 // Changing the cast operand is usually not a good idea but it is safe
7738 // here because the pointer operand is being replaced with another
7739 // pointer operand so the opcode doesn't need to change.
7740 AddToWorkList(GEP);
7741 CI.setOperand(0, GEP->getOperand(0));
7742 return &CI;
7743 }
7744
7745 // If the GEP has a single use, and the base pointer is a bitcast, and the
7746 // GEP computes a constant offset, see if we can convert these three
7747 // instructions into fewer. This typically happens with unions and other
7748 // non-type-safe code.
7749 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7750 if (GEP->hasAllConstantIndices()) {
7751 // We are guaranteed to get a constant from EmitGEPOffset.
7752 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7753 int64_t Offset = OffsetV->getSExtValue();
7754
7755 // Get the base pointer input of the bitcast, and the type it points to.
7756 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7757 const Type *GEPIdxTy =
7758 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007759 SmallVector<Value*, 8> NewIndices;
7760 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7761 // If we were able to index down into an element, create the GEP
7762 // and bitcast the result. This eliminates one bitcast, potentially
7763 // two.
7764 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7765 NewIndices.begin(),
7766 NewIndices.end(), "");
7767 InsertNewInstBefore(NGEP, CI);
7768 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007769
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007770 if (isa<BitCastInst>(CI))
7771 return new BitCastInst(NGEP, CI.getType());
7772 assert(isa<PtrToIntInst>(CI));
7773 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007774 }
7775 }
7776 }
7777 }
7778
7779 return commonCastTransforms(CI);
7780}
7781
7782
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007783/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7784/// integer types. This function implements the common transforms for all those
7785/// cases.
7786/// @brief Implement the transforms common to CastInst with integer operands
7787Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7788 if (Instruction *Result = commonCastTransforms(CI))
7789 return Result;
7790
7791 Value *Src = CI.getOperand(0);
7792 const Type *SrcTy = Src->getType();
7793 const Type *DestTy = CI.getType();
7794 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7795 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7796
7797 // See if we can simplify any instructions used by the LHS whose sole
7798 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00007799 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007800 return &CI;
7801
7802 // If the source isn't an instruction or has more than one use then we
7803 // can't do anything more.
7804 Instruction *SrcI = dyn_cast<Instruction>(Src);
7805 if (!SrcI || !Src->hasOneUse())
7806 return 0;
7807
7808 // Attempt to propagate the cast into the instruction for int->int casts.
7809 int NumCastsRemoved = 0;
7810 if (!isa<BitCastInst>(CI) &&
7811 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Evan Cheng814a00c2009-01-16 02:11:43 +00007812 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007813 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00007814 // eliminates the cast, so it is always a win. If this is a zero-extension,
7815 // we need to do an AND to maintain the clear top-part of the computation,
7816 // so we require that the input have eliminated at least one cast. If this
7817 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007818 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007819 bool DoXForm = false;
7820 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007821 switch (CI.getOpcode()) {
7822 default:
7823 // All the others use floating point so we shouldn't actually
7824 // get here because of the check above.
7825 assert(0 && "Unknown cast type");
7826 case Instruction::Trunc:
7827 DoXForm = true;
7828 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00007829 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007830 DoXForm = NumCastsRemoved >= 1;
Evan Cheng814a00c2009-01-16 02:11:43 +00007831 if (!DoXForm) {
7832 // If it's unnecessary to issue an AND to clear the high bits, it's
7833 // always profitable to do this xform.
7834 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy,
7835 CI.getOpcode() == Instruction::SExt);
7836 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7837 if (MaskedValueIsZero(TryRes, Mask))
7838 return ReplaceInstUsesWith(CI, TryRes);
7839 else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7840 if (TryI->use_empty())
7841 EraseInstFromFunction(*TryI);
7842 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007843 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00007844 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007845 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007846 DoXForm = NumCastsRemoved >= 2;
Evan Cheng814a00c2009-01-16 02:11:43 +00007847 if (!DoXForm && !isa<TruncInst>(SrcI)) {
7848 // If we do not have to emit the truncate + sext pair, then it's always
7849 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007850 //
7851 // It's not safe to eliminate the trunc + sext pair if one of the
7852 // eliminated cast is a truncate. e.g.
7853 // t2 = trunc i32 t1 to i16
7854 // t3 = sext i16 t2 to i32
7855 // !=
7856 // i32 t1
Evan Cheng814a00c2009-01-16 02:11:43 +00007857 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy,
7858 CI.getOpcode() == Instruction::SExt);
7859 unsigned NumSignBits = ComputeNumSignBits(TryRes);
7860 if (NumSignBits > (DestBitSize - SrcBitSize))
7861 return ReplaceInstUsesWith(CI, TryRes);
7862 else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7863 if (TryI->use_empty())
7864 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007865 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007866 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007867 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007868 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007869
7870 if (DoXForm) {
7871 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7872 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00007873 if (JustReplace)
7874 // Just replace this cast with the result.
7875 return ReplaceInstUsesWith(CI, Res);
7876
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007877 assert(Res->getType() == DestTy);
7878 switch (CI.getOpcode()) {
7879 default: assert(0 && "Unknown cast type!");
7880 case Instruction::Trunc:
7881 case Instruction::BitCast:
7882 // Just replace this cast with the result.
7883 return ReplaceInstUsesWith(CI, Res);
7884 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007885 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00007886
7887 // If the high bits are already zero, just replace this cast with the
7888 // result.
7889 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7890 if (MaskedValueIsZero(Res, Mask))
7891 return ReplaceInstUsesWith(CI, Res);
7892
7893 // We need to emit an AND to clear the high bits.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007894 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7895 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00007896 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007897 }
Evan Cheng814a00c2009-01-16 02:11:43 +00007898 case Instruction::SExt: {
7899 // If the high bits are already filled with sign bit, just replace this
7900 // cast with the result.
7901 unsigned NumSignBits = ComputeNumSignBits(Res);
7902 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007903 return ReplaceInstUsesWith(CI, Res);
7904
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007905 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00007906 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007907 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7908 CI), DestTy);
7909 }
Evan Cheng814a00c2009-01-16 02:11:43 +00007910 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007911 }
7912 }
7913
7914 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7915 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7916
7917 switch (SrcI->getOpcode()) {
7918 case Instruction::Add:
7919 case Instruction::Mul:
7920 case Instruction::And:
7921 case Instruction::Or:
7922 case Instruction::Xor:
7923 // If we are discarding information, rewrite.
7924 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7925 // Don't insert two casts if they cannot be eliminated. We allow
7926 // two casts to be inserted if the sizes are the same. This could
7927 // only be converting signedness, which is a noop.
7928 if (DestBitSize == SrcBitSize ||
7929 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7930 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7931 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedman722b4792008-11-30 21:09:11 +00007932 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7933 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007934 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007935 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7936 }
7937 }
7938
7939 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7940 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7941 SrcI->getOpcode() == Instruction::Xor &&
7942 Op1 == ConstantInt::getTrue() &&
7943 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedman722b4792008-11-30 21:09:11 +00007944 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007945 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007946 }
7947 break;
7948 case Instruction::SDiv:
7949 case Instruction::UDiv:
7950 case Instruction::SRem:
7951 case Instruction::URem:
7952 // If we are just changing the sign, rewrite.
7953 if (DestBitSize == SrcBitSize) {
7954 // Don't insert two casts if they cannot be eliminated. We allow
7955 // two casts to be inserted if the sizes are the same. This could
7956 // only be converting signedness, which is a noop.
7957 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7958 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman722b4792008-11-30 21:09:11 +00007959 Value *Op0c = InsertCastBefore(Instruction::BitCast,
7960 Op0, DestTy, *SrcI);
7961 Value *Op1c = InsertCastBefore(Instruction::BitCast,
7962 Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007963 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007964 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7965 }
7966 }
7967 break;
7968
7969 case Instruction::Shl:
7970 // Allow changing the sign of the source operand. Do not allow
7971 // changing the size of the shift, UNLESS the shift amount is a
7972 // constant. We must not change variable sized shifts to a smaller
7973 // size, because it is undefined to shift more bits out than exist
7974 // in the value.
7975 if (DestBitSize == SrcBitSize ||
7976 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7977 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7978 Instruction::BitCast : Instruction::Trunc);
Eli Friedman722b4792008-11-30 21:09:11 +00007979 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7980 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007981 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007982 }
7983 break;
7984 case Instruction::AShr:
7985 // If this is a signed shr, and if all bits shifted in are about to be
7986 // truncated off, turn it into an unsigned shr to allow greater
7987 // simplifications.
7988 if (DestBitSize < SrcBitSize &&
7989 isa<ConstantInt>(Op1)) {
7990 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7991 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7992 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00007993 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007994 }
7995 }
7996 break;
7997 }
7998 return 0;
7999}
8000
8001Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8002 if (Instruction *Result = commonIntCastTransforms(CI))
8003 return Result;
8004
8005 Value *Src = CI.getOperand(0);
8006 const Type *Ty = CI.getType();
8007 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8008 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8009
8010 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8011 switch (SrcI->getOpcode()) {
8012 default: break;
8013 case Instruction::LShr:
8014 // We can shrink lshr to something smaller if we know the bits shifted in
8015 // are already zeros.
8016 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
8017 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8018
8019 // Get a mask for the bits shifting in.
8020 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8021 Value* SrcIOp0 = SrcI->getOperand(0);
8022 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
8023 if (ShAmt >= DestBitWidth) // All zeros.
8024 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8025
8026 // Okay, we can shrink this. Truncate the input, then return a new
8027 // shift.
8028 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8029 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8030 Ty, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008031 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008032 }
8033 } else { // This is a variable shr.
8034
8035 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
8036 // more LLVM instructions, but allows '1 << Y' to be hoisted if
8037 // loop-invariant and CSE'd.
8038 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
8039 Value *One = ConstantInt::get(SrcI->getType(), 1);
8040
8041 Value *V = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00008042 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008043 "tmp"), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008044 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008045 SrcI->getOperand(0),
8046 "tmp"), CI);
8047 Value *Zero = Constant::getNullValue(V->getType());
8048 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
8049 }
8050 }
8051 break;
8052 }
8053 }
8054
8055 return 0;
8056}
8057
Evan Chenge3779cf2008-03-24 00:21:34 +00008058/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8059/// in order to eliminate the icmp.
8060Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8061 bool DoXform) {
8062 // If we are just checking for a icmp eq of a single bit and zext'ing it
8063 // to an integer, then shift the bit to the appropriate place and then
8064 // cast to integer to avoid the comparison.
8065 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8066 const APInt &Op1CV = Op1C->getValue();
8067
8068 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8069 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8070 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8071 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8072 if (!DoXform) return ICI;
8073
8074 Value *In = ICI->getOperand(0);
8075 Value *Sh = ConstantInt::get(In->getType(),
8076 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008077 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00008078 In->getName()+".lobit"),
8079 CI);
8080 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00008081 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00008082 false/*ZExt*/, "tmp", &CI);
8083
8084 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8085 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008086 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00008087 In->getName()+".not"),
8088 CI);
8089 }
8090
8091 return ReplaceInstUsesWith(CI, In);
8092 }
8093
8094
8095
8096 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8097 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8098 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8099 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8100 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8101 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8102 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8103 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8104 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8105 // This only works for EQ and NE
8106 ICI->isEquality()) {
8107 // If Op1C some other power of two, convert:
8108 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8109 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8110 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8111 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8112
8113 APInt KnownZeroMask(~KnownZero);
8114 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8115 if (!DoXform) return ICI;
8116
8117 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8118 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8119 // (X&4) == 2 --> false
8120 // (X&4) != 2 --> true
8121 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8122 Res = ConstantExpr::getZExt(Res, CI.getType());
8123 return ReplaceInstUsesWith(CI, Res);
8124 }
8125
8126 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8127 Value *In = ICI->getOperand(0);
8128 if (ShiftAmt) {
8129 // Perform a logical shr by shiftamt.
8130 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00008131 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chenge3779cf2008-03-24 00:21:34 +00008132 ConstantInt::get(In->getType(), ShiftAmt),
8133 In->getName()+".lobit"), CI);
8134 }
8135
8136 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8137 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008138 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008139 InsertNewInstBefore(cast<Instruction>(In), CI);
8140 }
8141
8142 if (CI.getType() == In->getType())
8143 return ReplaceInstUsesWith(CI, In);
8144 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008145 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008146 }
8147 }
8148 }
8149
8150 return 0;
8151}
8152
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008153Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8154 // If one of the common conversion will work ..
8155 if (Instruction *Result = commonIntCastTransforms(CI))
8156 return Result;
8157
8158 Value *Src = CI.getOperand(0);
8159
8160 // If this is a cast of a cast
8161 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8162 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8163 // types and if the sizes are just right we can convert this into a logical
8164 // 'and' which will be much cheaper than the pair of casts.
8165 if (isa<TruncInst>(CSrc)) {
8166 // Get the sizes of the types involved
8167 Value *A = CSrc->getOperand(0);
8168 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8169 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8170 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8171 // If we're actually extending zero bits and the trunc is a no-op
8172 if (MidSize < DstSize && SrcSize == DstSize) {
8173 // Replace both of the casts with an And of the type mask.
8174 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8175 Constant *AndConst = ConstantInt::get(AndValue);
8176 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00008177 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008178 // Unfortunately, if the type changed, we need to cast it back.
8179 if (And->getType() != CI.getType()) {
8180 And->setName(CSrc->getName()+".mask");
8181 InsertNewInstBefore(And, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008182 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008183 }
8184 return And;
8185 }
8186 }
8187 }
8188
Evan Chenge3779cf2008-03-24 00:21:34 +00008189 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8190 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008191
Evan Chenge3779cf2008-03-24 00:21:34 +00008192 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8193 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8194 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8195 // of the (zext icmp) will be transformed.
8196 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8197 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8198 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8199 (transformZExtICmp(LHS, CI, false) ||
8200 transformZExtICmp(RHS, CI, false))) {
8201 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8202 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008203 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008204 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008205 }
8206
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008207 return 0;
8208}
8209
8210Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8211 if (Instruction *I = commonIntCastTransforms(CI))
8212 return I;
8213
8214 Value *Src = CI.getOperand(0);
8215
Dan Gohman35b76162008-10-30 20:40:10 +00008216 // Canonicalize sign-extend from i1 to a select.
8217 if (Src->getType() == Type::Int1Ty)
8218 return SelectInst::Create(Src,
8219 ConstantInt::getAllOnesValue(CI.getType()),
8220 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008221
8222 // See if the value being truncated is already sign extended. If so, just
8223 // eliminate the trunc/sext pair.
8224 if (getOpcode(Src) == Instruction::Trunc) {
8225 Value *Op = cast<User>(Src)->getOperand(0);
8226 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8227 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8228 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8229 unsigned NumSignBits = ComputeNumSignBits(Op);
8230
8231 if (OpBits == DestBits) {
8232 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8233 // bits, it is already ready.
8234 if (NumSignBits > DestBits-MidBits)
8235 return ReplaceInstUsesWith(CI, Op);
8236 } else if (OpBits < DestBits) {
8237 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8238 // bits, just sext from i32.
8239 if (NumSignBits > OpBits-MidBits)
8240 return new SExtInst(Op, CI.getType(), "tmp");
8241 } else {
8242 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8243 // bits, just truncate to i32.
8244 if (NumSignBits > OpBits-MidBits)
8245 return new TruncInst(Op, CI.getType(), "tmp");
8246 }
8247 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008248
8249 // If the input is a shl/ashr pair of a same constant, then this is a sign
8250 // extension from a smaller value. If we could trust arbitrary bitwidth
8251 // integers, we could turn this into a truncate to the smaller bit and then
8252 // use a sext for the whole extension. Since we don't, look deeper and check
8253 // for a truncate. If the source and dest are the same type, eliminate the
8254 // trunc and extend and just do shifts. For example, turn:
8255 // %a = trunc i32 %i to i8
8256 // %b = shl i8 %a, 6
8257 // %c = ashr i8 %b, 6
8258 // %d = sext i8 %c to i32
8259 // into:
8260 // %a = shl i32 %i, 30
8261 // %d = ashr i32 %a, 30
8262 Value *A = 0;
8263 ConstantInt *BA = 0, *CA = 0;
8264 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8265 m_ConstantInt(CA))) &&
8266 BA == CA && isa<TruncInst>(A)) {
8267 Value *I = cast<TruncInst>(A)->getOperand(0);
8268 if (I->getType() == CI.getType()) {
8269 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8270 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8271 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8272 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8273 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8274 CI.getName()), CI);
8275 return BinaryOperator::CreateAShr(I, ShAmtV);
8276 }
8277 }
8278
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008279 return 0;
8280}
8281
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008282/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8283/// in the specified FP type without changing its value.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008284static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008285 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008286 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008287 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8288 if (!losesInfo)
Chris Lattner5e0610f2008-04-20 00:41:09 +00008289 return ConstantFP::get(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008290 return 0;
8291}
8292
8293/// LookThroughFPExtensions - If this is an fp extension instruction, look
8294/// through it until we get the source value.
8295static Value *LookThroughFPExtensions(Value *V) {
8296 if (Instruction *I = dyn_cast<Instruction>(V))
8297 if (I->getOpcode() == Instruction::FPExt)
8298 return LookThroughFPExtensions(I->getOperand(0));
8299
8300 // If this value is a constant, return the constant in the smallest FP type
8301 // that can accurately represent it. This allows us to turn
8302 // (float)((double)X+2.0) into x+2.0f.
8303 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8304 if (CFP->getType() == Type::PPC_FP128Ty)
8305 return V; // No constant folding of this.
8306 // See if the value can be truncated to float and then reextended.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008307 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008308 return V;
8309 if (CFP->getType() == Type::DoubleTy)
8310 return V; // Won't shrink.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008311 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008312 return V;
8313 // Don't try to shrink to various long double types.
8314 }
8315
8316 return V;
8317}
8318
8319Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8320 if (Instruction *I = commonCastTransforms(CI))
8321 return I;
8322
8323 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8324 // smaller than the destination type, we can eliminate the truncate by doing
8325 // the add as the smaller type. This applies to add/sub/mul/div as well as
8326 // many builtins (sqrt, etc).
8327 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8328 if (OpI && OpI->hasOneUse()) {
8329 switch (OpI->getOpcode()) {
8330 default: break;
8331 case Instruction::Add:
8332 case Instruction::Sub:
8333 case Instruction::Mul:
8334 case Instruction::FDiv:
8335 case Instruction::FRem:
8336 const Type *SrcTy = OpI->getType();
8337 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8338 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8339 if (LHSTrunc->getType() != SrcTy &&
8340 RHSTrunc->getType() != SrcTy) {
8341 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8342 // If the source types were both smaller than the destination type of
8343 // the cast, do this xform.
8344 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8345 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8346 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8347 CI.getType(), CI);
8348 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8349 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008350 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008351 }
8352 }
8353 break;
8354 }
8355 }
8356 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008357}
8358
8359Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8360 return commonCastTransforms(CI);
8361}
8362
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008363Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008364 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8365 if (OpI == 0)
8366 return commonCastTransforms(FI);
8367
8368 // fptoui(uitofp(X)) --> X
8369 // fptoui(sitofp(X)) --> X
8370 // This is safe if the intermediate type has enough bits in its mantissa to
8371 // accurately represent all values of X. For example, do not do this with
8372 // i64->float->i64. This is also safe for sitofp case, because any negative
8373 // 'X' value would cause an undefined result for the fptoui.
8374 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8375 OpI->getOperand(0)->getType() == FI.getType() &&
8376 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8377 OpI->getType()->getFPMantissaWidth())
8378 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008379
8380 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008381}
8382
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008383Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008384 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8385 if (OpI == 0)
8386 return commonCastTransforms(FI);
8387
8388 // fptosi(sitofp(X)) --> X
8389 // fptosi(uitofp(X)) --> X
8390 // This is safe if the intermediate type has enough bits in its mantissa to
8391 // accurately represent all values of X. For example, do not do this with
8392 // i64->float->i64. This is also safe for sitofp case, because any negative
8393 // 'X' value would cause an undefined result for the fptoui.
8394 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8395 OpI->getOperand(0)->getType() == FI.getType() &&
8396 (int)FI.getType()->getPrimitiveSizeInBits() <=
8397 OpI->getType()->getFPMantissaWidth())
8398 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008399
8400 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008401}
8402
8403Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8404 return commonCastTransforms(CI);
8405}
8406
8407Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8408 return commonCastTransforms(CI);
8409}
8410
8411Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8412 return commonPointerCastTransforms(CI);
8413}
8414
Chris Lattner7c1626482008-01-08 07:23:51 +00008415Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8416 if (Instruction *I = commonCastTransforms(CI))
8417 return I;
8418
8419 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8420 if (!DestPointee->isSized()) return 0;
8421
8422 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8423 ConstantInt *Cst;
8424 Value *X;
8425 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8426 m_ConstantInt(Cst)))) {
8427 // If the source and destination operands have the same type, see if this
8428 // is a single-index GEP.
8429 if (X->getType() == CI.getType()) {
8430 // Get the size of the pointee type.
Duncan Sandsd68f13b2009-01-12 20:38:59 +00008431 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008432
8433 // Convert the constant to intptr type.
8434 APInt Offset = Cst->getValue();
8435 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8436
8437 // If Offset is evenly divisible by Size, we can do this xform.
8438 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8439 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00008440 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00008441 }
8442 }
8443 // TODO: Could handle other cases, e.g. where add is indexing into field of
8444 // struct etc.
8445 } else if (CI.getOperand(0)->hasOneUse() &&
8446 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8447 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8448 // "inttoptr+GEP" instead of "add+intptr".
8449
8450 // Get the size of the pointee type.
Duncan Sandsd68f13b2009-01-12 20:38:59 +00008451 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008452
8453 // Convert the constant to intptr type.
8454 APInt Offset = Cst->getValue();
8455 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8456
8457 // If Offset is evenly divisible by Size, we can do this xform.
8458 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8459 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8460
8461 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8462 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008463 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00008464 }
8465 }
8466 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008467}
8468
8469Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8470 // If the operands are integer typed then apply the integer transforms,
8471 // otherwise just apply the common ones.
8472 Value *Src = CI.getOperand(0);
8473 const Type *SrcTy = Src->getType();
8474 const Type *DestTy = CI.getType();
8475
8476 if (SrcTy->isInteger() && DestTy->isInteger()) {
8477 if (Instruction *Result = commonIntCastTransforms(CI))
8478 return Result;
8479 } else if (isa<PointerType>(SrcTy)) {
8480 if (Instruction *I = commonPointerCastTransforms(CI))
8481 return I;
8482 } else {
8483 if (Instruction *Result = commonCastTransforms(CI))
8484 return Result;
8485 }
8486
8487
8488 // Get rid of casts from one type to the same type. These are useless and can
8489 // be replaced by the operand.
8490 if (DestTy == Src->getType())
8491 return ReplaceInstUsesWith(CI, Src);
8492
8493 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8494 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8495 const Type *DstElTy = DstPTy->getElementType();
8496 const Type *SrcElTy = SrcPTy->getElementType();
8497
Nate Begemandf5b3612008-03-31 00:22:16 +00008498 // If the address spaces don't match, don't eliminate the bitcast, which is
8499 // required for changing types.
8500 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8501 return 0;
8502
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008503 // If we are casting a malloc or alloca to a pointer to a type of the same
8504 // size, rewrite the allocation instruction to allocate the "right" type.
8505 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8506 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8507 return V;
8508
8509 // If the source and destination are pointers, and this cast is equivalent
8510 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8511 // This can enhance SROA and other transforms that want type-safe pointers.
8512 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8513 unsigned NumZeros = 0;
8514 while (SrcElTy != DstElTy &&
8515 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8516 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8517 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8518 ++NumZeros;
8519 }
8520
8521 // If we found a path from the src to dest, create the getelementptr now.
8522 if (SrcElTy == DstElTy) {
8523 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008524 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8525 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008526 }
8527 }
8528
8529 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8530 if (SVI->hasOneUse()) {
8531 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8532 // a bitconvert to a vector with the same # elts.
8533 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00008534 cast<VectorType>(DestTy)->getNumElements() ==
8535 SVI->getType()->getNumElements() &&
8536 SVI->getType()->getNumElements() ==
8537 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008538 CastInst *Tmp;
8539 // If either of the operands is a cast from CI.getType(), then
8540 // evaluating the shuffle in the casted destination's type will allow
8541 // us to eliminate at least one cast.
8542 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8543 Tmp->getOperand(0)->getType() == DestTy) ||
8544 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8545 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedman722b4792008-11-30 21:09:11 +00008546 Value *LHS = InsertCastBefore(Instruction::BitCast,
8547 SVI->getOperand(0), DestTy, CI);
8548 Value *RHS = InsertCastBefore(Instruction::BitCast,
8549 SVI->getOperand(1), DestTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008550 // Return a new shuffle vector. Use the same element ID's, as we
8551 // know the vector types match #elts.
8552 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8553 }
8554 }
8555 }
8556 }
8557 return 0;
8558}
8559
8560/// GetSelectFoldableOperands - We want to turn code that looks like this:
8561/// %C = or %A, %B
8562/// %D = select %cond, %C, %A
8563/// into:
8564/// %C = select %cond, %B, 0
8565/// %D = or %A, %C
8566///
8567/// Assuming that the specified instruction is an operand to the select, return
8568/// a bitmask indicating which operands of this instruction are foldable if they
8569/// equal the other incoming value of the select.
8570///
8571static unsigned GetSelectFoldableOperands(Instruction *I) {
8572 switch (I->getOpcode()) {
8573 case Instruction::Add:
8574 case Instruction::Mul:
8575 case Instruction::And:
8576 case Instruction::Or:
8577 case Instruction::Xor:
8578 return 3; // Can fold through either operand.
8579 case Instruction::Sub: // Can only fold on the amount subtracted.
8580 case Instruction::Shl: // Can only fold on the shift amount.
8581 case Instruction::LShr:
8582 case Instruction::AShr:
8583 return 1;
8584 default:
8585 return 0; // Cannot fold
8586 }
8587}
8588
8589/// GetSelectFoldableConstant - For the same transformation as the previous
8590/// function, return the identity constant that goes into the select.
8591static Constant *GetSelectFoldableConstant(Instruction *I) {
8592 switch (I->getOpcode()) {
8593 default: assert(0 && "This cannot happen!"); abort();
8594 case Instruction::Add:
8595 case Instruction::Sub:
8596 case Instruction::Or:
8597 case Instruction::Xor:
8598 case Instruction::Shl:
8599 case Instruction::LShr:
8600 case Instruction::AShr:
8601 return Constant::getNullValue(I->getType());
8602 case Instruction::And:
8603 return Constant::getAllOnesValue(I->getType());
8604 case Instruction::Mul:
8605 return ConstantInt::get(I->getType(), 1);
8606 }
8607}
8608
8609/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8610/// have the same opcode and only one use each. Try to simplify this.
8611Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8612 Instruction *FI) {
8613 if (TI->getNumOperands() == 1) {
8614 // If this is a non-volatile load or a cast from the same type,
8615 // merge.
8616 if (TI->isCast()) {
8617 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8618 return 0;
8619 } else {
8620 return 0; // unknown unary op.
8621 }
8622
8623 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008624 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8625 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008626 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008627 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008628 TI->getType());
8629 }
8630
8631 // Only handle binary operators here.
8632 if (!isa<BinaryOperator>(TI))
8633 return 0;
8634
8635 // Figure out if the operations have any operands in common.
8636 Value *MatchOp, *OtherOpT, *OtherOpF;
8637 bool MatchIsOpZero;
8638 if (TI->getOperand(0) == FI->getOperand(0)) {
8639 MatchOp = TI->getOperand(0);
8640 OtherOpT = TI->getOperand(1);
8641 OtherOpF = FI->getOperand(1);
8642 MatchIsOpZero = true;
8643 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8644 MatchOp = TI->getOperand(1);
8645 OtherOpT = TI->getOperand(0);
8646 OtherOpF = FI->getOperand(0);
8647 MatchIsOpZero = false;
8648 } else if (!TI->isCommutative()) {
8649 return 0;
8650 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8651 MatchOp = TI->getOperand(0);
8652 OtherOpT = TI->getOperand(1);
8653 OtherOpF = FI->getOperand(0);
8654 MatchIsOpZero = true;
8655 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8656 MatchOp = TI->getOperand(1);
8657 OtherOpT = TI->getOperand(0);
8658 OtherOpF = FI->getOperand(1);
8659 MatchIsOpZero = true;
8660 } else {
8661 return 0;
8662 }
8663
8664 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008665 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8666 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008667 InsertNewInstBefore(NewSI, SI);
8668
8669 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8670 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00008671 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008672 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008673 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008674 }
8675 assert(0 && "Shouldn't get here");
8676 return 0;
8677}
8678
Dan Gohman58c09632008-09-16 18:46:06 +00008679/// visitSelectInstWithICmp - Visit a SelectInst that has an
8680/// ICmpInst as its first operand.
8681///
8682Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8683 ICmpInst *ICI) {
8684 bool Changed = false;
8685 ICmpInst::Predicate Pred = ICI->getPredicate();
8686 Value *CmpLHS = ICI->getOperand(0);
8687 Value *CmpRHS = ICI->getOperand(1);
8688 Value *TrueVal = SI.getTrueValue();
8689 Value *FalseVal = SI.getFalseValue();
8690
8691 // Check cases where the comparison is with a constant that
8692 // can be adjusted to fit the min/max idiom. We may edit ICI in
8693 // place here, so make sure the select is the only user.
8694 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00008695 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00008696 switch (Pred) {
8697 default: break;
8698 case ICmpInst::ICMP_ULT:
8699 case ICmpInst::ICMP_SLT: {
8700 // X < MIN ? T : F --> F
8701 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8702 return ReplaceInstUsesWith(SI, FalseVal);
8703 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8704 Constant *AdjustedRHS = SubOne(CI);
8705 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8706 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8707 Pred = ICmpInst::getSwappedPredicate(Pred);
8708 CmpRHS = AdjustedRHS;
8709 std::swap(FalseVal, TrueVal);
8710 ICI->setPredicate(Pred);
8711 ICI->setOperand(1, CmpRHS);
8712 SI.setOperand(1, TrueVal);
8713 SI.setOperand(2, FalseVal);
8714 Changed = true;
8715 }
8716 break;
8717 }
8718 case ICmpInst::ICMP_UGT:
8719 case ICmpInst::ICMP_SGT: {
8720 // X > MAX ? T : F --> F
8721 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8722 return ReplaceInstUsesWith(SI, FalseVal);
8723 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8724 Constant *AdjustedRHS = AddOne(CI);
8725 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8726 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8727 Pred = ICmpInst::getSwappedPredicate(Pred);
8728 CmpRHS = AdjustedRHS;
8729 std::swap(FalseVal, TrueVal);
8730 ICI->setPredicate(Pred);
8731 ICI->setOperand(1, CmpRHS);
8732 SI.setOperand(1, TrueVal);
8733 SI.setOperand(2, FalseVal);
8734 Changed = true;
8735 }
8736 break;
8737 }
8738 }
8739
Dan Gohman35b76162008-10-30 20:40:10 +00008740 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8741 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00008742 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner73c1ddb2009-01-05 23:53:12 +00008743 if (match(TrueVal, m_ConstantInt<-1>()) &&
8744 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00008745 Pred = ICI->getPredicate();
Chris Lattner73c1ddb2009-01-05 23:53:12 +00008746 else if (match(TrueVal, m_ConstantInt<0>()) &&
8747 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00008748 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8749
Dan Gohman35b76162008-10-30 20:40:10 +00008750 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8751 // If we are just checking for a icmp eq of a single bit and zext'ing it
8752 // to an integer, then shift the bit to the appropriate place and then
8753 // cast to integer to avoid the comparison.
8754 const APInt &Op1CV = CI->getValue();
8755
8756 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8757 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8758 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00008759 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00008760 Value *In = ICI->getOperand(0);
8761 Value *Sh = ConstantInt::get(In->getType(),
8762 In->getType()->getPrimitiveSizeInBits()-1);
8763 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8764 In->getName()+".lobit"),
8765 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00008766 if (In->getType() != SI.getType())
8767 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00008768 true/*SExt*/, "tmp", ICI);
8769
8770 if (Pred == ICmpInst::ICMP_SGT)
8771 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8772 In->getName()+".not"), *ICI);
8773
8774 return ReplaceInstUsesWith(SI, In);
8775 }
8776 }
8777 }
8778
Dan Gohman58c09632008-09-16 18:46:06 +00008779 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8780 // Transform (X == Y) ? X : Y -> Y
8781 if (Pred == ICmpInst::ICMP_EQ)
8782 return ReplaceInstUsesWith(SI, FalseVal);
8783 // Transform (X != Y) ? X : Y -> X
8784 if (Pred == ICmpInst::ICMP_NE)
8785 return ReplaceInstUsesWith(SI, TrueVal);
8786 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8787
8788 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8789 // Transform (X == Y) ? Y : X -> X
8790 if (Pred == ICmpInst::ICMP_EQ)
8791 return ReplaceInstUsesWith(SI, FalseVal);
8792 // Transform (X != Y) ? Y : X -> Y
8793 if (Pred == ICmpInst::ICMP_NE)
8794 return ReplaceInstUsesWith(SI, TrueVal);
8795 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8796 }
8797
8798 /// NOTE: if we wanted to, this is where to detect integer ABS
8799
8800 return Changed ? &SI : 0;
8801}
8802
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008803Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8804 Value *CondVal = SI.getCondition();
8805 Value *TrueVal = SI.getTrueValue();
8806 Value *FalseVal = SI.getFalseValue();
8807
8808 // select true, X, Y -> X
8809 // select false, X, Y -> Y
8810 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8811 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8812
8813 // select C, X, X -> X
8814 if (TrueVal == FalseVal)
8815 return ReplaceInstUsesWith(SI, TrueVal);
8816
8817 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8818 return ReplaceInstUsesWith(SI, FalseVal);
8819 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8820 return ReplaceInstUsesWith(SI, TrueVal);
8821 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8822 if (isa<Constant>(TrueVal))
8823 return ReplaceInstUsesWith(SI, TrueVal);
8824 else
8825 return ReplaceInstUsesWith(SI, FalseVal);
8826 }
8827
8828 if (SI.getType() == Type::Int1Ty) {
8829 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8830 if (C->getZExtValue()) {
8831 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008832 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008833 } else {
8834 // Change: A = select B, false, C --> A = and !B, C
8835 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008836 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008837 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008838 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008839 }
8840 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8841 if (C->getZExtValue() == false) {
8842 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008843 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008844 } else {
8845 // Change: A = select B, C, true --> A = or !B, C
8846 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008847 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008848 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008849 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008850 }
8851 }
Chris Lattner53f85a72007-11-25 21:27:53 +00008852
8853 // select a, b, a -> a&b
8854 // select a, a, b -> a|b
8855 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008856 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00008857 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008858 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008859 }
8860
8861 // Selecting between two integer constants?
8862 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8863 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8864 // select C, 1, 0 -> zext C to int
8865 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00008866 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008867 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8868 // select C, 0, 1 -> zext !C to int
8869 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008870 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008871 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008872 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008873 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008874
8875 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8876
8877 // (x <s 0) ? -1 : 0 -> ashr x, 31
8878 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8879 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8880 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8881 // The comparison constant and the result are not neccessarily the
8882 // same width. Make an all-ones value by inserting a AShr.
8883 Value *X = IC->getOperand(0);
8884 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8885 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008886 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008887 ShAmt, "ones");
8888 InsertNewInstBefore(SRA, SI);
Eli Friedman722b4792008-11-30 21:09:11 +00008889
8890 // Then cast to the appropriate width.
8891 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008892 }
8893 }
8894
8895
8896 // If one of the constants is zero (we know they can't both be) and we
8897 // have an icmp instruction with zero, and we have an 'and' with the
8898 // non-constant value, eliminate this whole mess. This corresponds to
8899 // cases like this: ((X & 27) ? 27 : 0)
8900 if (TrueValC->isZero() || FalseValC->isZero())
8901 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8902 cast<Constant>(IC->getOperand(1))->isNullValue())
8903 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8904 if (ICA->getOpcode() == Instruction::And &&
8905 isa<ConstantInt>(ICA->getOperand(1)) &&
8906 (ICA->getOperand(1) == TrueValC ||
8907 ICA->getOperand(1) == FalseValC) &&
8908 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8909 // Okay, now we know that everything is set up, we just don't
8910 // know whether we have a icmp_ne or icmp_eq and whether the
8911 // true or false val is the zero.
8912 bool ShouldNotVal = !TrueValC->isZero();
8913 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8914 Value *V = ICA;
8915 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008916 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008917 Instruction::Xor, V, ICA->getOperand(1)), SI);
8918 return ReplaceInstUsesWith(SI, V);
8919 }
8920 }
8921 }
8922
8923 // See if we are selecting two values based on a comparison of the two values.
8924 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8925 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8926 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008927 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8928 // This is not safe in general for floating point:
8929 // consider X== -0, Y== +0.
8930 // It becomes safe if either operand is a nonzero constant.
8931 ConstantFP *CFPt, *CFPf;
8932 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8933 !CFPt->getValueAPF().isZero()) ||
8934 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8935 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008936 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008937 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008938 // Transform (X != Y) ? X : Y -> X
8939 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8940 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00008941 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008942
8943 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8944 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008945 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8946 // This is not safe in general for floating point:
8947 // consider X== -0, Y== +0.
8948 // It becomes safe if either operand is a nonzero constant.
8949 ConstantFP *CFPt, *CFPf;
8950 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8951 !CFPt->getValueAPF().isZero()) ||
8952 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8953 !CFPf->getValueAPF().isZero()))
8954 return ReplaceInstUsesWith(SI, FalseVal);
8955 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008956 // Transform (X != Y) ? Y : X -> Y
8957 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8958 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00008959 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008960 }
Dan Gohman58c09632008-09-16 18:46:06 +00008961 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008962 }
8963
8964 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00008965 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8966 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8967 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008968
8969 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8970 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8971 if (TI->hasOneUse() && FI->hasOneUse()) {
8972 Instruction *AddOp = 0, *SubOp = 0;
8973
8974 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8975 if (TI->getOpcode() == FI->getOpcode())
8976 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8977 return IV;
8978
8979 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8980 // even legal for FP.
8981 if (TI->getOpcode() == Instruction::Sub &&
8982 FI->getOpcode() == Instruction::Add) {
8983 AddOp = FI; SubOp = TI;
8984 } else if (FI->getOpcode() == Instruction::Sub &&
8985 TI->getOpcode() == Instruction::Add) {
8986 AddOp = TI; SubOp = FI;
8987 }
8988
8989 if (AddOp) {
8990 Value *OtherAddOp = 0;
8991 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8992 OtherAddOp = AddOp->getOperand(1);
8993 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8994 OtherAddOp = AddOp->getOperand(0);
8995 }
8996
8997 if (OtherAddOp) {
8998 // So at this point we know we have (Y -> OtherAddOp):
8999 // select C, (add X, Y), (sub X, Z)
9000 Value *NegVal; // Compute -Z
9001 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9002 NegVal = ConstantExpr::getNeg(C);
9003 } else {
9004 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00009005 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009006 }
9007
9008 Value *NewTrueOp = OtherAddOp;
9009 Value *NewFalseOp = NegVal;
9010 if (AddOp != TI)
9011 std::swap(NewTrueOp, NewFalseOp);
9012 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009013 SelectInst::Create(CondVal, NewTrueOp,
9014 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009015
9016 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009017 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009018 }
9019 }
9020 }
9021
9022 // See if we can fold the select into one of our operands.
9023 if (SI.getType()->isInteger()) {
9024 // See the comment above GetSelectFoldableOperands for a description of the
9025 // transformation we are doing here.
9026 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9027 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9028 !isa<Constant>(FalseVal))
9029 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9030 unsigned OpToFold = 0;
9031 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9032 OpToFold = 1;
9033 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9034 OpToFold = 2;
9035 }
9036
9037 if (OpToFold) {
9038 Constant *C = GetSelectFoldableConstant(TVI);
9039 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009040 SelectInst::Create(SI.getCondition(),
9041 TVI->getOperand(2-OpToFold), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009042 InsertNewInstBefore(NewSel, SI);
9043 NewSel->takeName(TVI);
9044 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00009045 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009046 else {
9047 assert(0 && "Unknown instruction!!");
9048 }
9049 }
9050 }
9051
9052 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9053 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9054 !isa<Constant>(TrueVal))
9055 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9056 unsigned OpToFold = 0;
9057 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9058 OpToFold = 1;
9059 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9060 OpToFold = 2;
9061 }
9062
9063 if (OpToFold) {
9064 Constant *C = GetSelectFoldableConstant(FVI);
9065 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009066 SelectInst::Create(SI.getCondition(), C,
9067 FVI->getOperand(2-OpToFold));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009068 InsertNewInstBefore(NewSel, SI);
9069 NewSel->takeName(FVI);
9070 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00009071 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009072 else
9073 assert(0 && "Unknown instruction!!");
9074 }
9075 }
9076 }
9077
9078 if (BinaryOperator::isNot(CondVal)) {
9079 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9080 SI.setOperand(1, FalseVal);
9081 SI.setOperand(2, TrueVal);
9082 return &SI;
9083 }
9084
9085 return 0;
9086}
9087
Dan Gohman2d648bb2008-04-10 18:43:06 +00009088/// EnforceKnownAlignment - If the specified pointer points to an object that
9089/// we control, modify the object's alignment to PrefAlign. This isn't
9090/// often possible though. If alignment is important, a more reliable approach
9091/// is to simply align all global variables and allocation instructions to
9092/// their preferred alignment from the beginning.
9093///
9094static unsigned EnforceKnownAlignment(Value *V,
9095 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009096
Dan Gohman2d648bb2008-04-10 18:43:06 +00009097 User *U = dyn_cast<User>(V);
9098 if (!U) return Align;
9099
9100 switch (getOpcode(U)) {
9101 default: break;
9102 case Instruction::BitCast:
9103 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9104 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009105 // If all indexes are zero, it is just the alignment of the base pointer.
9106 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009107 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009108 if (!isa<Constant>(*i) ||
9109 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009110 AllZeroOperands = false;
9111 break;
9112 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009113
9114 if (AllZeroOperands) {
9115 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009116 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009117 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009118 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009119 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009120 }
9121
9122 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9123 // If there is a large requested alignment and we can, bump up the alignment
9124 // of the global.
9125 if (!GV->isDeclaration()) {
9126 GV->setAlignment(PrefAlign);
9127 Align = PrefAlign;
9128 }
9129 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9130 // If there is a requested alignment and if this is an alloca, round up. We
9131 // don't do this for malloc, because some systems can't respect the request.
9132 if (isa<AllocaInst>(AI)) {
9133 AI->setAlignment(PrefAlign);
9134 Align = PrefAlign;
9135 }
9136 }
9137
9138 return Align;
9139}
9140
9141/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9142/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9143/// and it is more than the alignment of the ultimate object, see if we can
9144/// increase the alignment of the ultimate object, making this check succeed.
9145unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9146 unsigned PrefAlign) {
9147 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9148 sizeof(PrefAlign) * CHAR_BIT;
9149 APInt Mask = APInt::getAllOnesValue(BitWidth);
9150 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9151 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9152 unsigned TrailZ = KnownZero.countTrailingOnes();
9153 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9154
9155 if (PrefAlign > Align)
9156 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9157
9158 // We don't need to make any adjustment.
9159 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009160}
9161
Chris Lattner00ae5132008-01-13 23:50:23 +00009162Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009163 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9164 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009165 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9166 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9167
9168 if (CopyAlign < MinAlign) {
9169 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9170 return MI;
9171 }
9172
9173 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9174 // load/store.
9175 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9176 if (MemOpLength == 0) return 0;
9177
Chris Lattnerc669fb62008-01-14 00:28:35 +00009178 // Source and destination pointer types are always "i8*" for intrinsic. See
9179 // if the size is something we can handle with a single primitive load/store.
9180 // A single load+store correctly handles overlapping memory in the memmove
9181 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009182 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009183 if (Size == 0) return MI; // Delete this mem transfer.
9184
9185 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009186 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009187
Chris Lattnerc669fb62008-01-14 00:28:35 +00009188 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00009189 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009190
9191 // Memcpy forces the use of i8* for the source and destination. That means
9192 // that if you're using memcpy to move one double around, you'll get a cast
9193 // from double* to i8*. We'd much rather use a double load+store rather than
9194 // an i64 load+store, here because this improves the odds that the source or
9195 // dest address will be promotable. See if we can find a better type than the
9196 // integer datatype.
9197 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9198 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9199 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9200 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9201 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009202 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009203 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9204 if (STy->getNumElements() == 1)
9205 SrcETy = STy->getElementType(0);
9206 else
9207 break;
9208 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9209 if (ATy->getNumElements() == 1)
9210 SrcETy = ATy->getElementType();
9211 else
9212 break;
9213 } else
9214 break;
9215 }
9216
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009217 if (SrcETy->isSingleValueType())
Chris Lattnerc669fb62008-01-14 00:28:35 +00009218 NewPtrTy = PointerType::getUnqual(SrcETy);
9219 }
9220 }
9221
9222
Chris Lattner00ae5132008-01-13 23:50:23 +00009223 // If the memcpy/memmove provides better alignment info than we can
9224 // infer, use it.
9225 SrcAlign = std::max(SrcAlign, CopyAlign);
9226 DstAlign = std::max(DstAlign, CopyAlign);
9227
9228 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9229 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009230 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9231 InsertNewInstBefore(L, *MI);
9232 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9233
9234 // Set the size of the copy to 0, it will be deleted on the next iteration.
9235 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9236 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009237}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009238
Chris Lattner5af8a912008-04-30 06:39:11 +00009239Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9240 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9241 if (MI->getAlignment()->getZExtValue() < Alignment) {
9242 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9243 return MI;
9244 }
9245
9246 // Extract the length and alignment and fill if they are constant.
9247 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9248 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9249 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9250 return 0;
9251 uint64_t Len = LenC->getZExtValue();
9252 Alignment = MI->getAlignment()->getZExtValue();
9253
9254 // If the length is zero, this is a no-op
9255 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9256
9257 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9258 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9259 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9260
9261 Value *Dest = MI->getDest();
9262 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9263
9264 // Alignment 0 is identity for alignment 1 for memset, but not store.
9265 if (Alignment == 0) Alignment = 1;
9266
9267 // Extract the fill value and store.
9268 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9269 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9270 Alignment), *MI);
9271
9272 // Set the size of the copy to 0, it will be deleted on the next iteration.
9273 MI->setLength(Constant::getNullValue(LenC->getType()));
9274 return MI;
9275 }
9276
9277 return 0;
9278}
9279
9280
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009281/// visitCallInst - CallInst simplification. This mostly only handles folding
9282/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9283/// the heavy lifting.
9284///
9285Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9286 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9287 if (!II) return visitCallSite(&CI);
9288
9289 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9290 // visitCallSite.
9291 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9292 bool Changed = false;
9293
9294 // memmove/cpy/set of zero bytes is a noop.
9295 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9296 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9297
9298 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9299 if (CI->getZExtValue() == 1) {
9300 // Replace the instruction with just byte operations. We would
9301 // transform other cases to loads/stores, but we don't know if
9302 // alignment is sufficient.
9303 }
9304 }
9305
9306 // If we have a memmove and the source operation is a constant global,
9307 // then the source and dest pointers can't alias, so we can change this
9308 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009309 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009310 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9311 if (GVSrc->isConstant()) {
9312 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009313 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9314 const Type *Tys[1];
9315 Tys[0] = CI.getOperand(3)->getType();
9316 CI.setOperand(0,
9317 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009318 Changed = true;
9319 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009320
9321 // memmove(x,x,size) -> noop.
9322 if (MMI->getSource() == MMI->getDest())
9323 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009324 }
9325
9326 // If we can determine a pointer alignment that is bigger than currently
9327 // set, update the alignment.
9328 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009329 if (Instruction *I = SimplifyMemTransfer(MI))
9330 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009331 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9332 if (Instruction *I = SimplifyMemSet(MSI))
9333 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009334 }
9335
9336 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009337 }
9338
9339 switch (II->getIntrinsicID()) {
9340 default: break;
9341 case Intrinsic::bswap:
9342 // bswap(bswap(x)) -> x
9343 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9344 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9345 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9346 break;
9347 case Intrinsic::ppc_altivec_lvx:
9348 case Intrinsic::ppc_altivec_lvxl:
9349 case Intrinsic::x86_sse_loadu_ps:
9350 case Intrinsic::x86_sse2_loadu_pd:
9351 case Intrinsic::x86_sse2_loadu_dq:
9352 // Turn PPC lvx -> load if the pointer is known aligned.
9353 // Turn X86 loadups -> load if the pointer is known aligned.
9354 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9355 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9356 PointerType::getUnqual(II->getType()),
9357 CI);
9358 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009359 }
Chris Lattner989ba312008-06-18 04:33:20 +00009360 break;
9361 case Intrinsic::ppc_altivec_stvx:
9362 case Intrinsic::ppc_altivec_stvxl:
9363 // Turn stvx -> store if the pointer is known aligned.
9364 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9365 const Type *OpPtrTy =
9366 PointerType::getUnqual(II->getOperand(1)->getType());
9367 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9368 return new StoreInst(II->getOperand(1), Ptr);
9369 }
9370 break;
9371 case Intrinsic::x86_sse_storeu_ps:
9372 case Intrinsic::x86_sse2_storeu_pd:
9373 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009374 // Turn X86 storeu -> store if the pointer is known aligned.
9375 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9376 const Type *OpPtrTy =
9377 PointerType::getUnqual(II->getOperand(2)->getType());
9378 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9379 return new StoreInst(II->getOperand(2), Ptr);
9380 }
9381 break;
9382
9383 case Intrinsic::x86_sse_cvttss2si: {
9384 // These intrinsics only demands the 0th element of its input vector. If
9385 // we can simplify the input based on that, do so now.
9386 uint64_t UndefElts;
9387 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9388 UndefElts)) {
9389 II->setOperand(1, V);
9390 return II;
9391 }
9392 break;
9393 }
9394
9395 case Intrinsic::ppc_altivec_vperm:
9396 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9397 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9398 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009399
Chris Lattner989ba312008-06-18 04:33:20 +00009400 // Check that all of the elements are integer constants or undefs.
9401 bool AllEltsOk = true;
9402 for (unsigned i = 0; i != 16; ++i) {
9403 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9404 !isa<UndefValue>(Mask->getOperand(i))) {
9405 AllEltsOk = false;
9406 break;
9407 }
9408 }
9409
9410 if (AllEltsOk) {
9411 // Cast the input vectors to byte vectors.
9412 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9413 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9414 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009415
Chris Lattner989ba312008-06-18 04:33:20 +00009416 // Only extract each element once.
9417 Value *ExtractedElts[32];
9418 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9419
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009420 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00009421 if (isa<UndefValue>(Mask->getOperand(i)))
9422 continue;
9423 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9424 Idx &= 31; // Match the hardware behavior.
9425
9426 if (ExtractedElts[Idx] == 0) {
9427 Instruction *Elt =
9428 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9429 InsertNewInstBefore(Elt, CI);
9430 ExtractedElts[Idx] = Elt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009431 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009432
Chris Lattner989ba312008-06-18 04:33:20 +00009433 // Insert this value into the result vector.
9434 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9435 i, "tmp");
9436 InsertNewInstBefore(cast<Instruction>(Result), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009437 }
Chris Lattner989ba312008-06-18 04:33:20 +00009438 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009439 }
Chris Lattner989ba312008-06-18 04:33:20 +00009440 }
9441 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009442
Chris Lattner989ba312008-06-18 04:33:20 +00009443 case Intrinsic::stackrestore: {
9444 // If the save is right next to the restore, remove the restore. This can
9445 // happen when variable allocas are DCE'd.
9446 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9447 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9448 BasicBlock::iterator BI = SS;
9449 if (&*++BI == II)
9450 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009451 }
Chris Lattner989ba312008-06-18 04:33:20 +00009452 }
9453
9454 // Scan down this block to see if there is another stack restore in the
9455 // same block without an intervening call/alloca.
9456 BasicBlock::iterator BI = II;
9457 TerminatorInst *TI = II->getParent()->getTerminator();
9458 bool CannotRemove = false;
9459 for (++BI; &*BI != TI; ++BI) {
9460 if (isa<AllocaInst>(BI)) {
9461 CannotRemove = true;
9462 break;
9463 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00009464 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9465 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9466 // If there is a stackrestore below this one, remove this one.
9467 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9468 return EraseInstFromFunction(CI);
9469 // Otherwise, ignore the intrinsic.
9470 } else {
9471 // If we found a non-intrinsic call, we can't remove the stack
9472 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00009473 CannotRemove = true;
9474 break;
9475 }
Chris Lattner989ba312008-06-18 04:33:20 +00009476 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009477 }
Chris Lattner989ba312008-06-18 04:33:20 +00009478
9479 // If the stack restore is in a return/unwind block and if there are no
9480 // allocas or calls between the restore and the return, nuke the restore.
9481 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9482 return EraseInstFromFunction(CI);
9483 break;
9484 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009485 }
9486
9487 return visitCallSite(II);
9488}
9489
9490// InvokeInst simplification
9491//
9492Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9493 return visitCallSite(&II);
9494}
9495
Dale Johannesen96021832008-04-25 21:16:07 +00009496/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9497/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00009498static bool isSafeToEliminateVarargsCast(const CallSite CS,
9499 const CastInst * const CI,
9500 const TargetData * const TD,
9501 const int ix) {
9502 if (!CI->isLosslessCast())
9503 return false;
9504
9505 // The size of ByVal arguments is derived from the type, so we
9506 // can't change to a type with a different size. If the size were
9507 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +00009508 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +00009509 return true;
9510
9511 const Type* SrcTy =
9512 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9513 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9514 if (!SrcTy->isSized() || !DstTy->isSized())
9515 return false;
Duncan Sandsd68f13b2009-01-12 20:38:59 +00009516 if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +00009517 return false;
9518 return true;
9519}
9520
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009521// visitCallSite - Improvements for call and invoke instructions.
9522//
9523Instruction *InstCombiner::visitCallSite(CallSite CS) {
9524 bool Changed = false;
9525
9526 // If the callee is a constexpr cast of a function, attempt to move the cast
9527 // to the arguments of the call/invoke.
9528 if (transformConstExprCastCall(CS)) return 0;
9529
9530 Value *Callee = CS.getCalledValue();
9531
9532 if (Function *CalleeF = dyn_cast<Function>(Callee))
9533 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9534 Instruction *OldCall = CS.getInstruction();
9535 // If the call and callee calling conventions don't match, this call must
9536 // be unreachable, as the call is undefined.
9537 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009538 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9539 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009540 if (!OldCall->use_empty())
9541 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9542 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9543 return EraseInstFromFunction(*OldCall);
9544 return 0;
9545 }
9546
9547 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9548 // This instruction is not reachable, just remove it. We insert a store to
9549 // undef so that we know that this code is not reachable, despite the fact
9550 // that we can't modify the CFG here.
9551 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009552 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009553 CS.getInstruction());
9554
9555 if (!CS.getInstruction()->use_empty())
9556 CS.getInstruction()->
9557 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9558
9559 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9560 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009561 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9562 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009563 }
9564 return EraseInstFromFunction(*CS.getInstruction());
9565 }
9566
Duncan Sands74833f22007-09-17 10:26:40 +00009567 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9568 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9569 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9570 return transformCallThroughTrampoline(CS);
9571
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009572 const PointerType *PTy = cast<PointerType>(Callee->getType());
9573 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9574 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00009575 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009576 // See if we can optimize any arguments passed through the varargs area of
9577 // the call.
9578 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00009579 E = CS.arg_end(); I != E; ++I, ++ix) {
9580 CastInst *CI = dyn_cast<CastInst>(*I);
9581 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9582 *I = CI->getOperand(0);
9583 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009584 }
Dale Johannesen35615462008-04-23 18:34:37 +00009585 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009586 }
9587
Duncan Sands2937e352007-12-19 21:13:37 +00009588 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00009589 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00009590 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00009591 Changed = true;
9592 }
9593
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009594 return Changed ? CS.getInstruction() : 0;
9595}
9596
9597// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9598// attempt to move the cast to the arguments of the call/invoke.
9599//
9600bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9601 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9602 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9603 if (CE->getOpcode() != Instruction::BitCast ||
9604 !isa<Function>(CE->getOperand(0)))
9605 return false;
9606 Function *Callee = cast<Function>(CE->getOperand(0));
9607 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +00009608 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009609
9610 // Okay, this is a cast from a function to a different type. Unless doing so
9611 // would cause a type conversion of one of our arguments, change this call to
9612 // be a direct call with arguments casted to the appropriate types.
9613 //
9614 const FunctionType *FT = Callee->getFunctionType();
9615 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +00009616 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009617
Duncan Sands7901ce12008-06-01 07:38:42 +00009618 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +00009619 return false; // TODO: Handle multiple return values.
9620
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009621 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +00009622 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00009623 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +00009624 // Conversion is ok if changing from one pointer type to another or from
9625 // a pointer to an integer of the same size.
9626 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands886cadb2008-06-17 15:55:30 +00009627 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009628 return false; // Cannot transform this return value.
9629
Duncan Sands5c489582008-01-06 10:12:28 +00009630 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00009631 // void -> non-void is handled specially
Duncan Sands7901ce12008-06-01 07:38:42 +00009632 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00009633 return false; // Cannot transform this return value.
9634
Chris Lattner1c8733e2008-03-12 17:45:29 +00009635 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +00009636 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +00009637 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00009638 return false; // Attribute not compatible with transformed value.
9639 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009640
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009641 // If the callsite is an invoke instruction, and the return value is used by
9642 // a PHI node in a successor, we cannot change the return type of the call
9643 // because there is no place to put the cast instruction (without breaking
9644 // the critical edge). Bail out in this case.
9645 if (!Caller->use_empty())
9646 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9647 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9648 UI != E; ++UI)
9649 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9650 if (PN->getParent() == II->getNormalDest() ||
9651 PN->getParent() == II->getUnwindDest())
9652 return false;
9653 }
9654
9655 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9656 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9657
9658 CallSite::arg_iterator AI = CS.arg_begin();
9659 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9660 const Type *ParamTy = FT->getParamType(i);
9661 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00009662
9663 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00009664 return false; // Cannot transform this parameter value.
9665
Devang Patelf2a4a922008-09-26 22:53:05 +00009666 if (CallerPAL.getParamAttributes(i + 1)
9667 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +00009668 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00009669
Duncan Sands7901ce12008-06-01 07:38:42 +00009670 // Converting from one pointer type to another or between a pointer and an
9671 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009672 bool isConvertible = ActTy == ParamTy ||
Duncan Sands7901ce12008-06-01 07:38:42 +00009673 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9674 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009675 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009676 }
9677
9678 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9679 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00009680 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009681
Chris Lattner1c8733e2008-03-12 17:45:29 +00009682 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9683 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00009684 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00009685 // won't be dropping them. Check that these extra arguments have attributes
9686 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009687 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9688 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00009689 break;
Devang Patele480dfa2008-09-23 23:03:40 +00009690 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +00009691 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +00009692 return false;
9693 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009694
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009695 // Okay, we decided that this is a safe thing to do: go ahead and start
9696 // inserting cast instructions as necessary...
9697 std::vector<Value*> Args;
9698 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +00009699 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00009700 attrVec.reserve(NumCommonArgs);
9701
9702 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00009703 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +00009704
9705 // If the return value is not being used, the type may not be compatible
9706 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +00009707 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +00009708
9709 // Add the new return attributes.
9710 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +00009711 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009712
9713 AI = CS.arg_begin();
9714 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9715 const Type *ParamTy = FT->getParamType(i);
9716 if ((*AI)->getType() == ParamTy) {
9717 Args.push_back(*AI);
9718 } else {
9719 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9720 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009721 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009722 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9723 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009724
9725 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00009726 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +00009727 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009728 }
9729
9730 // If the function takes more arguments than the call was taking, add them
9731 // now...
9732 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9733 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9734
9735 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009736 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009737 if (!FT->isVarArg()) {
9738 cerr << "WARNING: While resolving call to function '"
9739 << Callee->getName() << "' arguments were dropped!\n";
9740 } else {
9741 // Add all of the arguments in their promoted form to the arg list...
9742 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9743 const Type *PTy = getPromotedType((*AI)->getType());
9744 if (PTy != (*AI)->getType()) {
9745 // Must promote to pass through va_arg area!
9746 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9747 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009748 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009749 InsertNewInstBefore(Cast, *Caller);
9750 Args.push_back(Cast);
9751 } else {
9752 Args.push_back(*AI);
9753 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009754
Duncan Sands4ced1f82008-01-13 08:02:44 +00009755 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00009756 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +00009757 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +00009758 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009759 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009760 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009761
Devang Patelf2a4a922008-09-26 22:53:05 +00009762 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9763 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9764
Duncan Sands7901ce12008-06-01 07:38:42 +00009765 if (NewRetTy == Type::VoidTy)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009766 Caller->setName(""); // Void type should not have a name.
9767
Devang Pateld222f862008-09-25 21:00:45 +00009768 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00009769
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009770 Instruction *NC;
9771 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009772 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009773 Args.begin(), Args.end(),
9774 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00009775 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00009776 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009777 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009778 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9779 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009780 CallInst *CI = cast<CallInst>(Caller);
9781 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009782 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009783 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00009784 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009785 }
9786
9787 // Insert a cast of the return type as necessary.
9788 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00009789 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009790 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009791 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00009792 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009793 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009794
9795 // If this is an invoke instruction, we should insert it after the first
9796 // non-phi, instruction in the normal successor block.
9797 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +00009798 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009799 InsertNewInstBefore(NC, *I);
9800 } else {
9801 // Otherwise, it's a call, just insert cast right after the call instr
9802 InsertNewInstBefore(NC, *Caller);
9803 }
9804 AddUsersToWorkList(*Caller);
9805 } else {
9806 NV = UndefValue::get(Caller->getType());
9807 }
9808 }
9809
9810 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9811 Caller->replaceAllUsesWith(NV);
9812 Caller->eraseFromParent();
9813 RemoveFromWorkList(Caller);
9814 return true;
9815}
9816
Duncan Sands74833f22007-09-17 10:26:40 +00009817// transformCallThroughTrampoline - Turn a call to a function created by the
9818// init_trampoline intrinsic into a direct call to the underlying function.
9819//
9820Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9821 Value *Callee = CS.getCalledValue();
9822 const PointerType *PTy = cast<PointerType>(Callee->getType());
9823 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +00009824 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +00009825
9826 // If the call already has the 'nest' attribute somewhere then give up -
9827 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +00009828 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00009829 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00009830
9831 IntrinsicInst *Tramp =
9832 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9833
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +00009834 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +00009835 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9836 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9837
Devang Pateld222f862008-09-25 21:00:45 +00009838 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +00009839 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00009840 unsigned NestIdx = 1;
9841 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +00009842 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +00009843
9844 // Look for a parameter marked with the 'nest' attribute.
9845 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9846 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +00009847 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00009848 // Record the parameter type and any other attributes.
9849 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +00009850 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00009851 break;
9852 }
9853
9854 if (NestTy) {
9855 Instruction *Caller = CS.getInstruction();
9856 std::vector<Value*> NewArgs;
9857 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9858
Devang Pateld222f862008-09-25 21:00:45 +00009859 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009860 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00009861
Duncan Sands74833f22007-09-17 10:26:40 +00009862 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009863 // mean appending it. Likewise for attributes.
9864
Devang Patelf2a4a922008-09-26 22:53:05 +00009865 // Add any result attributes.
9866 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +00009867 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00009868
Duncan Sands74833f22007-09-17 10:26:40 +00009869 {
9870 unsigned Idx = 1;
9871 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9872 do {
9873 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00009874 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009875 Value *NestVal = Tramp->getOperand(3);
9876 if (NestVal->getType() != NestTy)
9877 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9878 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +00009879 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00009880 }
9881
9882 if (I == E)
9883 break;
9884
Duncan Sands48b81112008-01-14 19:52:09 +00009885 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009886 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +00009887 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00009888 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +00009889 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00009890
9891 ++Idx, ++I;
9892 } while (1);
9893 }
9894
Devang Patelf2a4a922008-09-26 22:53:05 +00009895 // Add any function attributes.
9896 if (Attributes Attr = Attrs.getFnAttributes())
9897 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9898
Duncan Sands74833f22007-09-17 10:26:40 +00009899 // The trampoline may have been bitcast to a bogus type (FTy).
9900 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00009901 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00009902
Duncan Sands74833f22007-09-17 10:26:40 +00009903 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00009904 NewTypes.reserve(FTy->getNumParams()+1);
9905
Duncan Sands74833f22007-09-17 10:26:40 +00009906 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009907 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00009908 {
9909 unsigned Idx = 1;
9910 FunctionType::param_iterator I = FTy->param_begin(),
9911 E = FTy->param_end();
9912
9913 do {
Duncan Sands48b81112008-01-14 19:52:09 +00009914 if (Idx == NestIdx)
9915 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00009916 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00009917
9918 if (I == E)
9919 break;
9920
Duncan Sands48b81112008-01-14 19:52:09 +00009921 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00009922 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00009923
9924 ++Idx, ++I;
9925 } while (1);
9926 }
9927
9928 // Replace the trampoline call with a direct call. Let the generic
9929 // code sort out any function type mismatches.
9930 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009931 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00009932 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9933 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Pateld222f862008-09-25 21:00:45 +00009934 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00009935
9936 Instruction *NewCaller;
9937 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009938 NewCaller = InvokeInst::Create(NewCallee,
9939 II->getNormalDest(), II->getUnwindDest(),
9940 NewArgs.begin(), NewArgs.end(),
9941 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009942 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00009943 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009944 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009945 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9946 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009947 if (cast<CallInst>(Caller)->isTailCall())
9948 cast<CallInst>(NewCaller)->setTailCall();
9949 cast<CallInst>(NewCaller)->
9950 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00009951 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009952 }
9953 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9954 Caller->replaceAllUsesWith(NewCaller);
9955 Caller->eraseFromParent();
9956 RemoveFromWorkList(Caller);
9957 return 0;
9958 }
9959 }
9960
9961 // Replace the trampoline call with a direct call. Since there is no 'nest'
9962 // parameter, there is no need to adjust the argument list. Let the generic
9963 // code sort out any function type mismatches.
9964 Constant *NewCallee =
9965 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9966 CS.setCalledFunction(NewCallee);
9967 return CS.getInstruction();
9968}
9969
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009970/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9971/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9972/// and a single binop.
9973Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9974 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +00009975 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009976 unsigned Opc = FirstInst->getOpcode();
9977 Value *LHSVal = FirstInst->getOperand(0);
9978 Value *RHSVal = FirstInst->getOperand(1);
9979
9980 const Type *LHSType = LHSVal->getType();
9981 const Type *RHSType = RHSVal->getType();
9982
9983 // Scan to see if all operands are the same opcode, all have one use, and all
9984 // kill their operands (i.e. the operands have one use).
Chris Lattner9e1916e2008-12-01 02:34:36 +00009985 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009986 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9987 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9988 // Verify type of the LHS matches so we don't fold cmp's of different
9989 // types or GEP's with different index types.
9990 I->getOperand(0)->getType() != LHSType ||
9991 I->getOperand(1)->getType() != RHSType)
9992 return 0;
9993
9994 // If they are CmpInst instructions, check their predicates
9995 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9996 if (cast<CmpInst>(I)->getPredicate() !=
9997 cast<CmpInst>(FirstInst)->getPredicate())
9998 return 0;
9999
10000 // Keep track of which operand needs a phi node.
10001 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10002 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10003 }
10004
Chris Lattner30078012008-12-01 03:42:51 +000010005 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010006
10007 Value *InLHS = FirstInst->getOperand(0);
10008 Value *InRHS = FirstInst->getOperand(1);
10009 PHINode *NewLHS = 0, *NewRHS = 0;
10010 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010011 NewLHS = PHINode::Create(LHSType,
10012 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010013 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10014 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10015 InsertNewInstBefore(NewLHS, PN);
10016 LHSVal = NewLHS;
10017 }
10018
10019 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010020 NewRHS = PHINode::Create(RHSType,
10021 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010022 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10023 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10024 InsertNewInstBefore(NewRHS, PN);
10025 RHSVal = NewRHS;
10026 }
10027
10028 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010029 if (NewLHS || NewRHS) {
10030 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10031 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10032 if (NewLHS) {
10033 Value *NewInLHS = InInst->getOperand(0);
10034 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10035 }
10036 if (NewRHS) {
10037 Value *NewInRHS = InInst->getOperand(1);
10038 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10039 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010040 }
10041 }
10042
10043 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010044 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010045 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10046 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10047 RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010048}
10049
Chris Lattner9e1916e2008-12-01 02:34:36 +000010050Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10051 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10052
10053 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10054 FirstInst->op_end());
10055
10056 // Scan to see if all operands are the same opcode, all have one use, and all
10057 // kill their operands (i.e. the operands have one use).
10058 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10059 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10060 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10061 GEP->getNumOperands() != FirstInst->getNumOperands())
10062 return 0;
10063
10064 // Compare the operand lists.
10065 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10066 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10067 continue;
10068
10069 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10070 // if one of the PHIs has a constant for the index. The index may be
10071 // substantially cheaper to compute for the constants, so making it a
10072 // variable index could pessimize the path. This also handles the case
10073 // for struct indices, which must always be constant.
10074 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10075 isa<ConstantInt>(GEP->getOperand(op)))
10076 return 0;
10077
10078 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10079 return 0;
10080 FixedOperands[op] = 0; // Needs a PHI.
10081 }
10082 }
10083
10084 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10085 // that is variable.
10086 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10087
10088 bool HasAnyPHIs = false;
10089 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10090 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10091 Value *FirstOp = FirstInst->getOperand(i);
10092 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10093 FirstOp->getName()+".pn");
10094 InsertNewInstBefore(NewPN, PN);
10095
10096 NewPN->reserveOperandSpace(e);
10097 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10098 OperandPhis[i] = NewPN;
10099 FixedOperands[i] = NewPN;
10100 HasAnyPHIs = true;
10101 }
10102
10103
10104 // Add all operands to the new PHIs.
10105 if (HasAnyPHIs) {
10106 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10107 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10108 BasicBlock *InBB = PN.getIncomingBlock(i);
10109
10110 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10111 if (PHINode *OpPhi = OperandPhis[op])
10112 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10113 }
10114 }
10115
10116 Value *Base = FixedOperands[0];
10117 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10118 FixedOperands.end());
10119}
10120
10121
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010122/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10123/// of the block that defines it. This means that it must be obvious the value
10124/// of the load is not changed from the point of the load to the end of the
10125/// block it is in.
10126///
10127/// Finally, it is safe, but not profitable, to sink a load targetting a
10128/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10129/// to a register.
10130static bool isSafeToSinkLoad(LoadInst *L) {
10131 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10132
10133 for (++BBI; BBI != E; ++BBI)
10134 if (BBI->mayWriteToMemory())
10135 return false;
10136
10137 // Check for non-address taken alloca. If not address-taken already, it isn't
10138 // profitable to do this xform.
10139 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10140 bool isAddressTaken = false;
10141 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10142 UI != E; ++UI) {
10143 if (isa<LoadInst>(UI)) continue;
10144 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10145 // If storing TO the alloca, then the address isn't taken.
10146 if (SI->getOperand(1) == AI) continue;
10147 }
10148 isAddressTaken = true;
10149 break;
10150 }
10151
10152 if (!isAddressTaken)
10153 return false;
10154 }
10155
10156 return true;
10157}
10158
10159
10160// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10161// operator and they all are only used by the PHI, PHI together their
10162// inputs, and do the operation once, to the result of the PHI.
10163Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10164 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10165
10166 // Scan the instruction, looking for input operations that can be folded away.
10167 // If all input operands to the phi are the same instruction (e.g. a cast from
10168 // the same type or "+42") we can pull the operation through the PHI, reducing
10169 // code size and simplifying code.
10170 Constant *ConstantOp = 0;
10171 const Type *CastSrcTy = 0;
10172 bool isVolatile = false;
10173 if (isa<CastInst>(FirstInst)) {
10174 CastSrcTy = FirstInst->getOperand(0)->getType();
10175 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10176 // Can fold binop, compare or shift here if the RHS is a constant,
10177 // otherwise call FoldPHIArgBinOpIntoPHI.
10178 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10179 if (ConstantOp == 0)
10180 return FoldPHIArgBinOpIntoPHI(PN);
10181 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10182 isVolatile = LI->isVolatile();
10183 // We can't sink the load if the loaded value could be modified between the
10184 // load and the PHI.
10185 if (LI->getParent() != PN.getIncomingBlock(0) ||
10186 !isSafeToSinkLoad(LI))
10187 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010188
10189 // If the PHI is of volatile loads and the load block has multiple
10190 // successors, sinking it would remove a load of the volatile value from
10191 // the path through the other successor.
10192 if (isVolatile &&
10193 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10194 return 0;
10195
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010196 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010197 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010198 } else {
10199 return 0; // Cannot fold this operation.
10200 }
10201
10202 // Check to see if all arguments are the same operation.
10203 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10204 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10205 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10206 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10207 return 0;
10208 if (CastSrcTy) {
10209 if (I->getOperand(0)->getType() != CastSrcTy)
10210 return 0; // Cast operation must match.
10211 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10212 // We can't sink the load if the loaded value could be modified between
10213 // the load and the PHI.
10214 if (LI->isVolatile() != isVolatile ||
10215 LI->getParent() != PN.getIncomingBlock(i) ||
10216 !isSafeToSinkLoad(LI))
10217 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010218
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010219 // If the PHI is of volatile loads and the load block has multiple
10220 // successors, sinking it would remove a load of the volatile value from
10221 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010222 if (isVolatile &&
10223 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10224 return 0;
10225
10226
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010227 } else if (I->getOperand(1) != ConstantOp) {
10228 return 0;
10229 }
10230 }
10231
10232 // Okay, they are all the same operation. Create a new PHI node of the
10233 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010234 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10235 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010236 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10237
10238 Value *InVal = FirstInst->getOperand(0);
10239 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10240
10241 // Add all operands to the new PHI.
10242 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10243 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10244 if (NewInVal != InVal)
10245 InVal = 0;
10246 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10247 }
10248
10249 Value *PhiVal;
10250 if (InVal) {
10251 // The new PHI unions all of the same values together. This is really
10252 // common, so we handle it intelligently here for compile-time speed.
10253 PhiVal = InVal;
10254 delete NewPN;
10255 } else {
10256 InsertNewInstBefore(NewPN, PN);
10257 PhiVal = NewPN;
10258 }
10259
10260 // Insert and return the new operation.
10261 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010262 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010263 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010264 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010265 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010266 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010267 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010268 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10269
10270 // If this was a volatile load that we are merging, make sure to loop through
10271 // and mark all the input loads as non-volatile. If we don't do this, we will
10272 // insert a new volatile load and the old ones will not be deletable.
10273 if (isVolatile)
10274 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10275 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10276
10277 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010278}
10279
10280/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10281/// that is dead.
10282static bool DeadPHICycle(PHINode *PN,
10283 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10284 if (PN->use_empty()) return true;
10285 if (!PN->hasOneUse()) return false;
10286
10287 // Remember this node, and if we find the cycle, return.
10288 if (!PotentiallyDeadPHIs.insert(PN))
10289 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010290
10291 // Don't scan crazily complex things.
10292 if (PotentiallyDeadPHIs.size() == 16)
10293 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010294
10295 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10296 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10297
10298 return false;
10299}
10300
Chris Lattner27b695d2007-11-06 21:52:06 +000010301/// PHIsEqualValue - Return true if this phi node is always equal to
10302/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10303/// z = some value; x = phi (y, z); y = phi (x, z)
10304static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10305 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10306 // See if we already saw this PHI node.
10307 if (!ValueEqualPHIs.insert(PN))
10308 return true;
10309
10310 // Don't scan crazily complex things.
10311 if (ValueEqualPHIs.size() == 16)
10312 return false;
10313
10314 // Scan the operands to see if they are either phi nodes or are equal to
10315 // the value.
10316 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10317 Value *Op = PN->getIncomingValue(i);
10318 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10319 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10320 return false;
10321 } else if (Op != NonPhiInVal)
10322 return false;
10323 }
10324
10325 return true;
10326}
10327
10328
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010329// PHINode simplification
10330//
10331Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10332 // If LCSSA is around, don't mess with Phi nodes
10333 if (MustPreserveLCSSA) return 0;
10334
10335 if (Value *V = PN.hasConstantValue())
10336 return ReplaceInstUsesWith(PN, V);
10337
10338 // If all PHI operands are the same operation, pull them through the PHI,
10339 // reducing code size.
10340 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010341 isa<Instruction>(PN.getIncomingValue(1)) &&
10342 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10343 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10344 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10345 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010346 PN.getIncomingValue(0)->hasOneUse())
10347 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10348 return Result;
10349
10350 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10351 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10352 // PHI)... break the cycle.
10353 if (PN.hasOneUse()) {
10354 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10355 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10356 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10357 PotentiallyDeadPHIs.insert(&PN);
10358 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10359 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10360 }
10361
10362 // If this phi has a single use, and if that use just computes a value for
10363 // the next iteration of a loop, delete the phi. This occurs with unused
10364 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10365 // common case here is good because the only other things that catch this
10366 // are induction variable analysis (sometimes) and ADCE, which is only run
10367 // late.
10368 if (PHIUser->hasOneUse() &&
10369 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10370 PHIUser->use_back() == &PN) {
10371 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10372 }
10373 }
10374
Chris Lattner27b695d2007-11-06 21:52:06 +000010375 // We sometimes end up with phi cycles that non-obviously end up being the
10376 // same value, for example:
10377 // z = some value; x = phi (y, z); y = phi (x, z)
10378 // where the phi nodes don't necessarily need to be in the same block. Do a
10379 // quick check to see if the PHI node only contains a single non-phi value, if
10380 // so, scan to see if the phi cycle is actually equal to that value.
10381 {
10382 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10383 // Scan for the first non-phi operand.
10384 while (InValNo != NumOperandVals &&
10385 isa<PHINode>(PN.getIncomingValue(InValNo)))
10386 ++InValNo;
10387
10388 if (InValNo != NumOperandVals) {
10389 Value *NonPhiInVal = PN.getOperand(InValNo);
10390
10391 // Scan the rest of the operands to see if there are any conflicts, if so
10392 // there is no need to recursively scan other phis.
10393 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10394 Value *OpVal = PN.getIncomingValue(InValNo);
10395 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10396 break;
10397 }
10398
10399 // If we scanned over all operands, then we have one unique value plus
10400 // phi values. Scan PHI nodes to see if they all merge in each other or
10401 // the value.
10402 if (InValNo == NumOperandVals) {
10403 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10404 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10405 return ReplaceInstUsesWith(PN, NonPhiInVal);
10406 }
10407 }
10408 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010409 return 0;
10410}
10411
10412static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10413 Instruction *InsertPoint,
10414 InstCombiner *IC) {
10415 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10416 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10417 // We must cast correctly to the pointer type. Ensure that we
10418 // sign extend the integer value if it is smaller as this is
10419 // used for address computation.
10420 Instruction::CastOps opcode =
10421 (VTySize < PtrSize ? Instruction::SExt :
10422 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10423 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10424}
10425
10426
10427Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10428 Value *PtrOp = GEP.getOperand(0);
10429 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10430 // If so, eliminate the noop.
10431 if (GEP.getNumOperands() == 1)
10432 return ReplaceInstUsesWith(GEP, PtrOp);
10433
10434 if (isa<UndefValue>(GEP.getOperand(0)))
10435 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10436
10437 bool HasZeroPointerIndex = false;
10438 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10439 HasZeroPointerIndex = C->isNullValue();
10440
10441 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10442 return ReplaceInstUsesWith(GEP, PtrOp);
10443
10444 // Eliminate unneeded casts for indices.
10445 bool MadeChange = false;
10446
10447 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif17396002008-06-12 21:37:33 +000010448 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10449 i != e; ++i, ++GTI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010450 if (isa<SequentialType>(*GTI)) {
Gabor Greif17396002008-06-12 21:37:33 +000010451 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010452 if (CI->getOpcode() == Instruction::ZExt ||
10453 CI->getOpcode() == Instruction::SExt) {
10454 const Type *SrcTy = CI->getOperand(0)->getType();
10455 // We can eliminate a cast from i32 to i64 iff the target
10456 // is a 32-bit pointer target.
10457 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10458 MadeChange = true;
Gabor Greif17396002008-06-12 21:37:33 +000010459 *i = CI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010460 }
10461 }
10462 }
10463 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman5d639ed2008-09-11 23:06:38 +000010464 // to what we need. If narrower, sign-extend it to what we need.
10465 // If the incoming value needs a cast instruction,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010466 // insert it. This explicit cast can make subsequent optimizations more
10467 // obvious.
Gabor Greif17396002008-06-12 21:37:33 +000010468 Value *Op = *i;
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010469 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010470 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif17396002008-06-12 21:37:33 +000010471 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010472 MadeChange = true;
10473 } else {
10474 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10475 GEP);
Gabor Greif17396002008-06-12 21:37:33 +000010476 *i = Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010477 MadeChange = true;
10478 }
Dan Gohman5d639ed2008-09-11 23:06:38 +000010479 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10480 if (Constant *C = dyn_cast<Constant>(Op)) {
10481 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10482 MadeChange = true;
10483 } else {
10484 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10485 GEP);
10486 *i = Op;
10487 MadeChange = true;
10488 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010489 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010490 }
10491 }
10492 if (MadeChange) return &GEP;
10493
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010494 // Combine Indices - If the source pointer to this getelementptr instruction
10495 // is a getelementptr instruction, combine the indices of the two
10496 // getelementptr instructions into a single instruction.
10497 //
10498 SmallVector<Value*, 8> SrcGEPOperands;
10499 if (User *Src = dyn_castGetElementPtr(PtrOp))
10500 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10501
10502 if (!SrcGEPOperands.empty()) {
10503 // Note that if our source is a gep chain itself that we wait for that
10504 // chain to be resolved before we perform this transformation. This
10505 // avoids us creating a TON of code in some cases.
10506 //
10507 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10508 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10509 return 0; // Wait until our source is folded to completion.
10510
10511 SmallVector<Value*, 8> Indices;
10512
10513 // Find out whether the last index in the source GEP is a sequential idx.
10514 bool EndsWithSequential = false;
10515 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10516 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10517 EndsWithSequential = !isa<StructType>(*I);
10518
10519 // Can we combine the two pointer arithmetics offsets?
10520 if (EndsWithSequential) {
10521 // Replace: gep (gep %P, long B), long A, ...
10522 // With: T = long A+B; gep %P, T, ...
10523 //
10524 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10525 if (SO1 == Constant::getNullValue(SO1->getType())) {
10526 Sum = GO1;
10527 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10528 Sum = SO1;
10529 } else {
10530 // If they aren't the same type, convert both to an integer of the
10531 // target's pointer size.
10532 if (SO1->getType() != GO1->getType()) {
10533 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10534 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10535 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10536 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10537 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010538 unsigned PS = TD->getPointerSizeInBits();
10539 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010540 // Convert GO1 to SO1's type.
10541 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10542
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010543 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010544 // Convert SO1 to GO1's type.
10545 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10546 } else {
10547 const Type *PT = TD->getIntPtrType();
10548 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10549 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10550 }
10551 }
10552 }
10553 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10554 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10555 else {
Gabor Greifa645dd32008-05-16 19:29:10 +000010556 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010557 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10558 }
10559 }
10560
10561 // Recycle the GEP we already have if possible.
10562 if (SrcGEPOperands.size() == 2) {
10563 GEP.setOperand(0, SrcGEPOperands[0]);
10564 GEP.setOperand(1, Sum);
10565 return &GEP;
10566 } else {
10567 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10568 SrcGEPOperands.end()-1);
10569 Indices.push_back(Sum);
10570 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10571 }
10572 } else if (isa<Constant>(*GEP.idx_begin()) &&
10573 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10574 SrcGEPOperands.size() != 1) {
10575 // Otherwise we can do the fold if the first index of the GEP is a zero
10576 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10577 SrcGEPOperands.end());
10578 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10579 }
10580
10581 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +000010582 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10583 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010584
10585 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10586 // GEP of global variable. If all of the indices for this GEP are
10587 // constants, we can promote this to a constexpr instead of an instruction.
10588
10589 // Scan for nonconstants...
10590 SmallVector<Constant*, 8> Indices;
10591 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10592 for (; I != E && isa<Constant>(*I); ++I)
10593 Indices.push_back(cast<Constant>(*I));
10594
10595 if (I == E) { // If they are all constants...
10596 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10597 &Indices[0],Indices.size());
10598
10599 // Replace all uses of the GEP with the new constexpr...
10600 return ReplaceInstUsesWith(GEP, CE);
10601 }
10602 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
10603 if (!isa<PointerType>(X->getType())) {
10604 // Not interesting. Source pointer must be a cast from pointer.
10605 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010606 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10607 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010608 //
10609 // This occurs when the program declares an array extern like "int X[];"
10610 //
10611 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10612 const PointerType *XTy = cast<PointerType>(X->getType());
10613 if (const ArrayType *XATy =
10614 dyn_cast<ArrayType>(XTy->getElementType()))
10615 if (const ArrayType *CATy =
10616 dyn_cast<ArrayType>(CPTy->getElementType()))
10617 if (CATy->getElementType() == XATy->getElementType()) {
10618 // At this point, we know that the cast source type is a pointer
10619 // to an array of the same type as the destination pointer
10620 // array. Because the array type is never stepped over (there
10621 // is a leading zero) we can fold the cast into this GEP.
10622 GEP.setOperand(0, X);
10623 return &GEP;
10624 }
10625 } else if (GEP.getNumOperands() == 2) {
10626 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010627 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10628 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010629 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10630 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10631 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsd68f13b2009-01-12 20:38:59 +000010632 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10633 TD->getTypePaddedSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000010634 Value *Idx[2];
10635 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10636 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010637 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +000010638 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010639 // V and GEP are both pointer types --> BitCast
10640 return new BitCastInst(V, GEP.getType());
10641 }
10642
10643 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010644 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010645 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010646 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010647
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010648 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010649 uint64_t ArrayEltSize =
Duncan Sandsd68f13b2009-01-12 20:38:59 +000010650 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010651
10652 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10653 // allow either a mul, shift, or constant here.
10654 Value *NewIdx = 0;
10655 ConstantInt *Scale = 0;
10656 if (ArrayEltSize == 1) {
10657 NewIdx = GEP.getOperand(1);
10658 Scale = ConstantInt::get(NewIdx->getType(), 1);
10659 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10660 NewIdx = ConstantInt::get(CI->getType(), 1);
10661 Scale = CI;
10662 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10663 if (Inst->getOpcode() == Instruction::Shl &&
10664 isa<ConstantInt>(Inst->getOperand(1))) {
10665 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10666 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10667 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10668 NewIdx = Inst->getOperand(0);
10669 } else if (Inst->getOpcode() == Instruction::Mul &&
10670 isa<ConstantInt>(Inst->getOperand(1))) {
10671 Scale = cast<ConstantInt>(Inst->getOperand(1));
10672 NewIdx = Inst->getOperand(0);
10673 }
10674 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010675
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010676 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010677 // out, perform the transformation. Note, we don't know whether Scale is
10678 // signed or not. We'll use unsigned version of division/modulo
10679 // operation after making sure Scale doesn't have the sign bit set.
10680 if (Scale && Scale->getSExtValue() >= 0LL &&
10681 Scale->getZExtValue() % ArrayEltSize == 0) {
10682 Scale = ConstantInt::get(Scale->getType(),
10683 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010684 if (Scale->getZExtValue() != 1) {
10685 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010686 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000010687 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010688 NewIdx = InsertNewInstBefore(Sc, GEP);
10689 }
10690
10691 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000010692 Value *Idx[2];
10693 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10694 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010695 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000010696 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010697 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10698 // The NewGEP must be pointer typed, so must the old one -> BitCast
10699 return new BitCastInst(NewGEP, GEP.getType());
10700 }
10701 }
10702 }
10703 }
Chris Lattner111ea772009-01-09 04:53:57 +000010704
Chris Lattner94ccd5f2009-01-09 05:44:56 +000010705 /// See if we can simplify:
10706 /// X = bitcast A to B*
10707 /// Y = gep X, <...constant indices...>
10708 /// into a gep of the original struct. This is important for SROA and alias
10709 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000010710 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000010711 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10712 // Determine how much the GEP moves the pointer. We are guaranteed to get
10713 // a constant back from EmitGEPOffset.
10714 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10715 int64_t Offset = OffsetV->getSExtValue();
10716
10717 // If this GEP instruction doesn't move the pointer, just replace the GEP
10718 // with a bitcast of the real input to the dest type.
10719 if (Offset == 0) {
10720 // If the bitcast is of an allocation, and the allocation will be
10721 // converted to match the type of the cast, don't touch this.
10722 if (isa<AllocationInst>(BCI->getOperand(0))) {
10723 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10724 if (Instruction *I = visitBitCast(*BCI)) {
10725 if (I != BCI) {
10726 I->takeName(BCI);
10727 BCI->getParent()->getInstList().insert(BCI, I);
10728 ReplaceInstUsesWith(*BCI, I);
10729 }
10730 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000010731 }
Chris Lattner111ea772009-01-09 04:53:57 +000010732 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000010733 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000010734 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000010735
10736 // Otherwise, if the offset is non-zero, we need to find out if there is a
10737 // field at Offset in 'A's type. If so, we can pull the cast through the
10738 // GEP.
10739 SmallVector<Value*, 8> NewIndices;
10740 const Type *InTy =
10741 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10742 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10743 Instruction *NGEP =
10744 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10745 NewIndices.end());
10746 if (NGEP->getType() == GEP.getType()) return NGEP;
10747 InsertNewInstBefore(NGEP, GEP);
10748 NGEP->takeName(&GEP);
10749 return new BitCastInst(NGEP, GEP.getType());
10750 }
Chris Lattner111ea772009-01-09 04:53:57 +000010751 }
10752 }
10753
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010754 return 0;
10755}
10756
10757Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10758 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010759 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010760 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10761 const Type *NewTy =
10762 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10763 AllocationInst *New = 0;
10764
10765 // Create and insert the replacement instruction...
10766 if (isa<MallocInst>(AI))
10767 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10768 else {
10769 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10770 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10771 }
10772
10773 InsertNewInstBefore(New, AI);
10774
10775 // Scan to the end of the allocation instructions, to skip over a block of
10776 // allocas if possible...
10777 //
10778 BasicBlock::iterator It = New;
10779 while (isa<AllocationInst>(*It)) ++It;
10780
10781 // Now that I is pointing to the first non-allocation-inst in the block,
10782 // insert our getelementptr instruction...
10783 //
10784 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000010785 Value *Idx[2];
10786 Idx[0] = NullIdx;
10787 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000010788 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10789 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010790
10791 // Now make everything use the getelementptr instead of the original
10792 // allocation.
10793 return ReplaceInstUsesWith(AI, V);
10794 } else if (isa<UndefValue>(AI.getArraySize())) {
10795 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10796 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010797 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010798
Dan Gohman28e78f02009-01-13 20:18:38 +000010799 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10800 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10801 // Note that we only do this for alloca's, because malloc should allocate and
10802 // return a unique pointer, even for a zero byte allocation.
10803 if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10804 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10805
10806 // If the alignment is 0 (unspecified), assign it the preferred alignment.
10807 if (AI.getAlignment() == 0)
10808 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10809 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010810
10811 return 0;
10812}
10813
10814Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10815 Value *Op = FI.getOperand(0);
10816
10817 // free undef -> unreachable.
10818 if (isa<UndefValue>(Op)) {
10819 // Insert a new store to null because we cannot modify the CFG here.
10820 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000010821 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010822 return EraseInstFromFunction(FI);
10823 }
10824
10825 // If we have 'free null' delete the instruction. This can happen in stl code
10826 // when lots of inlining happens.
10827 if (isa<ConstantPointerNull>(Op))
10828 return EraseInstFromFunction(FI);
10829
10830 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10831 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10832 FI.setOperand(0, CI->getOperand(0));
10833 return &FI;
10834 }
10835
10836 // Change free (gep X, 0,0,0,0) into free(X)
10837 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10838 if (GEPI->hasAllZeroIndices()) {
10839 AddToWorkList(GEPI);
10840 FI.setOperand(0, GEPI->getOperand(0));
10841 return &FI;
10842 }
10843 }
10844
10845 // Change free(malloc) into nothing, if the malloc has a single use.
10846 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10847 if (MI->hasOneUse()) {
10848 EraseInstFromFunction(FI);
10849 return EraseInstFromFunction(*MI);
10850 }
10851
10852 return 0;
10853}
10854
10855
10856/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000010857static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000010858 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010859 User *CI = cast<User>(LI.getOperand(0));
10860 Value *CastOp = CI->getOperand(0);
10861
Devang Patela0f8ea82007-10-18 19:52:32 +000010862 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10863 // Instead of loading constant c string, use corresponding integer value
10864 // directly if string length is small enough.
Evan Cheng833501d2008-06-30 07:31:25 +000010865 std::string Str;
10866 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000010867 unsigned len = Str.length();
10868 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10869 unsigned numBits = Ty->getPrimitiveSizeInBits();
10870 // Replace LI with immediate integer store.
10871 if ((numBits >> 3) == len + 1) {
Bill Wendling44a36ea2008-02-26 10:53:30 +000010872 APInt StrVal(numBits, 0);
10873 APInt SingleChar(numBits, 0);
10874 if (TD->isLittleEndian()) {
10875 for (signed i = len-1; i >= 0; i--) {
10876 SingleChar = (uint64_t) Str[i];
10877 StrVal = (StrVal << 8) | SingleChar;
10878 }
10879 } else {
10880 for (unsigned i = 0; i < len; i++) {
10881 SingleChar = (uint64_t) Str[i];
10882 StrVal = (StrVal << 8) | SingleChar;
10883 }
10884 // Append NULL at the end.
10885 SingleChar = 0;
10886 StrVal = (StrVal << 8) | SingleChar;
10887 }
10888 Value *NL = ConstantInt::get(StrVal);
10889 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patela0f8ea82007-10-18 19:52:32 +000010890 }
10891 }
10892 }
10893
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010894 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10895 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10896 const Type *SrcPTy = SrcTy->getElementType();
10897
10898 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10899 isa<VectorType>(DestPTy)) {
10900 // If the source is an array, the code below will not succeed. Check to
10901 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10902 // constants.
10903 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10904 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10905 if (ASrcTy->getNumElements() != 0) {
10906 Value *Idxs[2];
10907 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10908 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10909 SrcTy = cast<PointerType>(CastOp->getType());
10910 SrcPTy = SrcTy->getElementType();
10911 }
10912
10913 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10914 isa<VectorType>(SrcPTy)) &&
10915 // Do not allow turning this into a load of an integer, which is then
10916 // casted to a pointer, this pessimizes pointer analysis a lot.
10917 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10918 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10919 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10920
10921 // Okay, we are casting from one integer or pointer type to another of
10922 // the same size. Instead of casting the pointer before the load, cast
10923 // the result of the loaded value.
10924 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10925 CI->getName(),
10926 LI.isVolatile()),LI);
10927 // Now cast the result of the load.
10928 return new BitCastInst(NewLoad, LI.getType());
10929 }
10930 }
10931 }
10932 return 0;
10933}
10934
10935/// isSafeToLoadUnconditionally - Return true if we know that executing a load
10936/// from this value cannot trap. If it is not obviously safe to load from the
10937/// specified pointer, we do a quick local scan of the basic block containing
10938/// ScanFrom, to determine if the address is already accessed.
10939static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010940 // If it is an alloca it is always safe to load from.
10941 if (isa<AllocaInst>(V)) return true;
10942
Duncan Sandse40a94a2007-09-19 10:25:38 +000010943 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010944 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +000010945 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010946 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010947
10948 // Otherwise, be a little bit agressive by scanning the local block where we
10949 // want to check to see if the pointer is already being loaded or stored
10950 // from/to. If so, the previous load or store would have already trapped,
10951 // so there is no harm doing an extra load (also, CSE will later eliminate
10952 // the load entirely).
10953 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10954
10955 while (BBI != E) {
10956 --BBI;
10957
Chris Lattner476983a2008-06-20 05:12:56 +000010958 // If we see a free or a call (which might do a free) the pointer could be
10959 // marked invalid.
10960 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10961 return false;
10962
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010963 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10964 if (LI->getOperand(0) == V) return true;
Chris Lattner476983a2008-06-20 05:12:56 +000010965 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010966 if (SI->getOperand(1) == V) return true;
Chris Lattner476983a2008-06-20 05:12:56 +000010967 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010968
10969 }
10970 return false;
10971}
10972
10973Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10974 Value *Op = LI.getOperand(0);
10975
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010976 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010977 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10978 if (KnownAlign >
10979 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10980 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010981 LI.setAlignment(KnownAlign);
10982
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010983 // load (cast X) --> cast (load X) iff safe
10984 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000010985 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010986 return Res;
10987
10988 // None of the following transforms are legal for volatile loads.
10989 if (LI.isVolatile()) return 0;
10990
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000010991 // Do really simple store-to-load forwarding and load CSE, to catch cases
10992 // where there are several consequtive memory accesses to the same location,
10993 // separated by a few arithmetic operations.
10994 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000010995 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
10996 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010997
Christopher Lamb2c175392007-12-29 07:56:53 +000010998 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10999 const Value *GEPI0 = GEPI->getOperand(0);
11000 // TODO: Consider a target hook for valid address spaces for this xform.
11001 if (isa<ConstantPointerNull>(GEPI0) &&
11002 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011003 // Insert a new store to null instruction before the load to indicate
11004 // that this code is not reachable. We do this instead of inserting
11005 // an unreachable instruction directly because we cannot modify the
11006 // CFG.
11007 new StoreInst(UndefValue::get(LI.getType()),
11008 Constant::getNullValue(Op->getType()), &LI);
11009 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11010 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011011 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011012
11013 if (Constant *C = dyn_cast<Constant>(Op)) {
11014 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000011015 // TODO: Consider a target hook for valid address spaces for this xform.
11016 if (isa<UndefValue>(C) || (C->isNullValue() &&
11017 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011018 // Insert a new store to null instruction before the load to indicate that
11019 // this code is not reachable. We do this instead of inserting an
11020 // unreachable instruction directly because we cannot modify the CFG.
11021 new StoreInst(UndefValue::get(LI.getType()),
11022 Constant::getNullValue(Op->getType()), &LI);
11023 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11024 }
11025
11026 // Instcombine load (constant global) into the value loaded.
11027 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11028 if (GV->isConstant() && !GV->isDeclaration())
11029 return ReplaceInstUsesWith(LI, GV->getInitializer());
11030
11031 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011032 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011033 if (CE->getOpcode() == Instruction::GetElementPtr) {
11034 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11035 if (GV->isConstant() && !GV->isDeclaration())
11036 if (Constant *V =
11037 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11038 return ReplaceInstUsesWith(LI, V);
11039 if (CE->getOperand(0)->isNullValue()) {
11040 // Insert a new store to null instruction before the load to indicate
11041 // that this code is not reachable. We do this instead of inserting
11042 // an unreachable instruction directly because we cannot modify the
11043 // CFG.
11044 new StoreInst(UndefValue::get(LI.getType()),
11045 Constant::getNullValue(Op->getType()), &LI);
11046 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11047 }
11048
11049 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000011050 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011051 return Res;
11052 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011053 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011054 }
Chris Lattner0270a112007-08-11 18:48:48 +000011055
11056 // If this load comes from anywhere in a constant global, and if the global
11057 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000011058 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Chris Lattner0270a112007-08-11 18:48:48 +000011059 if (GV->isConstant() && GV->hasInitializer()) {
11060 if (GV->getInitializer()->isNullValue())
11061 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11062 else if (isa<UndefValue>(GV->getInitializer()))
11063 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11064 }
11065 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011066
11067 if (Op->hasOneUse()) {
11068 // Change select and PHI nodes to select values instead of addresses: this
11069 // helps alias analysis out a lot, allows many others simplifications, and
11070 // exposes redundancy in the code.
11071 //
11072 // Note that we cannot do the transformation unless we know that the
11073 // introduced loads cannot trap! Something like this is valid as long as
11074 // the condition is always false: load (select bool %C, int* null, int* %G),
11075 // but it would not be valid if we transformed it to load from null
11076 // unconditionally.
11077 //
11078 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11079 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11080 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11081 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11082 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11083 SI->getOperand(1)->getName()+".val"), LI);
11084 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11085 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000011086 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011087 }
11088
11089 // load (select (cond, null, P)) -> load P
11090 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11091 if (C->isNullValue()) {
11092 LI.setOperand(0, SI->getOperand(2));
11093 return &LI;
11094 }
11095
11096 // load (select (cond, P, null)) -> load P
11097 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11098 if (C->isNullValue()) {
11099 LI.setOperand(0, SI->getOperand(1));
11100 return &LI;
11101 }
11102 }
11103 }
11104 return 0;
11105}
11106
11107/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011108/// when possible. This makes it generally easy to do alias analysis and/or
11109/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011110static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11111 User *CI = cast<User>(SI.getOperand(1));
11112 Value *CastOp = CI->getOperand(0);
11113
11114 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011115 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11116 if (SrcTy == 0) return 0;
11117
11118 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011119
Chris Lattnera032c0e2009-01-16 20:08:59 +000011120 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11121 return 0;
11122
Chris Lattner54dddc72009-01-24 01:00:13 +000011123 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11124 /// to its first element. This allows us to handle things like:
11125 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11126 /// on 32-bit hosts.
11127 SmallVector<Value*, 4> NewGEPIndices;
11128
Chris Lattnera032c0e2009-01-16 20:08:59 +000011129 // If the source is an array, the code below will not succeed. Check to
11130 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11131 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011132 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11133 // Index through pointer.
11134 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11135 NewGEPIndices.push_back(Zero);
11136
11137 while (1) {
11138 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011139 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011140 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011141 NewGEPIndices.push_back(Zero);
11142 SrcPTy = STy->getElementType(0);
11143 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11144 NewGEPIndices.push_back(Zero);
11145 SrcPTy = ATy->getElementType();
11146 } else {
11147 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011148 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011149 }
11150
11151 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11152 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011153
11154 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11155 return 0;
11156
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011157 // If the pointers point into different address spaces or if they point to
11158 // values with different sizes, we can't do the transformation.
11159 if (SrcTy->getAddressSpace() !=
11160 cast<PointerType>(CI->getType())->getAddressSpace() ||
11161 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattnera032c0e2009-01-16 20:08:59 +000011162 IC.getTargetData().getTypeSizeInBits(DestPTy))
11163 return 0;
11164
11165 // Okay, we are casting from one integer or pointer type to another of
11166 // the same size. Instead of casting the pointer before
11167 // the store, cast the value to be stored.
11168 Value *NewCast;
11169 Value *SIOp0 = SI.getOperand(0);
11170 Instruction::CastOps opcode = Instruction::BitCast;
11171 const Type* CastSrcTy = SIOp0->getType();
11172 const Type* CastDstTy = SrcPTy;
11173 if (isa<PointerType>(CastDstTy)) {
11174 if (CastSrcTy->isInteger())
11175 opcode = Instruction::IntToPtr;
11176 } else if (isa<IntegerType>(CastDstTy)) {
11177 if (isa<PointerType>(SIOp0->getType()))
11178 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011179 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011180
11181 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11182 // emit a GEP to index into its first field.
11183 if (!NewGEPIndices.empty()) {
11184 if (Constant *C = dyn_cast<Constant>(CastOp))
11185 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11186 NewGEPIndices.size());
11187 else
11188 CastOp = IC.InsertNewInstBefore(
11189 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11190 NewGEPIndices.end()), SI);
11191 }
11192
Chris Lattnera032c0e2009-01-16 20:08:59 +000011193 if (Constant *C = dyn_cast<Constant>(SIOp0))
11194 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11195 else
11196 NewCast = IC.InsertNewInstBefore(
11197 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11198 SI);
11199 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011200}
11201
Chris Lattner6fd8c802008-11-27 08:56:30 +000011202/// equivalentAddressValues - Test if A and B will obviously have the same
11203/// value. This includes recognizing that %t0 and %t1 will have the same
11204/// value in code like this:
11205/// %t0 = getelementptr @a, 0, 3
11206/// store i32 0, i32* %t0
11207/// %t1 = getelementptr @a, 0, 3
11208/// %t2 = load i32* %t1
11209///
11210static bool equivalentAddressValues(Value *A, Value *B) {
11211 // Test if the values are trivially equivalent.
11212 if (A == B) return true;
11213
11214 // Test if the values come form identical arithmetic instructions.
11215 if (isa<BinaryOperator>(A) ||
11216 isa<CastInst>(A) ||
11217 isa<PHINode>(A) ||
11218 isa<GetElementPtrInst>(A))
11219 if (Instruction *BI = dyn_cast<Instruction>(B))
11220 if (cast<Instruction>(A)->isIdenticalTo(BI))
11221 return true;
11222
11223 // Otherwise they may not be equivalent.
11224 return false;
11225}
11226
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011227Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11228 Value *Val = SI.getOperand(0);
11229 Value *Ptr = SI.getOperand(1);
11230
11231 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11232 EraseInstFromFunction(SI);
11233 ++NumCombined;
11234 return 0;
11235 }
11236
11237 // If the RHS is an alloca with a single use, zapify the store, making the
11238 // alloca dead.
Chris Lattnera02bacc2008-04-29 04:58:38 +000011239 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011240 if (isa<AllocaInst>(Ptr)) {
11241 EraseInstFromFunction(SI);
11242 ++NumCombined;
11243 return 0;
11244 }
11245
11246 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11247 if (isa<AllocaInst>(GEP->getOperand(0)) &&
11248 GEP->getOperand(0)->hasOneUse()) {
11249 EraseInstFromFunction(SI);
11250 ++NumCombined;
11251 return 0;
11252 }
11253 }
11254
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011255 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000011256 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11257 if (KnownAlign >
11258 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11259 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011260 SI.setAlignment(KnownAlign);
11261
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011262 // Do really simple DSE, to catch cases where there are several consequtive
11263 // stores to the same location, separated by a few arithmetic operations. This
11264 // situation often occurs with bitfield accesses.
11265 BasicBlock::iterator BBI = &SI;
11266 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11267 --ScanInsts) {
11268 --BBI;
11269
11270 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11271 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011272 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11273 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011274 ++NumDeadStore;
11275 ++BBI;
11276 EraseInstFromFunction(*PrevSI);
11277 continue;
11278 }
11279 break;
11280 }
11281
11282 // If this is a load, we have to stop. However, if the loaded value is from
11283 // the pointer we're loading and is producing the pointer we're storing,
11284 // then *this* store is dead (X = load P; store X -> P).
11285 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011286 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11287 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011288 EraseInstFromFunction(SI);
11289 ++NumCombined;
11290 return 0;
11291 }
11292 // Otherwise, this is a load from some other location. Stores before it
11293 // may not be dead.
11294 break;
11295 }
11296
11297 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011298 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011299 break;
11300 }
11301
11302
11303 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11304
11305 // store X, null -> turns into 'unreachable' in SimplifyCFG
11306 if (isa<ConstantPointerNull>(Ptr)) {
11307 if (!isa<UndefValue>(Val)) {
11308 SI.setOperand(0, UndefValue::get(Val->getType()));
11309 if (Instruction *U = dyn_cast<Instruction>(Val))
11310 AddToWorkList(U); // Dropped a use.
11311 ++NumCombined;
11312 }
11313 return 0; // Do not modify these!
11314 }
11315
11316 // store undef, Ptr -> noop
11317 if (isa<UndefValue>(Val)) {
11318 EraseInstFromFunction(SI);
11319 ++NumCombined;
11320 return 0;
11321 }
11322
11323 // If the pointer destination is a cast, see if we can fold the cast into the
11324 // source instead.
11325 if (isa<CastInst>(Ptr))
11326 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11327 return Res;
11328 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11329 if (CE->isCast())
11330 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11331 return Res;
11332
11333
11334 // If this store is the last instruction in the basic block, and if the block
11335 // ends with an unconditional branch, try to move it to the successor block.
11336 BBI = &SI; ++BBI;
11337 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11338 if (BI->isUnconditional())
11339 if (SimplifyStoreAtEndOfBlock(SI))
11340 return 0; // xform done!
11341
11342 return 0;
11343}
11344
11345/// SimplifyStoreAtEndOfBlock - Turn things like:
11346/// if () { *P = v1; } else { *P = v2 }
11347/// into a phi node with a store in the successor.
11348///
11349/// Simplify things like:
11350/// *P = v1; if () { *P = v2; }
11351/// into a phi node with a store in the successor.
11352///
11353bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11354 BasicBlock *StoreBB = SI.getParent();
11355
11356 // Check to see if the successor block has exactly two incoming edges. If
11357 // so, see if the other predecessor contains a store to the same location.
11358 // if so, insert a PHI node (if needed) and move the stores down.
11359 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11360
11361 // Determine whether Dest has exactly two predecessors and, if so, compute
11362 // the other predecessor.
11363 pred_iterator PI = pred_begin(DestBB);
11364 BasicBlock *OtherBB = 0;
11365 if (*PI != StoreBB)
11366 OtherBB = *PI;
11367 ++PI;
11368 if (PI == pred_end(DestBB))
11369 return false;
11370
11371 if (*PI != StoreBB) {
11372 if (OtherBB)
11373 return false;
11374 OtherBB = *PI;
11375 }
11376 if (++PI != pred_end(DestBB))
11377 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000011378
11379 // Bail out if all the relevant blocks aren't distinct (this can happen,
11380 // for example, if SI is in an infinite loop)
11381 if (StoreBB == DestBB || OtherBB == DestBB)
11382 return false;
11383
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011384 // Verify that the other block ends in a branch and is not otherwise empty.
11385 BasicBlock::iterator BBI = OtherBB->getTerminator();
11386 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11387 if (!OtherBr || BBI == OtherBB->begin())
11388 return false;
11389
11390 // If the other block ends in an unconditional branch, check for the 'if then
11391 // else' case. there is an instruction before the branch.
11392 StoreInst *OtherStore = 0;
11393 if (OtherBr->isUnconditional()) {
11394 // If this isn't a store, or isn't a store to the same location, bail out.
11395 --BBI;
11396 OtherStore = dyn_cast<StoreInst>(BBI);
11397 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11398 return false;
11399 } else {
11400 // Otherwise, the other block ended with a conditional branch. If one of the
11401 // destinations is StoreBB, then we have the if/then case.
11402 if (OtherBr->getSuccessor(0) != StoreBB &&
11403 OtherBr->getSuccessor(1) != StoreBB)
11404 return false;
11405
11406 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11407 // if/then triangle. See if there is a store to the same ptr as SI that
11408 // lives in OtherBB.
11409 for (;; --BBI) {
11410 // Check to see if we find the matching store.
11411 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11412 if (OtherStore->getOperand(1) != SI.getOperand(1))
11413 return false;
11414 break;
11415 }
Eli Friedman3a311d52008-06-13 22:02:12 +000011416 // If we find something that may be using or overwriting the stored
11417 // value, or if we run out of instructions, we can't do the xform.
11418 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011419 BBI == OtherBB->begin())
11420 return false;
11421 }
11422
11423 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000011424 // make sure nothing reads or overwrites the stored value in
11425 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011426 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11427 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000011428 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011429 return false;
11430 }
11431 }
11432
11433 // Insert a PHI node now if we need it.
11434 Value *MergedVal = OtherStore->getOperand(0);
11435 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000011436 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011437 PN->reserveOperandSpace(2);
11438 PN->addIncoming(SI.getOperand(0), SI.getParent());
11439 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11440 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11441 }
11442
11443 // Advance to a place where it is safe to insert the new store and
11444 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000011445 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011446 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11447 OtherStore->isVolatile()), *BBI);
11448
11449 // Nuke the old stores.
11450 EraseInstFromFunction(SI);
11451 EraseInstFromFunction(*OtherStore);
11452 ++NumCombined;
11453 return true;
11454}
11455
11456
11457Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11458 // Change br (not X), label True, label False to: br X, label False, True
11459 Value *X = 0;
11460 BasicBlock *TrueDest;
11461 BasicBlock *FalseDest;
11462 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11463 !isa<Constant>(X)) {
11464 // Swap Destinations and condition...
11465 BI.setCondition(X);
11466 BI.setSuccessor(0, FalseDest);
11467 BI.setSuccessor(1, TrueDest);
11468 return &BI;
11469 }
11470
11471 // Cannonicalize fcmp_one -> fcmp_oeq
11472 FCmpInst::Predicate FPred; Value *Y;
11473 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11474 TrueDest, FalseDest)))
11475 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11476 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11477 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11478 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11479 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11480 NewSCC->takeName(I);
11481 // Swap Destinations and condition...
11482 BI.setCondition(NewSCC);
11483 BI.setSuccessor(0, FalseDest);
11484 BI.setSuccessor(1, TrueDest);
11485 RemoveFromWorkList(I);
11486 I->eraseFromParent();
11487 AddToWorkList(NewSCC);
11488 return &BI;
11489 }
11490
11491 // Cannonicalize icmp_ne -> icmp_eq
11492 ICmpInst::Predicate IPred;
11493 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11494 TrueDest, FalseDest)))
11495 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11496 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11497 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11498 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11499 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11500 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11501 NewSCC->takeName(I);
11502 // Swap Destinations and condition...
11503 BI.setCondition(NewSCC);
11504 BI.setSuccessor(0, FalseDest);
11505 BI.setSuccessor(1, TrueDest);
11506 RemoveFromWorkList(I);
11507 I->eraseFromParent();;
11508 AddToWorkList(NewSCC);
11509 return &BI;
11510 }
11511
11512 return 0;
11513}
11514
11515Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11516 Value *Cond = SI.getCondition();
11517 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11518 if (I->getOpcode() == Instruction::Add)
11519 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11520 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11521 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11522 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11523 AddRHS));
11524 SI.setOperand(0, I->getOperand(0));
11525 AddToWorkList(I);
11526 return &SI;
11527 }
11528 }
11529 return 0;
11530}
11531
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011532Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011533 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011534
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011535 if (!EV.hasIndices())
11536 return ReplaceInstUsesWith(EV, Agg);
11537
11538 if (Constant *C = dyn_cast<Constant>(Agg)) {
11539 if (isa<UndefValue>(C))
11540 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11541
11542 if (isa<ConstantAggregateZero>(C))
11543 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11544
11545 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11546 // Extract the element indexed by the first index out of the constant
11547 Value *V = C->getOperand(*EV.idx_begin());
11548 if (EV.getNumIndices() > 1)
11549 // Extract the remaining indices out of the constant indexed by the
11550 // first index
11551 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11552 else
11553 return ReplaceInstUsesWith(EV, V);
11554 }
11555 return 0; // Can't handle other constants
11556 }
11557 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11558 // We're extracting from an insertvalue instruction, compare the indices
11559 const unsigned *exti, *exte, *insi, *inse;
11560 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11561 exte = EV.idx_end(), inse = IV->idx_end();
11562 exti != exte && insi != inse;
11563 ++exti, ++insi) {
11564 if (*insi != *exti)
11565 // The insert and extract both reference distinctly different elements.
11566 // This means the extract is not influenced by the insert, and we can
11567 // replace the aggregate operand of the extract with the aggregate
11568 // operand of the insert. i.e., replace
11569 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11570 // %E = extractvalue { i32, { i32 } } %I, 0
11571 // with
11572 // %E = extractvalue { i32, { i32 } } %A, 0
11573 return ExtractValueInst::Create(IV->getAggregateOperand(),
11574 EV.idx_begin(), EV.idx_end());
11575 }
11576 if (exti == exte && insi == inse)
11577 // Both iterators are at the end: Index lists are identical. Replace
11578 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11579 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11580 // with "i32 42"
11581 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11582 if (exti == exte) {
11583 // The extract list is a prefix of the insert list. i.e. replace
11584 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11585 // %E = extractvalue { i32, { i32 } } %I, 1
11586 // with
11587 // %X = extractvalue { i32, { i32 } } %A, 1
11588 // %E = insertvalue { i32 } %X, i32 42, 0
11589 // by switching the order of the insert and extract (though the
11590 // insertvalue should be left in, since it may have other uses).
11591 Value *NewEV = InsertNewInstBefore(
11592 ExtractValueInst::Create(IV->getAggregateOperand(),
11593 EV.idx_begin(), EV.idx_end()),
11594 EV);
11595 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11596 insi, inse);
11597 }
11598 if (insi == inse)
11599 // The insert list is a prefix of the extract list
11600 // We can simply remove the common indices from the extract and make it
11601 // operate on the inserted value instead of the insertvalue result.
11602 // i.e., replace
11603 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11604 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11605 // with
11606 // %E extractvalue { i32 } { i32 42 }, 0
11607 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11608 exti, exte);
11609 }
11610 // Can't simplify extracts from other values. Note that nested extracts are
11611 // already simplified implicitely by the above (extract ( extract (insert) )
11612 // will be translated into extract ( insert ( extract ) ) first and then just
11613 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011614 return 0;
11615}
11616
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011617/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11618/// is to leave as a vector operation.
11619static bool CheapToScalarize(Value *V, bool isConstant) {
11620 if (isa<ConstantAggregateZero>(V))
11621 return true;
11622 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11623 if (isConstant) return true;
11624 // If all elts are the same, we can extract.
11625 Constant *Op0 = C->getOperand(0);
11626 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11627 if (C->getOperand(i) != Op0)
11628 return false;
11629 return true;
11630 }
11631 Instruction *I = dyn_cast<Instruction>(V);
11632 if (!I) return false;
11633
11634 // Insert element gets simplified to the inserted element or is deleted if
11635 // this is constant idx extract element and its a constant idx insertelt.
11636 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11637 isa<ConstantInt>(I->getOperand(2)))
11638 return true;
11639 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11640 return true;
11641 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11642 if (BO->hasOneUse() &&
11643 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11644 CheapToScalarize(BO->getOperand(1), isConstant)))
11645 return true;
11646 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11647 if (CI->hasOneUse() &&
11648 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11649 CheapToScalarize(CI->getOperand(1), isConstant)))
11650 return true;
11651
11652 return false;
11653}
11654
11655/// Read and decode a shufflevector mask.
11656///
11657/// It turns undef elements into values that are larger than the number of
11658/// elements in the input.
11659static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11660 unsigned NElts = SVI->getType()->getNumElements();
11661 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11662 return std::vector<unsigned>(NElts, 0);
11663 if (isa<UndefValue>(SVI->getOperand(2)))
11664 return std::vector<unsigned>(NElts, 2*NElts);
11665
11666 std::vector<unsigned> Result;
11667 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000011668 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11669 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011670 Result.push_back(NElts*2); // undef -> 8
11671 else
Gabor Greif17396002008-06-12 21:37:33 +000011672 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011673 return Result;
11674}
11675
11676/// FindScalarElement - Given a vector and an element number, see if the scalar
11677/// value is already around as a register, for example if it were inserted then
11678/// extracted from the vector.
11679static Value *FindScalarElement(Value *V, unsigned EltNo) {
11680 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11681 const VectorType *PTy = cast<VectorType>(V->getType());
11682 unsigned Width = PTy->getNumElements();
11683 if (EltNo >= Width) // Out of range access.
11684 return UndefValue::get(PTy->getElementType());
11685
11686 if (isa<UndefValue>(V))
11687 return UndefValue::get(PTy->getElementType());
11688 else if (isa<ConstantAggregateZero>(V))
11689 return Constant::getNullValue(PTy->getElementType());
11690 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11691 return CP->getOperand(EltNo);
11692 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11693 // If this is an insert to a variable element, we don't know what it is.
11694 if (!isa<ConstantInt>(III->getOperand(2)))
11695 return 0;
11696 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11697
11698 // If this is an insert to the element we are looking for, return the
11699 // inserted value.
11700 if (EltNo == IIElt)
11701 return III->getOperand(1);
11702
11703 // Otherwise, the insertelement doesn't modify the value, recurse on its
11704 // vector input.
11705 return FindScalarElement(III->getOperand(0), EltNo);
11706 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000011707 unsigned LHSWidth =
11708 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011709 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000011710 if (InEl < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011711 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000011712 else if (InEl < LHSWidth*2)
11713 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011714 else
11715 return UndefValue::get(PTy->getElementType());
11716 }
11717
11718 // Otherwise, we don't know.
11719 return 0;
11720}
11721
11722Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011723 // If vector val is undef, replace extract with scalar undef.
11724 if (isa<UndefValue>(EI.getOperand(0)))
11725 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11726
11727 // If vector val is constant 0, replace extract with scalar 0.
11728 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11729 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11730
11731 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000011732 // If vector val is constant with all elements the same, replace EI with
11733 // that element. When the elements are not identical, we cannot replace yet
11734 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011735 Constant *op0 = C->getOperand(0);
11736 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11737 if (C->getOperand(i) != op0) {
11738 op0 = 0;
11739 break;
11740 }
11741 if (op0)
11742 return ReplaceInstUsesWith(EI, op0);
11743 }
11744
11745 // If extracting a specified index from the vector, see if we can recursively
11746 // find a previously computed scalar that was inserted into the vector.
11747 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11748 unsigned IndexVal = IdxC->getZExtValue();
11749 unsigned VectorWidth =
11750 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11751
11752 // If this is extracting an invalid index, turn this into undef, to avoid
11753 // crashing the code below.
11754 if (IndexVal >= VectorWidth)
11755 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11756
11757 // This instruction only demands the single element from the input vector.
11758 // If the input vector has a single use, simplify it based on this use
11759 // property.
11760 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11761 uint64_t UndefElts;
11762 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11763 1 << IndexVal,
11764 UndefElts)) {
11765 EI.setOperand(0, V);
11766 return &EI;
11767 }
11768 }
11769
11770 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11771 return ReplaceInstUsesWith(EI, Elt);
11772
11773 // If the this extractelement is directly using a bitcast from a vector of
11774 // the same number of elements, see if we can find the source element from
11775 // it. In this case, we will end up needing to bitcast the scalars.
11776 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11777 if (const VectorType *VT =
11778 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11779 if (VT->getNumElements() == VectorWidth)
11780 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11781 return new BitCastInst(Elt, EI.getType());
11782 }
11783 }
11784
11785 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11786 if (I->hasOneUse()) {
11787 // Push extractelement into predecessor operation if legal and
11788 // profitable to do so
11789 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11790 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11791 if (CheapToScalarize(BO, isConstantElt)) {
11792 ExtractElementInst *newEI0 =
11793 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11794 EI.getName()+".lhs");
11795 ExtractElementInst *newEI1 =
11796 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11797 EI.getName()+".rhs");
11798 InsertNewInstBefore(newEI0, EI);
11799 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000011800 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011801 }
11802 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000011803 unsigned AS =
11804 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000011805 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11806 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000011807 GetElementPtrInst *GEP =
11808 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011809 InsertNewInstBefore(GEP, EI);
11810 return new LoadInst(GEP);
11811 }
11812 }
11813 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11814 // Extracting the inserted element?
11815 if (IE->getOperand(2) == EI.getOperand(1))
11816 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11817 // If the inserted and extracted elements are constants, they must not
11818 // be the same value, extract from the pre-inserted value instead.
11819 if (isa<Constant>(IE->getOperand(2)) &&
11820 isa<Constant>(EI.getOperand(1))) {
11821 AddUsesToWorkList(EI);
11822 EI.setOperand(0, IE->getOperand(0));
11823 return &EI;
11824 }
11825 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11826 // If this is extracting an element from a shufflevector, figure out where
11827 // it came from and extract from the appropriate input element instead.
11828 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11829 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11830 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000011831 unsigned LHSWidth =
11832 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11833
11834 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011835 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000011836 else if (SrcIdx < LHSWidth*2) {
11837 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011838 Src = SVI->getOperand(1);
11839 } else {
11840 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11841 }
11842 return new ExtractElementInst(Src, SrcIdx);
11843 }
11844 }
11845 }
11846 return 0;
11847}
11848
11849/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11850/// elements from either LHS or RHS, return the shuffle mask and true.
11851/// Otherwise, return false.
11852static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11853 std::vector<Constant*> &Mask) {
11854 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11855 "Invalid CollectSingleShuffleElements");
11856 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11857
11858 if (isa<UndefValue>(V)) {
11859 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11860 return true;
11861 } else if (V == LHS) {
11862 for (unsigned i = 0; i != NumElts; ++i)
11863 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11864 return true;
11865 } else if (V == RHS) {
11866 for (unsigned i = 0; i != NumElts; ++i)
11867 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11868 return true;
11869 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11870 // If this is an insert of an extract from some other vector, include it.
11871 Value *VecOp = IEI->getOperand(0);
11872 Value *ScalarOp = IEI->getOperand(1);
11873 Value *IdxOp = IEI->getOperand(2);
11874
11875 if (!isa<ConstantInt>(IdxOp))
11876 return false;
11877 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11878
11879 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11880 // Okay, we can handle this if the vector we are insertinting into is
11881 // transitively ok.
11882 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11883 // If so, update the mask to reflect the inserted undef.
11884 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11885 return true;
11886 }
11887 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11888 if (isa<ConstantInt>(EI->getOperand(1)) &&
11889 EI->getOperand(0)->getType() == V->getType()) {
11890 unsigned ExtractedIdx =
11891 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11892
11893 // This must be extracting from either LHS or RHS.
11894 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11895 // Okay, we can handle this if the vector we are insertinting into is
11896 // transitively ok.
11897 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11898 // If so, update the mask to reflect the inserted value.
11899 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000011900 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011901 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11902 } else {
11903 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000011904 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011905 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11906
11907 }
11908 return true;
11909 }
11910 }
11911 }
11912 }
11913 }
11914 // TODO: Handle shufflevector here!
11915
11916 return false;
11917}
11918
11919/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11920/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11921/// that computes V and the LHS value of the shuffle.
11922static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11923 Value *&RHS) {
11924 assert(isa<VectorType>(V->getType()) &&
11925 (RHS == 0 || V->getType() == RHS->getType()) &&
11926 "Invalid shuffle!");
11927 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11928
11929 if (isa<UndefValue>(V)) {
11930 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11931 return V;
11932 } else if (isa<ConstantAggregateZero>(V)) {
11933 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11934 return V;
11935 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11936 // If this is an insert of an extract from some other vector, include it.
11937 Value *VecOp = IEI->getOperand(0);
11938 Value *ScalarOp = IEI->getOperand(1);
11939 Value *IdxOp = IEI->getOperand(2);
11940
11941 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11942 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11943 EI->getOperand(0)->getType() == V->getType()) {
11944 unsigned ExtractedIdx =
11945 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11946 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11947
11948 // Either the extracted from or inserted into vector must be RHSVec,
11949 // otherwise we'd end up with a shuffle of three inputs.
11950 if (EI->getOperand(0) == RHS || RHS == 0) {
11951 RHS = EI->getOperand(0);
11952 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000011953 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011954 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11955 return V;
11956 }
11957
11958 if (VecOp == RHS) {
11959 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11960 // Everything but the extracted element is replaced with the RHS.
11961 for (unsigned i = 0; i != NumElts; ++i) {
11962 if (i != InsertedIdx)
11963 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11964 }
11965 return V;
11966 }
11967
11968 // If this insertelement is a chain that comes from exactly these two
11969 // vectors, return the vector and the effective shuffle.
11970 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11971 return EI->getOperand(0);
11972
11973 }
11974 }
11975 }
11976 // TODO: Handle shufflevector here!
11977
11978 // Otherwise, can't do anything fancy. Return an identity vector.
11979 for (unsigned i = 0; i != NumElts; ++i)
11980 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11981 return V;
11982}
11983
11984Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11985 Value *VecOp = IE.getOperand(0);
11986 Value *ScalarOp = IE.getOperand(1);
11987 Value *IdxOp = IE.getOperand(2);
11988
11989 // Inserting an undef or into an undefined place, remove this.
11990 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11991 ReplaceInstUsesWith(IE, VecOp);
11992
11993 // If the inserted element was extracted from some other vector, and if the
11994 // indexes are constant, try to turn this into a shufflevector operation.
11995 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11996 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11997 EI->getOperand(0)->getType() == IE.getType()) {
11998 unsigned NumVectorElts = IE.getType()->getNumElements();
11999 unsigned ExtractedIdx =
12000 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12001 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12002
12003 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12004 return ReplaceInstUsesWith(IE, VecOp);
12005
12006 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12007 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12008
12009 // If we are extracting a value from a vector, then inserting it right
12010 // back into the same place, just use the input vector.
12011 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12012 return ReplaceInstUsesWith(IE, VecOp);
12013
12014 // We could theoretically do this for ANY input. However, doing so could
12015 // turn chains of insertelement instructions into a chain of shufflevector
12016 // instructions, and right now we do not merge shufflevectors. As such,
12017 // only do this in a situation where it is clear that there is benefit.
12018 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12019 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12020 // the values of VecOp, except then one read from EIOp0.
12021 // Build a new shuffle mask.
12022 std::vector<Constant*> Mask;
12023 if (isa<UndefValue>(VecOp))
12024 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12025 else {
12026 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12027 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12028 NumVectorElts));
12029 }
12030 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12031 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12032 ConstantVector::get(Mask));
12033 }
12034
12035 // If this insertelement isn't used by some other insertelement, turn it
12036 // (and any insertelements it points to), into one big shuffle.
12037 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12038 std::vector<Constant*> Mask;
12039 Value *RHS = 0;
12040 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12041 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12042 // We now have a shuffle of LHS, RHS, Mask.
12043 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12044 }
12045 }
12046 }
12047
12048 return 0;
12049}
12050
12051
12052Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12053 Value *LHS = SVI.getOperand(0);
12054 Value *RHS = SVI.getOperand(1);
12055 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12056
12057 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012058
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012059 // Undefined shuffle mask -> undefined value.
12060 if (isa<UndefValue>(SVI.getOperand(2)))
12061 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012062
12063 uint64_t UndefElts;
12064 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012065
12066 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12067 return 0;
12068
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012069 uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
12070 if (VWidth <= 64 &&
Dan Gohman83b702d2008-09-11 22:47:57 +000012071 SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12072 LHS = SVI.getOperand(0);
12073 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012074 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012075 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012076
12077 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12078 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12079 if (LHS == RHS || isa<UndefValue>(LHS)) {
12080 if (isa<UndefValue>(LHS) && LHS == RHS) {
12081 // shuffle(undef,undef,mask) -> undef.
12082 return ReplaceInstUsesWith(SVI, LHS);
12083 }
12084
12085 // Remap any references to RHS to use LHS.
12086 std::vector<Constant*> Elts;
12087 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12088 if (Mask[i] >= 2*e)
12089 Elts.push_back(UndefValue::get(Type::Int32Ty));
12090 else {
12091 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012092 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012093 Mask[i] = 2*e; // Turn into undef.
Dan Gohmanbba96b92008-08-06 18:17:32 +000012094 Elts.push_back(UndefValue::get(Type::Int32Ty));
12095 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012096 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohmanbba96b92008-08-06 18:17:32 +000012097 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12098 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012099 }
12100 }
12101 SVI.setOperand(0, SVI.getOperand(1));
12102 SVI.setOperand(1, UndefValue::get(RHS->getType()));
12103 SVI.setOperand(2, ConstantVector::get(Elts));
12104 LHS = SVI.getOperand(0);
12105 RHS = SVI.getOperand(1);
12106 MadeChange = true;
12107 }
12108
12109 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12110 bool isLHSID = true, isRHSID = true;
12111
12112 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12113 if (Mask[i] >= e*2) continue; // Ignore undef values.
12114 // Is this an identity shuffle of the LHS value?
12115 isLHSID &= (Mask[i] == i);
12116
12117 // Is this an identity shuffle of the RHS value?
12118 isRHSID &= (Mask[i]-e == i);
12119 }
12120
12121 // Eliminate identity shuffles.
12122 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12123 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12124
12125 // If the LHS is a shufflevector itself, see if we can combine it with this
12126 // one without producing an unusual shuffle. Here we are really conservative:
12127 // we are absolutely afraid of producing a shuffle mask not in the input
12128 // program, because the code gen may not be smart enough to turn a merged
12129 // shuffle into two specific shuffles: it may produce worse code. As such,
12130 // we only merge two shuffles if the result is one of the two input shuffle
12131 // masks. In this case, merging the shuffles just removes one instruction,
12132 // which we know is safe. This is good for things like turning:
12133 // (splat(splat)) -> splat.
12134 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12135 if (isa<UndefValue>(RHS)) {
12136 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12137
12138 std::vector<unsigned> NewMask;
12139 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12140 if (Mask[i] >= 2*e)
12141 NewMask.push_back(2*e);
12142 else
12143 NewMask.push_back(LHSMask[Mask[i]]);
12144
12145 // If the result mask is equal to the src shuffle or this shuffle mask, do
12146 // the replacement.
12147 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000012148 unsigned LHSInNElts =
12149 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012150 std::vector<Constant*> Elts;
12151 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000012152 if (NewMask[i] >= LHSInNElts*2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012153 Elts.push_back(UndefValue::get(Type::Int32Ty));
12154 } else {
12155 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12156 }
12157 }
12158 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12159 LHSSVI->getOperand(1),
12160 ConstantVector::get(Elts));
12161 }
12162 }
12163 }
12164
12165 return MadeChange ? &SVI : 0;
12166}
12167
12168
12169
12170
12171/// TryToSinkInstruction - Try to move the specified instruction from its
12172/// current block into the beginning of DestBlock, which can only happen if it's
12173/// safe to move the instruction past all of the instructions between it and the
12174/// end of its block.
12175static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12176 assert(I->hasOneUse() && "Invariants didn't hold!");
12177
12178 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012179 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12180 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012181
12182 // Do not sink alloca instructions out of the entry block.
12183 if (isa<AllocaInst>(I) && I->getParent() ==
12184 &DestBlock->getParent()->getEntryBlock())
12185 return false;
12186
12187 // We can only sink load instructions if there is nothing between the load and
12188 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012189 if (I->mayReadFromMemory()) {
12190 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012191 Scan != E; ++Scan)
12192 if (Scan->mayWriteToMemory())
12193 return false;
12194 }
12195
Dan Gohman514277c2008-05-23 21:05:58 +000012196 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012197
12198 I->moveBefore(InsertPos);
12199 ++NumSunkInst;
12200 return true;
12201}
12202
12203
12204/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12205/// all reachable code to the worklist.
12206///
12207/// This has a couple of tricks to make the code faster and more powerful. In
12208/// particular, we constant fold and DCE instructions as we go, to avoid adding
12209/// them to the worklist (this significantly speeds up instcombine on code where
12210/// many instructions are dead or constant). Additionally, if we find a branch
12211/// whose condition is a known constant, we only visit the reachable successors.
12212///
12213static void AddReachableCodeToWorklist(BasicBlock *BB,
12214 SmallPtrSet<BasicBlock*, 64> &Visited,
12215 InstCombiner &IC,
12216 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000012217 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012218 Worklist.push_back(BB);
12219
12220 while (!Worklist.empty()) {
12221 BB = Worklist.back();
12222 Worklist.pop_back();
12223
12224 // We have now visited this block! If we've already been here, ignore it.
12225 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012226
12227 DbgInfoIntrinsic *DBI_Prev = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012228 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12229 Instruction *Inst = BBI++;
12230
12231 // DCE instruction if trivially dead.
12232 if (isInstructionTriviallyDead(Inst)) {
12233 ++NumDeadInst;
12234 DOUT << "IC: DCE: " << *Inst;
12235 Inst->eraseFromParent();
12236 continue;
12237 }
12238
12239 // ConstantProp instruction if trivially constant.
12240 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12241 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12242 Inst->replaceAllUsesWith(C);
12243 ++NumConstProp;
12244 Inst->eraseFromParent();
12245 continue;
12246 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000012247
Devang Patel794140c2008-11-19 18:56:50 +000012248 // If there are two consecutive llvm.dbg.stoppoint calls then
12249 // it is likely that the optimizer deleted code in between these
12250 // two intrinsics.
12251 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12252 if (DBI_Next) {
12253 if (DBI_Prev
12254 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12255 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12256 IC.RemoveFromWorkList(DBI_Prev);
12257 DBI_Prev->eraseFromParent();
12258 }
12259 DBI_Prev = DBI_Next;
12260 }
12261
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012262 IC.AddToWorkList(Inst);
12263 }
12264
12265 // Recursively visit successors. If this is a branch or switch on a
12266 // constant, only visit the reachable successor.
12267 TerminatorInst *TI = BB->getTerminator();
12268 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12269 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12270 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012271 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012272 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012273 continue;
12274 }
12275 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12276 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12277 // See if this is an explicit destination.
12278 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12279 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012280 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012281 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012282 continue;
12283 }
12284
12285 // Otherwise it is the default destination.
12286 Worklist.push_back(SI->getSuccessor(0));
12287 continue;
12288 }
12289 }
12290
12291 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12292 Worklist.push_back(TI->getSuccessor(i));
12293 }
12294}
12295
12296bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12297 bool Changed = false;
12298 TD = &getAnalysis<TargetData>();
12299
12300 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12301 << F.getNameStr() << "\n");
12302
12303 {
12304 // Do a depth-first traversal of the function, populate the worklist with
12305 // the reachable instructions. Ignore blocks that are not reachable. Keep
12306 // track of which blocks we visit.
12307 SmallPtrSet<BasicBlock*, 64> Visited;
12308 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12309
12310 // Do a quick scan over the function. If we find any blocks that are
12311 // unreachable, remove any instructions inside of them. This prevents
12312 // the instcombine code from having to deal with some bad special cases.
12313 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12314 if (!Visited.count(BB)) {
12315 Instruction *Term = BB->getTerminator();
12316 while (Term != BB->begin()) { // Remove instrs bottom-up
12317 BasicBlock::iterator I = Term; --I;
12318
12319 DOUT << "IC: DCE: " << *I;
12320 ++NumDeadInst;
12321
12322 if (!I->use_empty())
12323 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12324 I->eraseFromParent();
Chris Lattnerf6d58862009-01-31 07:04:22 +000012325 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012326 }
12327 }
12328 }
12329
12330 while (!Worklist.empty()) {
12331 Instruction *I = RemoveOneFromWorkList();
12332 if (I == 0) continue; // skip null values.
12333
12334 // Check to see if we can DCE the instruction.
12335 if (isInstructionTriviallyDead(I)) {
12336 // Add operands to the worklist.
12337 if (I->getNumOperands() < 4)
12338 AddUsesToWorkList(*I);
12339 ++NumDeadInst;
12340
12341 DOUT << "IC: DCE: " << *I;
12342
12343 I->eraseFromParent();
12344 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000012345 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012346 continue;
12347 }
12348
12349 // Instruction isn't dead, see if we can constant propagate it.
12350 if (Constant *C = ConstantFoldInstruction(I, TD)) {
12351 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12352
12353 // Add operands to the worklist.
12354 AddUsesToWorkList(*I);
12355 ReplaceInstUsesWith(*I, C);
12356
12357 ++NumConstProp;
12358 I->eraseFromParent();
12359 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000012360 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012361 continue;
12362 }
12363
Nick Lewyckyadb67922008-05-25 20:56:15 +000012364 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12365 // See if we can constant fold its operands.
Chris Lattnerf6d58862009-01-31 07:04:22 +000012366 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12367 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewyckyadb67922008-05-25 20:56:15 +000012368 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattnerf6d58862009-01-31 07:04:22 +000012369 if (NewC != CE) {
12370 i->set(NewC);
12371 Changed = true;
12372 }
Nick Lewyckyadb67922008-05-25 20:56:15 +000012373 }
12374
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012375 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000012376 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012377 BasicBlock *BB = I->getParent();
12378 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12379 if (UserParent != BB) {
12380 bool UserIsSuccessor = false;
12381 // See if the user is one of our successors.
12382 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12383 if (*SI == UserParent) {
12384 UserIsSuccessor = true;
12385 break;
12386 }
12387
12388 // If the user is one of our immediate successors, and if that successor
12389 // only has us as a predecessors (we'd have to split the critical edge
12390 // otherwise), we can keep going.
12391 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12392 next(pred_begin(UserParent)) == pred_end(UserParent))
12393 // Okay, the CFG is simple enough, try to sink this instruction.
12394 Changed |= TryToSinkInstruction(I, UserParent);
12395 }
12396 }
12397
12398 // Now that we have an instruction, try combining it to simplify it...
12399#ifndef NDEBUG
12400 std::string OrigI;
12401#endif
12402 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12403 if (Instruction *Result = visit(*I)) {
12404 ++NumCombined;
12405 // Should we replace the old instruction with a new one?
12406 if (Result != I) {
12407 DOUT << "IC: Old = " << *I
12408 << " New = " << *Result;
12409
12410 // Everything uses the new instruction now.
12411 I->replaceAllUsesWith(Result);
12412
12413 // Push the new instruction and any users onto the worklist.
12414 AddToWorkList(Result);
12415 AddUsersToWorkList(*Result);
12416
12417 // Move the name to the new instruction first.
12418 Result->takeName(I);
12419
12420 // Insert the new instruction into the basic block...
12421 BasicBlock *InstParent = I->getParent();
12422 BasicBlock::iterator InsertPos = I;
12423
12424 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12425 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12426 ++InsertPos;
12427
12428 InstParent->getInstList().insert(InsertPos, Result);
12429
12430 // Make sure that we reprocess all operands now that we reduced their
12431 // use counts.
12432 AddUsesToWorkList(*I);
12433
12434 // Instructions can end up on the worklist more than once. Make sure
12435 // we do not process an instruction that has been deleted.
12436 RemoveFromWorkList(I);
12437
12438 // Erase the old instruction.
12439 InstParent->getInstList().erase(I);
12440 } else {
12441#ifndef NDEBUG
12442 DOUT << "IC: Mod = " << OrigI
12443 << " New = " << *I;
12444#endif
12445
12446 // If the instruction was modified, it's possible that it is now dead.
12447 // if so, remove it.
12448 if (isInstructionTriviallyDead(I)) {
12449 // Make sure we process all operands now that we are reducing their
12450 // use counts.
12451 AddUsesToWorkList(*I);
12452
12453 // Instructions may end up in the worklist more than once. Erase all
12454 // occurrences of this instruction.
12455 RemoveFromWorkList(I);
12456 I->eraseFromParent();
12457 } else {
12458 AddToWorkList(I);
12459 AddUsersToWorkList(*I);
12460 }
12461 }
12462 Changed = true;
12463 }
12464 }
12465
12466 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000012467
12468 // Do an explicit clear, this shrinks the map if needed.
12469 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012470 return Changed;
12471}
12472
12473
12474bool InstCombiner::runOnFunction(Function &F) {
12475 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12476
12477 bool EverMadeChange = false;
12478
12479 // Iterate while there is work to do.
12480 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000012481 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012482 EverMadeChange = true;
12483 return EverMadeChange;
12484}
12485
12486FunctionPass *llvm::createInstructionCombiningPass() {
12487 return new InstCombiner();
12488}