blob: 5bd17e0737b2ded5928f2b29e687875bd32e8ee4 [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);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000170 Instruction *visitFAdd(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000172 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000173 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000174 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175 Instruction *visitURem(BinaryOperator &I);
176 Instruction *visitSRem(BinaryOperator &I);
177 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000178 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 Instruction *commonRemTransforms(BinaryOperator &I);
180 Instruction *commonIRemTransforms(BinaryOperator &I);
181 Instruction *commonDivTransforms(BinaryOperator &I);
182 Instruction *commonIDivTransforms(BinaryOperator &I);
183 Instruction *visitUDiv(BinaryOperator &I);
184 Instruction *visitSDiv(BinaryOperator &I);
185 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000186 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000188 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000189 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000190 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 Instruction *visitOr (BinaryOperator &I);
192 Instruction *visitXor(BinaryOperator &I);
193 Instruction *visitShl(BinaryOperator &I);
194 Instruction *visitAShr(BinaryOperator &I);
195 Instruction *visitLShr(BinaryOperator &I);
196 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000197 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
198 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 Instruction *visitFCmpInst(FCmpInst &I);
200 Instruction *visitICmpInst(ICmpInst &I);
201 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
202 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
203 Instruction *LHS,
204 ConstantInt *RHS);
205 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
206 ConstantInt *DivRHS);
207
208 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
209 ICmpInst::Predicate Cond, Instruction &I);
210 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
211 BinaryOperator &I);
212 Instruction *commonCastTransforms(CastInst &CI);
213 Instruction *commonIntCastTransforms(CastInst &CI);
214 Instruction *commonPointerCastTransforms(CastInst &CI);
215 Instruction *visitTrunc(TruncInst &CI);
216 Instruction *visitZExt(ZExtInst &CI);
217 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000218 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000220 Instruction *visitFPToUI(FPToUIInst &FI);
221 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 Instruction *visitUIToFP(CastInst &CI);
223 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000224 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000225 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000226 Instruction *visitBitCast(BitCastInst &CI);
227 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
228 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000229 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman58c09632008-09-16 18:46:06 +0000230 Instruction *visitSelectInst(SelectInst &SI);
231 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 Instruction *visitCallInst(CallInst &CI);
233 Instruction *visitInvokeInst(InvokeInst &II);
234 Instruction *visitPHINode(PHINode &PN);
235 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
236 Instruction *visitAllocationInst(AllocationInst &AI);
237 Instruction *visitFreeInst(FreeInst &FI);
238 Instruction *visitLoadInst(LoadInst &LI);
239 Instruction *visitStoreInst(StoreInst &SI);
240 Instruction *visitBranchInst(BranchInst &BI);
241 Instruction *visitSwitchInst(SwitchInst &SI);
242 Instruction *visitInsertElementInst(InsertElementInst &IE);
243 Instruction *visitExtractElementInst(ExtractElementInst &EI);
244 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000245 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246
247 // visitInstruction - Specify what to return for unhandled instructions...
248 Instruction *visitInstruction(Instruction &I) { return 0; }
249
250 private:
251 Instruction *visitCallSite(CallSite CS);
252 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000253 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000254 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
255 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000256 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000257 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
258
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259
260 public:
261 // InsertNewInstBefore - insert an instruction New before instruction Old
262 // in the program. Add the new instruction to the worklist.
263 //
264 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
265 assert(New && New->getParent() == 0 &&
266 "New instruction already inserted into a basic block!");
267 BasicBlock *BB = Old.getParent();
268 BB->getInstList().insert(&Old, New); // Insert inst
269 AddToWorkList(New);
270 return New;
271 }
272
273 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
274 /// This also adds the cast to the worklist. Finally, this returns the
275 /// cast.
276 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
277 Instruction &Pos) {
278 if (V->getType() == Ty) return V;
279
280 if (Constant *CV = dyn_cast<Constant>(V))
281 return ConstantExpr::getCast(opc, CV, Ty);
282
Gabor Greifa645dd32008-05-16 19:29:10 +0000283 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284 AddToWorkList(C);
285 return C;
286 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000287
288 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
289 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
290 }
291
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292
293 // ReplaceInstUsesWith - This method is to be used when an instruction is
294 // found to be dead, replacable with another preexisting expression. Here
295 // we add all uses of I to the worklist, replace all uses of I with the new
296 // value, then return I, so that the inst combiner will know that I was
297 // modified.
298 //
299 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
300 AddUsersToWorkList(I); // Add all modified instrs to worklist
301 if (&I != V) {
302 I.replaceAllUsesWith(V);
303 return &I;
304 } else {
305 // If we are replacing the instruction with itself, this must be in a
306 // segment of unreachable code, so just clobber the instruction.
307 I.replaceAllUsesWith(UndefValue::get(I.getType()));
308 return &I;
309 }
310 }
311
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 // EraseInstFromFunction - When dealing with an instruction that has side
313 // effects or produces a void value, we can't rely on DCE to delete the
314 // instruction. Instead, visit methods should return the value returned by
315 // this function.
316 Instruction *EraseInstFromFunction(Instruction &I) {
317 assert(I.use_empty() && "Cannot erase instruction that is used!");
318 AddUsesToWorkList(I);
319 RemoveFromWorkList(&I);
320 I.eraseFromParent();
321 return 0; // Don't do anything with FI
322 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000323
324 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
325 APInt &KnownOne, unsigned Depth = 0) const {
326 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
327 }
328
329 bool MaskedValueIsZero(Value *V, const APInt &Mask,
330 unsigned Depth = 0) const {
331 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
332 }
333 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
334 return llvm::ComputeNumSignBits(Op, TD, Depth);
335 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336
337 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338
339 /// SimplifyCommutative - This performs a few simplifications for
340 /// commutative operators.
341 bool SimplifyCommutative(BinaryOperator &I);
342
343 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
344 /// most-complex to least-complex order.
345 bool SimplifyCompare(CmpInst &I);
346
Chris Lattner676c78e2009-01-31 08:15:18 +0000347 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
348 /// based on the demanded bits.
349 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
350 APInt& KnownZero, APInt& KnownOne,
351 unsigned Depth);
352 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000353 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000354 unsigned Depth=0);
355
356 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
357 /// SimplifyDemandedBits knows about. See if the instruction has any
358 /// properties that allow us to simplify its operands.
359 bool SimplifyDemandedInstructionBits(Instruction &Inst);
360
Evan Cheng63295ab2009-02-03 10:05:09 +0000361 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
362 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363
364 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
365 // PHI node as operand #0, see if we can fold the instruction into the PHI
366 // (which is only possible if all operands to the PHI are constants).
367 Instruction *FoldOpIntoPhi(Instruction &I);
368
369 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
370 // operator and they all are only used by the PHI, PHI together their
371 // inputs, and do the operation once, to the result of the PHI.
372 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
373 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000374 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
375
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000376
377 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
378 ConstantInt *AndRHS, BinaryOperator &TheAnd);
379
380 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
381 bool isSub, Instruction &I);
382 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
383 bool isSigned, bool Inside, Instruction &IB);
384 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
385 Instruction *MatchBSwap(BinaryOperator &I);
386 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000387 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000388 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000389
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390
391 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000392
Dan Gohman8fd520a2009-06-15 22:12:54 +0000393 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000394 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000395 unsigned GetOrEnforceKnownAlignment(Value *V,
396 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000397
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000398 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399}
400
Dan Gohman089efff2008-05-13 00:00:25 +0000401char InstCombiner::ID = 0;
402static RegisterPass<InstCombiner>
403X("instcombine", "Combine redundant instructions");
404
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405// getComplexity: Assign a complexity or rank value to LLVM Values...
406// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
407static unsigned getComplexity(Value *V) {
408 if (isa<Instruction>(V)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +0000409 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
410 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411 return 3;
412 return 4;
413 }
414 if (isa<Argument>(V)) return 3;
415 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
416}
417
418// isOnlyUse - Return true if this instruction will be deleted if we stop using
419// it.
420static bool isOnlyUse(Value *V) {
421 return V->hasOneUse() || isa<Constant>(V);
422}
423
424// getPromotedType - Return the specified type promoted as it would be to pass
425// though a va_arg area...
426static const Type *getPromotedType(const Type *Ty) {
427 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
428 if (ITy->getBitWidth() < 32)
429 return Type::Int32Ty;
430 }
431 return Ty;
432}
433
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000434/// getBitCastOperand - If the specified operand is a CastInst, a constant
435/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
436/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000437static Value *getBitCastOperand(Value *V) {
438 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000439 // BitCastInst?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000440 return I->getOperand(0);
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000441 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
442 // GetElementPtrInst?
443 if (GEP->hasAllZeroIndices())
444 return GEP->getOperand(0);
445 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000446 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000447 // BitCast ConstantExp?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448 return CE->getOperand(0);
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000449 else if (CE->getOpcode() == Instruction::GetElementPtr) {
450 // GetElementPtr ConstantExp?
451 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
452 I != E; ++I) {
453 ConstantInt *CI = dyn_cast<ConstantInt>(I);
454 if (!CI || !CI->isZero())
455 // Any non-zero indices? Not cast-like.
456 return 0;
457 }
458 // All-zero indices? This is just like casting.
459 return CE->getOperand(0);
460 }
461 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000462 return 0;
463}
464
465/// This function is a wrapper around CastInst::isEliminableCastPair. It
466/// simply extracts arguments and returns what that function returns.
467static Instruction::CastOps
468isEliminableCastPair(
469 const CastInst *CI, ///< The first cast instruction
470 unsigned opcode, ///< The opcode of the second cast instruction
471 const Type *DstTy, ///< The target type for the second cast instruction
472 TargetData *TD ///< The target data for pointer size
473) {
474
475 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
476 const Type *MidTy = CI->getType(); // B from above
477
478 // Get the opcodes of the two Cast instructions
479 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
480 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
481
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000482 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
483 DstTy, TD->getIntPtrType());
484
485 // We don't want to form an inttoptr or ptrtoint that converts to an integer
486 // type that differs from the pointer size.
487 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
488 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
489 Res = 0;
490
491 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000492}
493
494/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
495/// in any code being generated. It does not require codegen if V is simple
496/// enough or if the cast can be folded into other casts.
497static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
498 const Type *Ty, TargetData *TD) {
499 if (V->getType() == Ty || isa<Constant>(V)) return false;
500
501 // If this is another cast that can be eliminated, it isn't codegen either.
502 if (const CastInst *CI = dyn_cast<CastInst>(V))
503 if (isEliminableCastPair(CI, opcode, Ty, TD))
504 return false;
505 return true;
506}
507
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000508// SimplifyCommutative - This performs a few simplifications for commutative
509// operators:
510//
511// 1. Order operands such that they are listed from right (least complex) to
512// left (most complex). This puts constants before unary operators before
513// binary operators.
514//
515// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
516// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
517//
518bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
519 bool Changed = false;
520 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
521 Changed = !I.swapOperands();
522
523 if (!I.isAssociative()) return Changed;
524 Instruction::BinaryOps Opcode = I.getOpcode();
525 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
526 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
527 if (isa<Constant>(I.getOperand(1))) {
528 Constant *Folded = ConstantExpr::get(I.getOpcode(),
529 cast<Constant>(I.getOperand(1)),
530 cast<Constant>(Op->getOperand(1)));
531 I.setOperand(0, Op->getOperand(0));
532 I.setOperand(1, Folded);
533 return true;
534 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
535 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
536 isOnlyUse(Op) && isOnlyUse(Op1)) {
537 Constant *C1 = cast<Constant>(Op->getOperand(1));
538 Constant *C2 = cast<Constant>(Op1->getOperand(1));
539
540 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
541 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000542 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543 Op1->getOperand(0),
544 Op1->getName(), &I);
545 AddToWorkList(New);
546 I.setOperand(0, New);
547 I.setOperand(1, Folded);
548 return true;
549 }
550 }
551 return Changed;
552}
553
554/// SimplifyCompare - For a CmpInst this function just orders the operands
555/// so that theyare listed from right (least complex) to left (most complex).
556/// This puts constants before unary operators before binary operators.
557bool InstCombiner::SimplifyCompare(CmpInst &I) {
558 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
559 return false;
560 I.swapOperands();
561 // Compare instructions are not associative so there's nothing else we can do.
562 return true;
563}
564
565// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
566// if the LHS is a constant zero (which is the 'negate' form).
567//
568static inline Value *dyn_castNegVal(Value *V) {
569 if (BinaryOperator::isNeg(V))
570 return BinaryOperator::getNegArgument(V);
571
572 // Constants can be considered to be negated values if they can be folded.
573 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
574 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000575
576 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
577 if (C->getType()->getElementType()->isInteger())
578 return ConstantExpr::getNeg(C);
579
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000580 return 0;
581}
582
Dan Gohman7ce405e2009-06-04 22:49:04 +0000583// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
584// instruction if the LHS is a constant negative zero (which is the 'negate'
585// form).
586//
587static inline Value *dyn_castFNegVal(Value *V) {
588 if (BinaryOperator::isFNeg(V))
589 return BinaryOperator::getFNegArgument(V);
590
591 // Constants can be considered to be negated values if they can be folded.
592 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
593 return ConstantExpr::getFNeg(C);
594
595 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
596 if (C->getType()->getElementType()->isFloatingPoint())
597 return ConstantExpr::getFNeg(C);
598
599 return 0;
600}
601
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602static inline Value *dyn_castNotVal(Value *V) {
603 if (BinaryOperator::isNot(V))
604 return BinaryOperator::getNotArgument(V);
605
606 // Constants can be considered to be not'ed values...
607 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
608 return ConstantInt::get(~C->getValue());
609 return 0;
610}
611
612// dyn_castFoldableMul - If this value is a multiply that can be folded into
613// other computations (because it has a constant operand), return the
614// non-constant operand of the multiply, and set CST to point to the multiplier.
615// Otherwise, return null.
616//
617static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
618 if (V->hasOneUse() && V->getType()->isInteger())
619 if (Instruction *I = dyn_cast<Instruction>(V)) {
620 if (I->getOpcode() == Instruction::Mul)
621 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
622 return I->getOperand(0);
623 if (I->getOpcode() == Instruction::Shl)
624 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
625 // The multiplier is really 1 << CST.
626 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
627 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
628 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
629 return I->getOperand(0);
630 }
631 }
632 return 0;
633}
634
635/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
636/// expression, return it.
637static User *dyn_castGetElementPtr(Value *V) {
638 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
639 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
640 if (CE->getOpcode() == Instruction::GetElementPtr)
641 return cast<User>(V);
642 return false;
643}
644
Dan Gohman2d648bb2008-04-10 18:43:06 +0000645/// getOpcode - If this is an Instruction or a ConstantExpr, return the
646/// opcode value. Otherwise return UserOp1.
Dan Gohman8c397862008-05-29 19:53:46 +0000647static unsigned getOpcode(const Value *V) {
648 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000649 return I->getOpcode();
Dan Gohman8c397862008-05-29 19:53:46 +0000650 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000651 return CE->getOpcode();
652 // Use UserOp1 to mean there's no opcode.
653 return Instruction::UserOp1;
654}
655
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656/// AddOne - Add one to a ConstantInt
Dan Gohman8fd520a2009-06-15 22:12:54 +0000657static Constant *AddOne(Constant *C) {
658 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000659}
660/// SubOne - Subtract one from a ConstantInt
Dan Gohman8fd520a2009-06-15 22:12:54 +0000661static Constant *SubOne(ConstantInt *C) {
662 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000664/// MultiplyOverflows - True if the multiply can not be expressed in an int
665/// this size.
666static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
667 uint32_t W = C1->getBitWidth();
668 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
669 if (sign) {
670 LHSExt.sext(W * 2);
671 RHSExt.sext(W * 2);
672 } else {
673 LHSExt.zext(W * 2);
674 RHSExt.zext(W * 2);
675 }
676
677 APInt MulExt = LHSExt * RHSExt;
678
679 if (sign) {
680 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
681 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
682 return MulExt.slt(Min) || MulExt.sgt(Max);
683 } else
684 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
685}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687
688/// ShrinkDemandedConstant - Check to see if the specified operand of the
689/// specified instruction is a constant integer. If so, check to see if there
690/// are any bits set in the constant that are not demanded. If so, shrink the
691/// constant and return true.
692static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
693 APInt Demanded) {
694 assert(I && "No instruction?");
695 assert(OpNo < I->getNumOperands() && "Operand index too large");
696
697 // If the operand is not a constant integer, nothing to do.
698 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
699 if (!OpC) return false;
700
701 // If there are no bits set that aren't demanded, nothing to do.
702 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
703 if ((~Demanded & OpC->getValue()) == 0)
704 return false;
705
706 // This instruction is producing bits that are not demanded. Shrink the RHS.
707 Demanded &= OpC->getValue();
708 I->setOperand(OpNo, ConstantInt::get(Demanded));
709 return true;
710}
711
712// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
713// set of known zero and one bits, compute the maximum and minimum values that
714// could have the specified known zero and known one bits, returning them in
715// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000716static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717 const APInt& KnownOne,
718 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000719 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
720 KnownZero.getBitWidth() == Min.getBitWidth() &&
721 KnownZero.getBitWidth() == Max.getBitWidth() &&
722 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723 APInt UnknownBits = ~(KnownZero|KnownOne);
724
725 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
726 // bit if it is unknown.
727 Min = KnownOne;
728 Max = KnownOne|UnknownBits;
729
Dan Gohman7934d592009-04-25 17:12:48 +0000730 if (UnknownBits.isNegative()) { // Sign bit is unknown
731 Min.set(Min.getBitWidth()-1);
732 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 }
734}
735
736// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
737// a set of known zero and one bits, compute the maximum and minimum values that
738// could have the specified known zero and known one bits, returning them in
739// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000740static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000741 const APInt &KnownOne,
742 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000743 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
744 KnownZero.getBitWidth() == Min.getBitWidth() &&
745 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
747 APInt UnknownBits = ~(KnownZero|KnownOne);
748
749 // The minimum value is when the unknown bits are all zeros.
750 Min = KnownOne;
751 // The maximum value is when the unknown bits are all ones.
752 Max = KnownOne|UnknownBits;
753}
754
Chris Lattner676c78e2009-01-31 08:15:18 +0000755/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
756/// SimplifyDemandedBits knows about. See if the instruction has any
757/// properties that allow us to simplify its operands.
758bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000759 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000760 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
761 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
762
763 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
764 KnownZero, KnownOne, 0);
765 if (V == 0) return false;
766 if (V == &Inst) return true;
767 ReplaceInstUsesWith(Inst, V);
768 return true;
769}
770
771/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
772/// specified instruction operand if possible, updating it in place. It returns
773/// true if it made any change and false otherwise.
774bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
775 APInt &KnownZero, APInt &KnownOne,
776 unsigned Depth) {
777 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
778 KnownZero, KnownOne, Depth);
779 if (NewVal == 0) return false;
780 U.set(NewVal);
781 return true;
782}
783
784
785/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
786/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787/// that only the bits set in DemandedMask of the result of V are ever used
788/// downstream. Consequently, depending on the mask and V, it may be possible
789/// to replace V with a constant or one of its operands. In such cases, this
790/// function does the replacement and returns true. In all other cases, it
791/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000792/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000793/// to be zero in the expression. These are provided to potentially allow the
794/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
795/// the expression. KnownOne and KnownZero always follow the invariant that
796/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
797/// the bits in KnownOne and KnownZero may only be accurate for those bits set
798/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
799/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000800///
801/// This returns null if it did not change anything and it permits no
802/// simplification. This returns V itself if it did some simplification of V's
803/// operands based on the information about what bits are demanded. This returns
804/// some other non-null value if it found out that V is equal to another value
805/// in the context where the specified bits are demanded, but not for all users.
806Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
807 APInt &KnownZero, APInt &KnownOne,
808 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809 assert(V != 0 && "Null pointer of Value???");
810 assert(Depth <= 6 && "Limit Search Depth");
811 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000812 const Type *VTy = V->getType();
813 assert((TD || !isa<PointerType>(VTy)) &&
814 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000815 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
816 (!VTy->isIntOrIntVector() ||
817 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000818 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000820 "Value *V, DemandedMask, KnownZero and KnownOne "
821 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000822 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
823 // We know all of the bits for a constant!
824 KnownOne = CI->getValue() & DemandedMask;
825 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000826 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000827 }
Dan Gohman7934d592009-04-25 17:12:48 +0000828 if (isa<ConstantPointerNull>(V)) {
829 // We know all of the bits for a constant!
830 KnownOne.clear();
831 KnownZero = DemandedMask;
832 return 0;
833 }
834
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000835 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000837 if (DemandedMask == 0) { // Not demanding any bits from V.
838 if (isa<UndefValue>(V))
839 return 0;
840 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841 }
842
Chris Lattner08817332009-01-31 08:24:16 +0000843 if (Depth == 6) // Limit search depth.
844 return 0;
845
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000846 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
847 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
848
Dan Gohman7934d592009-04-25 17:12:48 +0000849 Instruction *I = dyn_cast<Instruction>(V);
850 if (!I) {
851 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
852 return 0; // Only analyze instructions.
853 }
854
Chris Lattner08817332009-01-31 08:24:16 +0000855 // If there are multiple uses of this value and we aren't at the root, then
856 // we can't do any simplifications of the operands, because DemandedMask
857 // only reflects the bits demanded by *one* of the users.
858 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000859 // Despite the fact that we can't simplify this instruction in all User's
860 // context, we can at least compute the knownzero/knownone bits, and we can
861 // do simplifications that apply to *just* the one user if we know that
862 // this instruction has a simpler value in that context.
863 if (I->getOpcode() == Instruction::And) {
864 // If either the LHS or the RHS are Zero, the result is zero.
865 ComputeMaskedBits(I->getOperand(1), DemandedMask,
866 RHSKnownZero, RHSKnownOne, Depth+1);
867 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
868 LHSKnownZero, LHSKnownOne, Depth+1);
869
870 // If all of the demanded bits are known 1 on one side, return the other.
871 // These bits cannot contribute to the result of the 'and' in this
872 // context.
873 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
874 (DemandedMask & ~LHSKnownZero))
875 return I->getOperand(0);
876 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
877 (DemandedMask & ~RHSKnownZero))
878 return I->getOperand(1);
879
880 // If all of the demanded bits in the inputs are known zeros, return zero.
881 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
882 return Constant::getNullValue(VTy);
883
884 } else if (I->getOpcode() == Instruction::Or) {
885 // We can simplify (X|Y) -> X or Y in the user's context if we know that
886 // only bits from X or Y are demanded.
887
888 // If either the LHS or the RHS are One, the result is One.
889 ComputeMaskedBits(I->getOperand(1), DemandedMask,
890 RHSKnownZero, RHSKnownOne, Depth+1);
891 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
892 LHSKnownZero, LHSKnownOne, Depth+1);
893
894 // If all of the demanded bits are known zero on one side, return the
895 // other. These bits cannot contribute to the result of the 'or' in this
896 // context.
897 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
898 (DemandedMask & ~LHSKnownOne))
899 return I->getOperand(0);
900 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
901 (DemandedMask & ~RHSKnownOne))
902 return I->getOperand(1);
903
904 // If all of the potentially set bits on one side are known to be set on
905 // the other side, just use the 'other' side.
906 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
907 (DemandedMask & (~RHSKnownZero)))
908 return I->getOperand(0);
909 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
910 (DemandedMask & (~LHSKnownZero)))
911 return I->getOperand(1);
912 }
913
Chris Lattner08817332009-01-31 08:24:16 +0000914 // Compute the KnownZero/KnownOne bits to simplify things downstream.
915 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
916 return 0;
917 }
918
919 // If this is the root being simplified, allow it to have multiple uses,
920 // just set the DemandedMask to all bits so that we can try to simplify the
921 // operands. This allows visitTruncInst (for example) to simplify the
922 // operand of a trunc without duplicating all the logic below.
923 if (Depth == 0 && !V->hasOneUse())
924 DemandedMask = APInt::getAllOnesValue(BitWidth);
925
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000926 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000927 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000928 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000929 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000930 case Instruction::And:
931 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000932 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
933 RHSKnownZero, RHSKnownOne, Depth+1) ||
934 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000935 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000936 return I;
937 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
938 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939
940 // If all of the demanded bits are known 1 on one side, return the other.
941 // These bits cannot contribute to the result of the 'and'.
942 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
943 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000944 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
946 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000947 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948
949 // If all of the demanded bits in the inputs are known zeros, return zero.
950 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000951 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000952
953 // If the RHS is a constant, see if we can simplify it.
954 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000955 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956
957 // Output known-1 bits are only known if set in both the LHS & RHS.
958 RHSKnownOne &= LHSKnownOne;
959 // Output known-0 are known to be clear if zero in either the LHS | RHS.
960 RHSKnownZero |= LHSKnownZero;
961 break;
962 case Instruction::Or:
963 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +0000964 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
965 RHSKnownZero, RHSKnownOne, Depth+1) ||
966 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000967 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000968 return I;
969 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
970 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000971
972 // If all of the demanded bits are known zero on one side, return the other.
973 // These bits cannot contribute to the result of the 'or'.
974 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
975 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000976 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000977 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
978 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000979 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000980
981 // If all of the potentially set bits on one side are known to be set on
982 // the other side, just use the 'other' side.
983 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
984 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000985 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
987 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000988 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989
990 // If the RHS is a constant, see if we can simplify it.
991 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +0000992 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993
994 // Output known-0 bits are only known if clear in both the LHS & RHS.
995 RHSKnownZero &= LHSKnownZero;
996 // Output known-1 are known to be set if set in either the LHS | RHS.
997 RHSKnownOne |= LHSKnownOne;
998 break;
999 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +00001000 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1001 RHSKnownZero, RHSKnownOne, Depth+1) ||
1002 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001003 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001004 return I;
1005 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1006 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001007
1008 // If all of the demanded bits are known zero on one side, return the other.
1009 // These bits cannot contribute to the result of the 'xor'.
1010 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001011 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001013 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014
1015 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1016 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1017 (RHSKnownOne & LHSKnownOne);
1018 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1019 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1020 (RHSKnownOne & LHSKnownZero);
1021
1022 // If all of the demanded bits are known to be zero on one side or the
1023 // other, turn this into an *inclusive* or.
1024 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1025 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1026 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001027 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001029 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001030 }
1031
1032 // If all of the demanded bits on one side are known, and all of the set
1033 // bits on that side are also known to be set on the other side, turn this
1034 // into an AND, as we know the bits will be cleared.
1035 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1036 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1037 // all known
1038 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1039 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1040 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001041 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001042 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 }
1044 }
1045
1046 // If the RHS is a constant, see if we can simplify it.
1047 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1048 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001049 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050
1051 RHSKnownZero = KnownZeroOut;
1052 RHSKnownOne = KnownOneOut;
1053 break;
1054 }
1055 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001056 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1057 RHSKnownZero, RHSKnownOne, Depth+1) ||
1058 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001060 return I;
1061 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1062 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001063
1064 // If the operands are constants, see if we can simplify them.
Chris Lattner676c78e2009-01-31 08:15:18 +00001065 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1066 ShrinkDemandedConstant(I, 2, DemandedMask))
1067 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001068
1069 // Only known if known in both the LHS and RHS.
1070 RHSKnownOne &= LHSKnownOne;
1071 RHSKnownZero &= LHSKnownZero;
1072 break;
1073 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001074 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001075 DemandedMask.zext(truncBf);
1076 RHSKnownZero.zext(truncBf);
1077 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001078 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001080 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001081 DemandedMask.trunc(BitWidth);
1082 RHSKnownZero.trunc(BitWidth);
1083 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001084 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001085 break;
1086 }
1087 case Instruction::BitCast:
1088 if (!I->getOperand(0)->getType()->isInteger())
Chris Lattner676c78e2009-01-31 08:15:18 +00001089 return false; // vector->int or fp->int?
1090 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001091 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001092 return I;
1093 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094 break;
1095 case Instruction::ZExt: {
1096 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001097 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098
1099 DemandedMask.trunc(SrcBitWidth);
1100 RHSKnownZero.trunc(SrcBitWidth);
1101 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001102 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001104 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 DemandedMask.zext(BitWidth);
1106 RHSKnownZero.zext(BitWidth);
1107 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001108 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001109 // The top bits are known to be zero.
1110 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1111 break;
1112 }
1113 case Instruction::SExt: {
1114 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001115 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116
1117 APInt InputDemandedBits = DemandedMask &
1118 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1119
1120 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1121 // If any of the sign extended bits are demanded, we know that the sign
1122 // bit is demanded.
1123 if ((NewBits & DemandedMask) != 0)
1124 InputDemandedBits.set(SrcBitWidth-1);
1125
1126 InputDemandedBits.trunc(SrcBitWidth);
1127 RHSKnownZero.trunc(SrcBitWidth);
1128 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001129 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001131 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132 InputDemandedBits.zext(BitWidth);
1133 RHSKnownZero.zext(BitWidth);
1134 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001135 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001136
1137 // If the sign bit of the input is known set or clear, then we know the
1138 // top bits of the result.
1139
1140 // If the input sign bit is known zero, or if the NewBits are not demanded
1141 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001142 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001144 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1145 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1147 RHSKnownOne |= NewBits;
1148 }
1149 break;
1150 }
1151 case Instruction::Add: {
1152 // Figure out what the input bits are. If the top bits of the and result
1153 // are not demanded, then the add doesn't demand them from its input
1154 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001155 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001156
1157 // If there is a constant on the RHS, there are a variety of xformations
1158 // we can do.
1159 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1160 // If null, this should be simplified elsewhere. Some of the xforms here
1161 // won't work if the RHS is zero.
1162 if (RHS->isZero())
1163 break;
1164
1165 // If the top bit of the output is demanded, demand everything from the
1166 // input. Otherwise, we demand all the input bits except NLZ top bits.
1167 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1168
1169 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001170 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001172 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001173
1174 // If the RHS of the add has bits set that can't affect the input, reduce
1175 // the constant.
1176 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001177 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001178
1179 // Avoid excess work.
1180 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1181 break;
1182
1183 // Turn it into OR if input bits are zero.
1184 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1185 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001186 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001187 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001188 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001189 }
1190
1191 // We can say something about the output known-zero and known-one bits,
1192 // depending on potential carries from the input constant and the
1193 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1194 // bits set and the RHS constant is 0x01001, then we know we have a known
1195 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1196
1197 // To compute this, we first compute the potential carry bits. These are
1198 // the bits which may be modified. I'm not aware of a better way to do
1199 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001200 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1202
1203 // Now that we know which bits have carries, compute the known-1/0 sets.
1204
1205 // Bits are known one if they are known zero in one operand and one in the
1206 // other, and there is no input carry.
1207 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1208 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1209
1210 // Bits are known zero if they are known zero in both operands and there
1211 // is no input carry.
1212 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1213 } else {
1214 // If the high-bits of this ADD are not demanded, then it does not demand
1215 // the high bits of its LHS or RHS.
1216 if (DemandedMask[BitWidth-1] == 0) {
1217 // Right fill the mask of bits for this ADD to demand the most
1218 // significant bit and all those below it.
1219 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001220 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1221 LHSKnownZero, LHSKnownOne, Depth+1) ||
1222 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001223 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001224 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001225 }
1226 }
1227 break;
1228 }
1229 case Instruction::Sub:
1230 // If the high-bits of this SUB are not demanded, then it does not demand
1231 // the high bits of its LHS or RHS.
1232 if (DemandedMask[BitWidth-1] == 0) {
1233 // Right fill the mask of bits for this SUB to demand the most
1234 // significant bit and all those below it.
1235 uint32_t NLZ = DemandedMask.countLeadingZeros();
1236 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001237 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1238 LHSKnownZero, LHSKnownOne, Depth+1) ||
1239 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001241 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001243 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1244 // the known zeros and ones.
1245 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001246 break;
1247 case Instruction::Shl:
1248 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1249 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1250 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001251 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001252 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001253 return I;
1254 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001255 RHSKnownZero <<= ShiftAmt;
1256 RHSKnownOne <<= ShiftAmt;
1257 // low bits known zero.
1258 if (ShiftAmt)
1259 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1260 }
1261 break;
1262 case Instruction::LShr:
1263 // For a logical shift right
1264 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1265 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1266
1267 // Unsigned shift right.
1268 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001269 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001271 return I;
1272 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1274 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1275 if (ShiftAmt) {
1276 // Compute the new bits that are at the top now.
1277 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1278 RHSKnownZero |= HighBits; // high bits known zero.
1279 }
1280 }
1281 break;
1282 case Instruction::AShr:
1283 // If this is an arithmetic shift right and only the low-bit is set, we can
1284 // always convert this into a logical shr, even if the shift amount is
1285 // variable. The low bit of the shift cannot be an input sign bit unless
1286 // the shift amount is >= the size of the datatype, which is undefined.
1287 if (DemandedMask == 1) {
1288 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001289 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001290 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001291 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 }
1293
1294 // If the sign bit is the only bit demanded by this ashr, then there is no
1295 // need to do it, the shift doesn't change the high bit.
1296 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001297 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001298
1299 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1300 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1301
1302 // Signed shift right.
1303 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1304 // If any of the "high bits" are demanded, we should set the sign bit as
1305 // demanded.
1306 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1307 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001308 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001309 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001310 return I;
1311 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001312 // Compute the new bits that are at the top now.
1313 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1314 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1315 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1316
1317 // Handle the sign bits.
1318 APInt SignBit(APInt::getSignBit(BitWidth));
1319 // Adjust to where it is now in the mask.
1320 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1321
1322 // If the input sign bit is known to be zero, or if none of the top bits
1323 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001324 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325 (HighBits & ~DemandedMask) == HighBits) {
1326 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001327 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001329 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1331 RHSKnownOne |= HighBits;
1332 }
1333 }
1334 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001335 case Instruction::SRem:
1336 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001337 APInt RA = Rem->getValue().abs();
1338 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001339 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001340 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001341
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001342 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001343 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001344 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001345 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001346 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001347
1348 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1349 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001350
1351 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001352
Chris Lattner676c78e2009-01-31 08:15:18 +00001353 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001354 }
1355 }
1356 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001357 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001358 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1359 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001360 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1361 KnownZero2, KnownOne2, Depth+1) ||
1362 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001363 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001364 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001365
Chris Lattneree5417c2009-01-21 18:09:24 +00001366 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001367 Leaders = std::max(Leaders,
1368 KnownZero2.countLeadingOnes());
1369 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001370 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371 }
Chris Lattner989ba312008-06-18 04:33:20 +00001372 case Instruction::Call:
1373 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1374 switch (II->getIntrinsicID()) {
1375 default: break;
1376 case Intrinsic::bswap: {
1377 // If the only bits demanded come from one byte of the bswap result,
1378 // just shift the input byte into position to eliminate the bswap.
1379 unsigned NLZ = DemandedMask.countLeadingZeros();
1380 unsigned NTZ = DemandedMask.countTrailingZeros();
1381
1382 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1383 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1384 // have 14 leading zeros, round to 8.
1385 NLZ &= ~7;
1386 NTZ &= ~7;
1387 // If we need exactly one byte, we can do this transformation.
1388 if (BitWidth-NLZ-NTZ == 8) {
1389 unsigned ResultBit = NTZ;
1390 unsigned InputBit = BitWidth-NTZ-8;
1391
1392 // Replace this with either a left or right shift to get the byte into
1393 // the right place.
1394 Instruction *NewVal;
1395 if (InputBit > ResultBit)
1396 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1397 ConstantInt::get(I->getType(), InputBit-ResultBit));
1398 else
1399 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1400 ConstantInt::get(I->getType(), ResultBit-InputBit));
1401 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001402 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001403 }
1404
1405 // TODO: Could compute known zero/one bits based on the input.
1406 break;
1407 }
1408 }
1409 }
Chris Lattner4946e222008-06-18 18:11:55 +00001410 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001411 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001412 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001413
1414 // If the client is only demanding bits that we know, return the known
1415 // constant.
Dan Gohman7934d592009-04-25 17:12:48 +00001416 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1417 Constant *C = ConstantInt::get(RHSKnownOne);
1418 if (isa<PointerType>(V->getType()))
1419 C = ConstantExpr::getIntToPtr(C, V->getType());
1420 return C;
1421 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001422 return false;
1423}
1424
1425
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001426/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001427/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001428/// actually used by the caller. This method analyzes which elements of the
1429/// operand are undef and returns that information in UndefElts.
1430///
1431/// If the information about demanded elements can be used to simplify the
1432/// operation, the operation is simplified, then the resultant value is
1433/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001434Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1435 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001436 unsigned Depth) {
1437 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001438 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001439 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001440
1441 if (isa<UndefValue>(V)) {
1442 // If the entire vector is undefined, just return this info.
1443 UndefElts = EltMask;
1444 return 0;
1445 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1446 UndefElts = EltMask;
1447 return UndefValue::get(V->getType());
1448 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001449
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001450 UndefElts = 0;
1451 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1452 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1453 Constant *Undef = UndefValue::get(EltTy);
1454
1455 std::vector<Constant*> Elts;
1456 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001457 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001458 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001459 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001460 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1461 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001462 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001463 } else { // Otherwise, defined.
1464 Elts.push_back(CP->getOperand(i));
1465 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001466
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001467 // If we changed the constant, return it.
1468 Constant *NewCP = ConstantVector::get(Elts);
1469 return NewCP != CP ? NewCP : 0;
1470 } else if (isa<ConstantAggregateZero>(V)) {
1471 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1472 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001473
1474 // Check if this is identity. If so, return 0 since we are not simplifying
1475 // anything.
1476 if (DemandedElts == ((1ULL << VWidth) -1))
1477 return 0;
1478
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001479 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1480 Constant *Zero = Constant::getNullValue(EltTy);
1481 Constant *Undef = UndefValue::get(EltTy);
1482 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001483 for (unsigned i = 0; i != VWidth; ++i) {
1484 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1485 Elts.push_back(Elt);
1486 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001487 UndefElts = DemandedElts ^ EltMask;
1488 return ConstantVector::get(Elts);
1489 }
1490
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001491 // Limit search depth.
1492 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001493 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001494
1495 // If multiple users are using the root value, procede with
1496 // simplification conservatively assuming that all elements
1497 // are needed.
1498 if (!V->hasOneUse()) {
1499 // Quit if we find multiple users of a non-root value though.
1500 // They'll be handled when it's their turn to be visited by
1501 // the main instcombine process.
1502 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001503 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001504 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001505
1506 // Conservatively assume that all elements are needed.
1507 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001508 }
1509
1510 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001511 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001512
1513 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001514 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001515 Value *TmpV;
1516 switch (I->getOpcode()) {
1517 default: break;
1518
1519 case Instruction::InsertElement: {
1520 // If this is a variable index, we don't know which element it overwrites.
1521 // demand exactly the same input as we produce.
1522 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1523 if (Idx == 0) {
1524 // Note that we can't propagate undef elt info, because we don't know
1525 // which elt is getting updated.
1526 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1527 UndefElts2, Depth+1);
1528 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1529 break;
1530 }
1531
1532 // If this is inserting an element that isn't demanded, remove this
1533 // insertelement.
1534 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng63295ab2009-02-03 10:05:09 +00001535 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001536 return AddSoonDeadInstToWorklist(*I, 0);
1537
1538 // Otherwise, the element inserted overwrites whatever was there, so the
1539 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001540 APInt DemandedElts2 = DemandedElts;
1541 DemandedElts2.clear(IdxNo);
1542 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001543 UndefElts, Depth+1);
1544 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1545
1546 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001547 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001548 break;
1549 }
1550 case Instruction::ShuffleVector: {
1551 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001552 uint64_t LHSVWidth =
1553 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001554 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001555 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001556 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001557 unsigned MaskVal = Shuffle->getMaskValue(i);
1558 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001559 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001560 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001561 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001562 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001563 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001564 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001565 }
1566 }
1567 }
1568
Nate Begemanb4d176f2009-02-11 22:36:25 +00001569 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001570 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001571 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001572 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1573
Nate Begemanb4d176f2009-02-11 22:36:25 +00001574 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001575 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1576 UndefElts3, Depth+1);
1577 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1578
1579 bool NewUndefElts = false;
1580 for (unsigned i = 0; i < VWidth; i++) {
1581 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001582 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001583 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001584 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001585 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001586 NewUndefElts = true;
1587 UndefElts.set(i);
1588 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001589 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001590 if (UndefElts3[MaskVal - LHSVWidth]) {
1591 NewUndefElts = true;
1592 UndefElts.set(i);
1593 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001594 }
1595 }
1596
1597 if (NewUndefElts) {
1598 // Add additional discovered undefs.
1599 std::vector<Constant*> Elts;
1600 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001601 if (UndefElts[i])
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001602 Elts.push_back(UndefValue::get(Type::Int32Ty));
1603 else
1604 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1605 Shuffle->getMaskValue(i)));
1606 }
1607 I->setOperand(2, ConstantVector::get(Elts));
1608 MadeChange = true;
1609 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001610 break;
1611 }
1612 case Instruction::BitCast: {
1613 // Vector->vector casts only.
1614 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1615 if (!VTy) break;
1616 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001617 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001618 unsigned Ratio;
1619
1620 if (VWidth == InVWidth) {
1621 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1622 // elements as are demanded of us.
1623 Ratio = 1;
1624 InputDemandedElts = DemandedElts;
1625 } else if (VWidth > InVWidth) {
1626 // Untested so far.
1627 break;
1628
1629 // If there are more elements in the result than there are in the source,
1630 // then an input element is live if any of the corresponding output
1631 // elements are live.
1632 Ratio = VWidth/InVWidth;
1633 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001634 if (DemandedElts[OutIdx])
1635 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001636 }
1637 } else {
1638 // Untested so far.
1639 break;
1640
1641 // If there are more elements in the source than there are in the result,
1642 // then an input element is live if the corresponding output element is
1643 // live.
1644 Ratio = InVWidth/VWidth;
1645 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001646 if (DemandedElts[InIdx/Ratio])
1647 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001648 }
1649
1650 // div/rem demand all inputs, because they don't want divide by zero.
1651 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1652 UndefElts2, Depth+1);
1653 if (TmpV) {
1654 I->setOperand(0, TmpV);
1655 MadeChange = true;
1656 }
1657
1658 UndefElts = UndefElts2;
1659 if (VWidth > InVWidth) {
1660 assert(0 && "Unimp");
1661 // If there are more elements in the result than there are in the source,
1662 // then an output element is undef if the corresponding input element is
1663 // undef.
1664 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001665 if (UndefElts2[OutIdx/Ratio])
1666 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001667 } else if (VWidth < InVWidth) {
1668 assert(0 && "Unimp");
1669 // If there are more elements in the source than there are in the result,
1670 // then a result element is undef if all of the corresponding input
1671 // elements are undef.
1672 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1673 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001674 if (!UndefElts2[InIdx]) // Not undef?
1675 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001676 }
1677 break;
1678 }
1679 case Instruction::And:
1680 case Instruction::Or:
1681 case Instruction::Xor:
1682 case Instruction::Add:
1683 case Instruction::Sub:
1684 case Instruction::Mul:
1685 // div/rem demand all inputs, because they don't want divide by zero.
1686 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1687 UndefElts, Depth+1);
1688 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1689 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1690 UndefElts2, Depth+1);
1691 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1692
1693 // Output elements are undefined if both are undefined. Consider things
1694 // like undef&0. The result is known zero, not undef.
1695 UndefElts &= UndefElts2;
1696 break;
1697
1698 case Instruction::Call: {
1699 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1700 if (!II) break;
1701 switch (II->getIntrinsicID()) {
1702 default: break;
1703
1704 // Binary vector operations that work column-wise. A dest element is a
1705 // function of the corresponding input elements from the two inputs.
1706 case Intrinsic::x86_sse_sub_ss:
1707 case Intrinsic::x86_sse_mul_ss:
1708 case Intrinsic::x86_sse_min_ss:
1709 case Intrinsic::x86_sse_max_ss:
1710 case Intrinsic::x86_sse2_sub_sd:
1711 case Intrinsic::x86_sse2_mul_sd:
1712 case Intrinsic::x86_sse2_min_sd:
1713 case Intrinsic::x86_sse2_max_sd:
1714 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1715 UndefElts, Depth+1);
1716 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1717 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1718 UndefElts2, Depth+1);
1719 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1720
1721 // If only the low elt is demanded and this is a scalarizable intrinsic,
1722 // scalarize it now.
1723 if (DemandedElts == 1) {
1724 switch (II->getIntrinsicID()) {
1725 default: break;
1726 case Intrinsic::x86_sse_sub_ss:
1727 case Intrinsic::x86_sse_mul_ss:
1728 case Intrinsic::x86_sse2_sub_sd:
1729 case Intrinsic::x86_sse2_mul_sd:
1730 // TODO: Lower MIN/MAX/ABS/etc
1731 Value *LHS = II->getOperand(1);
1732 Value *RHS = II->getOperand(2);
1733 // Extract the element as scalars.
1734 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1735 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1736
1737 switch (II->getIntrinsicID()) {
1738 default: assert(0 && "Case stmts out of sync!");
1739 case Intrinsic::x86_sse_sub_ss:
1740 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001741 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001742 II->getName()), *II);
1743 break;
1744 case Intrinsic::x86_sse_mul_ss:
1745 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001746 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001747 II->getName()), *II);
1748 break;
1749 }
1750
1751 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00001752 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1753 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001754 InsertNewInstBefore(New, *II);
1755 AddSoonDeadInstToWorklist(*II, 0);
1756 return New;
1757 }
1758 }
1759
1760 // Output elements are undefined if both are undefined. Consider things
1761 // like undef&0. The result is known zero, not undef.
1762 UndefElts &= UndefElts2;
1763 break;
1764 }
1765 break;
1766 }
1767 }
1768 return MadeChange ? I : 0;
1769}
1770
Dan Gohman5d56fd42008-05-19 22:14:15 +00001771
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001772/// AssociativeOpt - Perform an optimization on an associative operator. This
1773/// function is designed to check a chain of associative operators for a
1774/// potential to apply a certain optimization. Since the optimization may be
1775/// applicable if the expression was reassociated, this checks the chain, then
1776/// reassociates the expression as necessary to expose the optimization
1777/// opportunity. This makes use of a special Functor, which must define
1778/// 'shouldApply' and 'apply' methods.
1779///
1780template<typename Functor>
Dan Gohmand8bcf5b2008-05-20 01:14:05 +00001781static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001782 unsigned Opcode = Root.getOpcode();
1783 Value *LHS = Root.getOperand(0);
1784
1785 // Quick check, see if the immediate LHS matches...
1786 if (F.shouldApply(LHS))
1787 return F.apply(Root);
1788
1789 // Otherwise, if the LHS is not of the same opcode as the root, return.
1790 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1791 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1792 // Should we apply this transform to the RHS?
1793 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1794
1795 // If not to the RHS, check to see if we should apply to the LHS...
1796 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1797 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1798 ShouldApply = true;
1799 }
1800
1801 // If the functor wants to apply the optimization to the RHS of LHSI,
1802 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1803 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001804 // Now all of the instructions are in the current basic block, go ahead
1805 // and perform the reassociation.
1806 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1807
1808 // First move the selected RHS to the LHS of the root...
1809 Root.setOperand(0, LHSI->getOperand(1));
1810
1811 // Make what used to be the LHS of the root be the user of the root...
1812 Value *ExtraOperand = TmpLHSI->getOperand(1);
1813 if (&Root == TmpLHSI) {
1814 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1815 return 0;
1816 }
1817 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1818 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001819 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001820 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001821 ARI = Root;
1822
1823 // Now propagate the ExtraOperand down the chain of instructions until we
1824 // get to LHSI.
1825 while (TmpLHSI != LHSI) {
1826 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1827 // Move the instruction to immediately before the chain we are
1828 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001829 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001830 ARI = NextLHSI;
1831
1832 Value *NextOp = NextLHSI->getOperand(1);
1833 NextLHSI->setOperand(1, ExtraOperand);
1834 TmpLHSI = NextLHSI;
1835 ExtraOperand = NextOp;
1836 }
1837
1838 // Now that the instructions are reassociated, have the functor perform
1839 // the transformation...
1840 return F.apply(Root);
1841 }
1842
1843 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1844 }
1845 return 0;
1846}
1847
Dan Gohman089efff2008-05-13 00:00:25 +00001848namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001849
Nick Lewycky27f6c132008-05-23 04:34:58 +00001850// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001851struct AddRHS {
1852 Value *RHS;
1853 AddRHS(Value *rhs) : RHS(rhs) {}
1854 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1855 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001856 return BinaryOperator::CreateShl(Add.getOperand(0),
1857 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001858 }
1859};
1860
1861// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1862// iff C1&C2 == 0
1863struct AddMaskingAnd {
1864 Constant *C2;
1865 AddMaskingAnd(Constant *c) : C2(c) {}
1866 bool shouldApply(Value *LHS) const {
1867 ConstantInt *C1;
1868 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1869 ConstantExpr::getAnd(C1, C2)->isNullValue();
1870 }
1871 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001872 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001873 }
1874};
1875
Dan Gohman089efff2008-05-13 00:00:25 +00001876}
1877
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001878static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1879 InstCombiner *IC) {
1880 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedman722b4792008-11-30 21:09:11 +00001881 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001882 }
1883
1884 // Figure out if the constant is the left or the right argument.
1885 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1886 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1887
1888 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1889 if (ConstIsRHS)
1890 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1891 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1892 }
1893
1894 Value *Op0 = SO, *Op1 = ConstOperand;
1895 if (!ConstIsRHS)
1896 std::swap(Op0, Op1);
1897 Instruction *New;
1898 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001899 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001900 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001901 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001902 SO->getName()+".cmp");
1903 else {
1904 assert(0 && "Unknown binary instruction type!");
1905 abort();
1906 }
1907 return IC->InsertNewInstBefore(New, I);
1908}
1909
1910// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1911// constant as the other operand, try to fold the binary operator into the
1912// select arguments. This also works for Cast instructions, which obviously do
1913// not have a second operand.
1914static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1915 InstCombiner *IC) {
1916 // Don't modify shared select instructions
1917 if (!SI->hasOneUse()) return 0;
1918 Value *TV = SI->getOperand(1);
1919 Value *FV = SI->getOperand(2);
1920
1921 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1922 // Bool selects with constant operands can be folded to logical ops.
1923 if (SI->getType() == Type::Int1Ty) return 0;
1924
1925 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1926 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1927
Gabor Greifd6da1d02008-04-06 20:25:17 +00001928 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1929 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001930 }
1931 return 0;
1932}
1933
1934
1935/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1936/// node as operand #0, see if we can fold the instruction into the PHI (which
1937/// is only possible if all operands to the PHI are constants).
1938Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1939 PHINode *PN = cast<PHINode>(I.getOperand(0));
1940 unsigned NumPHIValues = PN->getNumIncomingValues();
1941 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1942
1943 // Check to see if all of the operands of the PHI are constants. If there is
1944 // one non-constant value, remember the BB it is. If there is more than one
1945 // or if *it* is a PHI, bail out.
1946 BasicBlock *NonConstBB = 0;
1947 for (unsigned i = 0; i != NumPHIValues; ++i)
1948 if (!isa<Constant>(PN->getIncomingValue(i))) {
1949 if (NonConstBB) return 0; // More than one non-const value.
1950 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1951 NonConstBB = PN->getIncomingBlock(i);
1952
1953 // If the incoming non-constant value is in I's block, we have an infinite
1954 // loop.
1955 if (NonConstBB == I.getParent())
1956 return 0;
1957 }
1958
1959 // If there is exactly one non-constant value, we can insert a copy of the
1960 // operation in that block. However, if this is a critical edge, we would be
1961 // inserting the computation one some other paths (e.g. inside a loop). Only
1962 // do this if the pred block is unconditionally branching into the phi block.
1963 if (NonConstBB) {
1964 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1965 if (!BI || !BI->isUnconditional()) return 0;
1966 }
1967
1968 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001969 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001970 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1971 InsertNewInstBefore(NewPN, *PN);
1972 NewPN->takeName(PN);
1973
1974 // Next, add all of the operands to the PHI.
1975 if (I.getNumOperands() == 2) {
1976 Constant *C = cast<Constant>(I.getOperand(1));
1977 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001978 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001979 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1980 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1981 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1982 else
1983 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1984 } else {
1985 assert(PN->getIncomingBlock(i) == NonConstBB);
1986 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001987 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001988 PN->getIncomingValue(i), C, "phitmp",
1989 NonConstBB->getTerminator());
1990 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001991 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001992 CI->getPredicate(),
1993 PN->getIncomingValue(i), C, "phitmp",
1994 NonConstBB->getTerminator());
1995 else
1996 assert(0 && "Unknown binop!");
1997
1998 AddToWorkList(cast<Instruction>(InV));
1999 }
2000 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2001 }
2002 } else {
2003 CastInst *CI = cast<CastInst>(&I);
2004 const Type *RetTy = CI->getType();
2005 for (unsigned i = 0; i != NumPHIValues; ++i) {
2006 Value *InV;
2007 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2008 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2009 } else {
2010 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002011 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002012 I.getType(), "phitmp",
2013 NonConstBB->getTerminator());
2014 AddToWorkList(cast<Instruction>(InV));
2015 }
2016 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2017 }
2018 }
2019 return ReplaceInstUsesWith(I, NewPN);
2020}
2021
Chris Lattner55476162008-01-29 06:52:45 +00002022
Chris Lattner3554f972008-05-20 05:46:13 +00002023/// WillNotOverflowSignedAdd - Return true if we can prove that:
2024/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2025/// This basically requires proving that the add in the original type would not
2026/// overflow to change the sign bit or have a carry out.
2027bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2028 // There are different heuristics we can use for this. Here are some simple
2029 // ones.
2030
2031 // Add has the property that adding any two 2's complement numbers can only
2032 // have one carry bit which can change a sign. As such, if LHS and RHS each
2033 // have at least two sign bits, we know that the addition of the two values will
2034 // sign extend fine.
2035 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2036 return true;
2037
2038
2039 // If one of the operands only has one non-zero bit, and if the other operand
2040 // has a known-zero bit in a more significant place than it (not including the
2041 // sign bit) the ripple may go up to and fill the zero, but won't change the
2042 // sign. For example, (X & ~4) + 1.
2043
2044 // TODO: Implement.
2045
2046 return false;
2047}
2048
Chris Lattner55476162008-01-29 06:52:45 +00002049
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002050Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2051 bool Changed = SimplifyCommutative(I);
2052 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2053
2054 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2055 // X + undef -> undef
2056 if (isa<UndefValue>(RHS))
2057 return ReplaceInstUsesWith(I, RHS);
2058
2059 // X + 0 --> X
Dan Gohman7ce405e2009-06-04 22:49:04 +00002060 if (RHSC->isNullValue())
2061 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002062
2063 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2064 // X + (signbit) --> X ^ signbit
2065 const APInt& Val = CI->getValue();
2066 uint32_t BitWidth = Val.getBitWidth();
2067 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002068 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002069
2070 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2071 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002072 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002073 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002074
2075 // zext(i1) - 1 -> select i1, 0, -1
2076 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2077 if (CI->isAllOnesValue() &&
2078 ZI->getOperand(0)->getType() == Type::Int1Ty)
2079 return SelectInst::Create(ZI->getOperand(0),
2080 Constant::getNullValue(I.getType()),
2081 ConstantInt::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002082 }
2083
2084 if (isa<PHINode>(LHS))
2085 if (Instruction *NV = FoldOpIntoPhi(I))
2086 return NV;
2087
2088 ConstantInt *XorRHS = 0;
2089 Value *XorLHS = 0;
2090 if (isa<ConstantInt>(RHSC) &&
2091 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002092 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002093 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2094
2095 uint32_t Size = TySizeBits / 2;
2096 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2097 APInt CFF80Val(-C0080Val);
2098 do {
2099 if (TySizeBits > Size) {
2100 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2101 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2102 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2103 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2104 // This is a sign extend if the top bits are known zero.
2105 if (!MaskedValueIsZero(XorLHS,
2106 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2107 Size = 0; // Not a sign ext, but can't be any others either.
2108 break;
2109 }
2110 }
2111 Size >>= 1;
2112 C0080Val = APIntOps::lshr(C0080Val, Size);
2113 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2114 } while (Size >= 1);
2115
2116 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002117 // with funny bit widths then this switch statement should be removed. It
2118 // is just here to get the size of the "middle" type back up to something
2119 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002120 const Type *MiddleType = 0;
2121 switch (Size) {
2122 default: break;
2123 case 32: MiddleType = Type::Int32Ty; break;
2124 case 16: MiddleType = Type::Int16Ty; break;
2125 case 8: MiddleType = Type::Int8Ty; break;
2126 }
2127 if (MiddleType) {
2128 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2129 InsertNewInstBefore(NewTrunc, I);
2130 return new SExtInst(NewTrunc, I.getType(), I.getName());
2131 }
2132 }
2133 }
2134
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002135 if (I.getType() == Type::Int1Ty)
2136 return BinaryOperator::CreateXor(LHS, RHS);
2137
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002138 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002139 if (I.getType()->isInteger()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002140 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2141
2142 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2143 if (RHSI->getOpcode() == Instruction::Sub)
2144 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2145 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2146 }
2147 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2148 if (LHSI->getOpcode() == Instruction::Sub)
2149 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2150 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2151 }
2152 }
2153
2154 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002155 // -A + -B --> -(A + B)
2156 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002157 if (LHS->getType()->isIntOrIntVector()) {
2158 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002159 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002160 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002161 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002162 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002163 }
2164
Gabor Greifa645dd32008-05-16 19:29:10 +00002165 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002166 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002167
2168 // A + -B --> A - B
2169 if (!isa<Constant>(RHS))
2170 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002171 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002172
2173
2174 ConstantInt *C2;
2175 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2176 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002177 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002178
2179 // X*C1 + X*C2 --> X * (C1+C2)
2180 ConstantInt *C1;
2181 if (X == dyn_castFoldableMul(RHS, C1))
Dan Gohman8fd520a2009-06-15 22:12:54 +00002182 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002183 }
2184
2185 // X + X*C --> X * (C+1)
2186 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greifa645dd32008-05-16 19:29:10 +00002187 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002188
2189 // X + ~X --> -1 since ~X = -X-1
2190 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2191 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2192
2193
2194 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2195 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2196 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2197 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002198
2199 // A+B --> A|B iff A and B have no bits set in common.
2200 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2201 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2202 APInt LHSKnownOne(IT->getBitWidth(), 0);
2203 APInt LHSKnownZero(IT->getBitWidth(), 0);
2204 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2205 if (LHSKnownZero != 0) {
2206 APInt RHSKnownOne(IT->getBitWidth(), 0);
2207 APInt RHSKnownZero(IT->getBitWidth(), 0);
2208 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2209
2210 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002211 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002212 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002213 }
2214 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002215
Nick Lewycky83598a72008-02-03 07:42:09 +00002216 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002217 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002218 Value *W, *X, *Y, *Z;
2219 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2220 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2221 if (W != Y) {
2222 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002223 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002224 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002225 std::swap(W, X);
2226 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002227 std::swap(Y, Z);
2228 std::swap(W, X);
2229 }
2230 }
2231
2232 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002233 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002234 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002235 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002236 }
2237 }
2238 }
2239
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002240 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2241 Value *X = 0;
2242 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002243 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002244
2245 // (X & FF00) + xx00 -> (X+xx00) & FF00
2246 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002247 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002248 if (Anded == CRHS) {
2249 // See if all bits from the first bit set in the Add RHS up are included
2250 // in the mask. First, get the rightmost bit.
2251 const APInt& AddRHSV = CRHS->getValue();
2252
2253 // Form a mask of all bits from the lowest bit added through the top.
2254 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2255
2256 // See if the and mask includes all of these bits.
2257 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2258
2259 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2260 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002261 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002262 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002263 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002264 }
2265 }
2266 }
2267
2268 // Try to fold constant add into select arguments.
2269 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2270 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2271 return R;
2272 }
2273
2274 // add (cast *A to intptrtype) B ->
Dan Gohman9e1657f2009-06-14 23:30:43 +00002275 // cast (GEP (cast *A to i8*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002276 {
2277 CastInst *CI = dyn_cast<CastInst>(LHS);
2278 Value *Other = RHS;
2279 if (!CI) {
2280 CI = dyn_cast<CastInst>(RHS);
2281 Other = LHS;
2282 }
2283 if (CI && CI->getType()->isSized() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00002284 (CI->getType()->getScalarSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002285 TD->getIntPtrType()->getPrimitiveSizeInBits())
2286 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002287 unsigned AS =
2288 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002289 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2290 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002291 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002292 return new PtrToIntInst(I2, CI->getType());
2293 }
2294 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002295
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002296 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002297 {
2298 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002299 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002300 if (!SI) {
2301 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002302 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002303 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002304 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002305 Value *TV = SI->getTrueValue();
2306 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002307 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002308
2309 // Can we fold the add into the argument of the select?
2310 // We check both true and false select arguments for a matching subtract.
Chris Lattner641ea462008-11-16 04:46:19 +00002311 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2312 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002313 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner641ea462008-11-16 04:46:19 +00002314 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2315 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002316 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002317 }
2318 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002319
Chris Lattner3554f972008-05-20 05:46:13 +00002320 // Check for (add (sext x), y), see if we can merge this into an
2321 // integer add followed by a sext.
2322 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2323 // (add (sext x), cst) --> (sext (add x, cst'))
2324 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2325 Constant *CI =
2326 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2327 if (LHSConv->hasOneUse() &&
2328 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2329 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2330 // Insert the new, smaller add.
2331 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2332 CI, "addconv");
2333 InsertNewInstBefore(NewAdd, I);
2334 return new SExtInst(NewAdd, I.getType());
2335 }
2336 }
2337
2338 // (add (sext x), (sext y)) --> (sext (add int x, y))
2339 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2340 // Only do this if x/y have the same type, if at last one of them has a
2341 // single use (so we don't increase the number of sexts), and if the
2342 // integer add will not overflow.
2343 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2344 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2345 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2346 RHSConv->getOperand(0))) {
2347 // Insert the new integer add.
2348 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2349 RHSConv->getOperand(0),
2350 "addconv");
2351 InsertNewInstBefore(NewAdd, I);
2352 return new SExtInst(NewAdd, I.getType());
2353 }
2354 }
2355 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002356
2357 return Changed ? &I : 0;
2358}
2359
2360Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2361 bool Changed = SimplifyCommutative(I);
2362 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2363
2364 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2365 // X + 0 --> X
2366 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2367 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2368 (I.getType())->getValueAPF()))
2369 return ReplaceInstUsesWith(I, LHS);
2370 }
2371
2372 if (isa<PHINode>(LHS))
2373 if (Instruction *NV = FoldOpIntoPhi(I))
2374 return NV;
2375 }
2376
2377 // -A + B --> B - A
2378 // -A + -B --> -(A + B)
2379 if (Value *LHSV = dyn_castFNegVal(LHS))
2380 return BinaryOperator::CreateFSub(RHS, LHSV);
2381
2382 // A + -B --> A - B
2383 if (!isa<Constant>(RHS))
2384 if (Value *V = dyn_castFNegVal(RHS))
2385 return BinaryOperator::CreateFSub(LHS, V);
2386
2387 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2388 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2389 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2390 return ReplaceInstUsesWith(I, LHS);
2391
Chris Lattner3554f972008-05-20 05:46:13 +00002392 // Check for (add double (sitofp x), y), see if we can merge this into an
2393 // integer add followed by a promotion.
2394 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2395 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2396 // ... if the constant fits in the integer value. This is useful for things
2397 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2398 // requires a constant pool load, and generally allows the add to be better
2399 // instcombined.
2400 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2401 Constant *CI =
2402 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2403 if (LHSConv->hasOneUse() &&
2404 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2405 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2406 // Insert the new integer add.
2407 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2408 CI, "addconv");
2409 InsertNewInstBefore(NewAdd, I);
2410 return new SIToFPInst(NewAdd, I.getType());
2411 }
2412 }
2413
2414 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2415 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2416 // Only do this if x/y have the same type, if at last one of them has a
2417 // single use (so we don't increase the number of int->fp conversions),
2418 // and if the integer add will not overflow.
2419 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2420 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2421 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2422 RHSConv->getOperand(0))) {
2423 // Insert the new integer add.
2424 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2425 RHSConv->getOperand(0),
2426 "addconv");
2427 InsertNewInstBefore(NewAdd, I);
2428 return new SIToFPInst(NewAdd, I.getType());
2429 }
2430 }
2431 }
2432
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002433 return Changed ? &I : 0;
2434}
2435
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002436Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2437 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2438
Dan Gohman7ce405e2009-06-04 22:49:04 +00002439 if (Op0 == Op1) // sub X, X -> 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002440 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2441
2442 // If this is a 'B = x-(-A)', change to B = x+A...
2443 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002444 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002445
2446 if (isa<UndefValue>(Op0))
2447 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2448 if (isa<UndefValue>(Op1))
2449 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2450
2451 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2452 // Replace (-1 - A) with (~A)...
2453 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002454 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002455
2456 // C - ~X == X + (1+C)
2457 Value *X = 0;
2458 if (match(Op1, m_Not(m_Value(X))))
Gabor Greifa645dd32008-05-16 19:29:10 +00002459 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002460
2461 // -(X >>u 31) -> (X >>s 31)
2462 // -(X >>s 31) -> (X >>u 31)
2463 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002464 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002465 if (SI->getOpcode() == Instruction::LShr) {
2466 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2467 // Check to see if we are shifting out everything but the sign bit.
2468 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2469 SI->getType()->getPrimitiveSizeInBits()-1) {
2470 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002471 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002472 SI->getOperand(0), CU, SI->getName());
2473 }
2474 }
2475 }
2476 else if (SI->getOpcode() == Instruction::AShr) {
2477 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2478 // Check to see if we are shifting out everything but the sign bit.
2479 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2480 SI->getType()->getPrimitiveSizeInBits()-1) {
2481 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002482 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002483 SI->getOperand(0), CU, SI->getName());
2484 }
2485 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002486 }
2487 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002488 }
2489
2490 // Try to fold constant sub into select arguments.
2491 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2492 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2493 return R;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002494 }
2495
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002496 if (I.getType() == Type::Int1Ty)
2497 return BinaryOperator::CreateXor(Op0, Op1);
2498
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002499 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002500 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002501 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002502 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002503 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002504 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002505 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2506 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2507 // C1-(X+C2) --> (C1-C2)-X
Dan Gohman8fd520a2009-06-15 22:12:54 +00002508 return BinaryOperator::CreateSub(ConstantExpr::getSub(CI1, CI2),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002509 Op1I->getOperand(0));
2510 }
2511 }
2512
2513 if (Op1I->hasOneUse()) {
2514 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2515 // is not used by anyone else...
2516 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002517 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002518 // Swap the two operands of the subexpr...
2519 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2520 Op1I->setOperand(0, IIOp1);
2521 Op1I->setOperand(1, IIOp0);
2522
2523 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002524 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002525 }
2526
2527 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2528 //
2529 if (Op1I->getOpcode() == Instruction::And &&
2530 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2531 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2532
2533 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00002534 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2535 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002536 }
2537
2538 // 0 - (X sdiv C) -> (X sdiv -C)
2539 if (Op1I->getOpcode() == Instruction::SDiv)
2540 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2541 if (CSI->isZero())
2542 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002543 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002544 ConstantExpr::getNeg(DivRHS));
2545
2546 // X - X*C --> X * (1-C)
2547 ConstantInt *C2 = 0;
2548 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002549 Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2550 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002551 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002552 }
2553 }
2554 }
2555
Dan Gohman7ce405e2009-06-04 22:49:04 +00002556 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2557 if (Op0I->getOpcode() == Instruction::Add) {
2558 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2559 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2560 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2561 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2562 } else if (Op0I->getOpcode() == Instruction::Sub) {
2563 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2564 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002565 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002566 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002567
2568 ConstantInt *C1;
2569 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2570 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002571 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002572
2573 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2574 if (X == dyn_castFoldableMul(Op1, C2))
Dan Gohman8fd520a2009-06-15 22:12:54 +00002575 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002576 }
2577 return 0;
2578}
2579
Dan Gohman7ce405e2009-06-04 22:49:04 +00002580Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2581 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2582
2583 // If this is a 'B = x-(-A)', change to B = x+A...
2584 if (Value *V = dyn_castFNegVal(Op1))
2585 return BinaryOperator::CreateFAdd(Op0, V);
2586
2587 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2588 if (Op1I->getOpcode() == Instruction::FAdd) {
2589 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2590 return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2591 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2592 return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2593 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002594 }
2595
2596 return 0;
2597}
2598
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002599/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2600/// comparison only checks the sign bit. If it only checks the sign bit, set
2601/// TrueIfSigned if the result of the comparison is true when the input value is
2602/// signed.
2603static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2604 bool &TrueIfSigned) {
2605 switch (pred) {
2606 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2607 TrueIfSigned = true;
2608 return RHS->isZero();
2609 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2610 TrueIfSigned = true;
2611 return RHS->isAllOnesValue();
2612 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2613 TrueIfSigned = false;
2614 return RHS->isAllOnesValue();
2615 case ICmpInst::ICMP_UGT:
2616 // True if LHS u> RHS and RHS == high-bit-mask - 1
2617 TrueIfSigned = true;
2618 return RHS->getValue() ==
2619 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2620 case ICmpInst::ICMP_UGE:
2621 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2622 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002623 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002624 default:
2625 return false;
2626 }
2627}
2628
2629Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2630 bool Changed = SimplifyCommutative(I);
2631 Value *Op0 = I.getOperand(0);
2632
Dan Gohmana22a8402009-06-04 17:12:12 +00002633 // TODO: If Op1 is undef and Op0 is finite, return zero.
2634 if (!I.getType()->isFPOrFPVector() &&
2635 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002636 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2637
2638 // Simplify mul instructions with a constant RHS...
2639 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2640 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2641
2642 // ((X << C1)*C2) == (X * (C2 << C1))
2643 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2644 if (SI->getOpcode() == Instruction::Shl)
2645 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002646 return BinaryOperator::CreateMul(SI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002647 ConstantExpr::getShl(CI, ShOp));
2648
2649 if (CI->isZero())
2650 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2651 if (CI->equalsInt(1)) // X * 1 == X
2652 return ReplaceInstUsesWith(I, Op0);
2653 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002654 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002655
2656 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2657 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002658 return BinaryOperator::CreateShl(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002659 ConstantInt::get(Op0->getType(), Val.logBase2()));
2660 }
Chris Lattner6297fc72008-08-11 22:06:05 +00002661 } else if (isa<VectorType>(Op1->getType())) {
Dan Gohmana22a8402009-06-04 17:12:12 +00002662 // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
Nick Lewycky94418732008-11-27 20:21:08 +00002663
2664 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2665 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2666 return BinaryOperator::CreateNeg(Op0, I.getName());
2667
2668 // As above, vector X*splat(1.0) -> X in all defined cases.
2669 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002670 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2671 if (CI->equalsInt(1))
2672 return ReplaceInstUsesWith(I, Op0);
2673 }
2674 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002675 }
2676
2677 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2678 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002679 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002680 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002681 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002682 Op1, "tmp");
2683 InsertNewInstBefore(Add, I);
2684 Value *C1C2 = ConstantExpr::getMul(Op1,
2685 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002686 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002687
2688 }
2689
2690 // Try to fold constant mul into select arguments.
2691 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2692 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2693 return R;
2694
2695 if (isa<PHINode>(Op0))
2696 if (Instruction *NV = FoldOpIntoPhi(I))
2697 return NV;
2698 }
2699
2700 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2701 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002702 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002703
Nick Lewycky1c246402008-11-21 07:33:58 +00002704 // (X / Y) * Y = X - (X % Y)
2705 // (X / Y) * -Y = (X % Y) - X
2706 {
2707 Value *Op1 = I.getOperand(1);
2708 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2709 if (!BO ||
2710 (BO->getOpcode() != Instruction::UDiv &&
2711 BO->getOpcode() != Instruction::SDiv)) {
2712 Op1 = Op0;
2713 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2714 }
2715 Value *Neg = dyn_castNegVal(Op1);
2716 if (BO && BO->hasOneUse() &&
2717 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2718 (BO->getOpcode() == Instruction::UDiv ||
2719 BO->getOpcode() == Instruction::SDiv)) {
2720 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2721
2722 Instruction *Rem;
2723 if (BO->getOpcode() == Instruction::UDiv)
2724 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2725 else
2726 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2727
2728 InsertNewInstBefore(Rem, I);
2729 Rem->takeName(BO);
2730
2731 if (Op1BO == Op1)
2732 return BinaryOperator::CreateSub(Op0BO, Rem);
2733 else
2734 return BinaryOperator::CreateSub(Rem, Op0BO);
2735 }
2736 }
2737
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002738 if (I.getType() == Type::Int1Ty)
2739 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2740
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002741 // If one of the operands of the multiply is a cast from a boolean value, then
2742 // we know the bool is either zero or one, so this is a 'masking' multiply.
2743 // See if we can simplify things based on how the boolean was originally
2744 // formed.
2745 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002746 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002747 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2748 BoolCast = CI;
2749 if (!BoolCast)
2750 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2751 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2752 BoolCast = CI;
2753 if (BoolCast) {
2754 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2755 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2756 const Type *SCOpTy = SCIOp0->getType();
2757 bool TIS = false;
2758
2759 // If the icmp is true iff the sign bit of X is set, then convert this
2760 // multiply into a shift/and combination.
2761 if (isa<ConstantInt>(SCIOp1) &&
2762 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2763 TIS) {
2764 // Shift the X value right to turn it into "all signbits".
2765 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2766 SCOpTy->getPrimitiveSizeInBits()-1);
2767 Value *V =
2768 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002769 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002770 BoolCast->getOperand(0)->getName()+
2771 ".mask"), I);
2772
2773 // If the multiply type is not the same as the source type, sign extend
2774 // or truncate to the multiply type.
2775 if (I.getType() != V->getType()) {
2776 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2777 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2778 Instruction::CastOps opcode =
2779 (SrcBits == DstBits ? Instruction::BitCast :
2780 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2781 V = InsertCastBefore(opcode, V, I.getType(), I);
2782 }
2783
2784 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002785 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002786 }
2787 }
2788 }
2789
2790 return Changed ? &I : 0;
2791}
2792
Dan Gohman7ce405e2009-06-04 22:49:04 +00002793Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2794 bool Changed = SimplifyCommutative(I);
2795 Value *Op0 = I.getOperand(0);
2796
2797 // Simplify mul instructions with a constant RHS...
2798 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2799 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2800 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2801 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2802 if (Op1F->isExactlyValue(1.0))
2803 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2804 } else if (isa<VectorType>(Op1->getType())) {
2805 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2806 // As above, vector X*splat(1.0) -> X in all defined cases.
2807 if (Constant *Splat = Op1V->getSplatValue()) {
2808 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2809 if (F->isExactlyValue(1.0))
2810 return ReplaceInstUsesWith(I, Op0);
2811 }
2812 }
2813 }
2814
2815 // Try to fold constant mul into select arguments.
2816 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2817 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2818 return R;
2819
2820 if (isa<PHINode>(Op0))
2821 if (Instruction *NV = FoldOpIntoPhi(I))
2822 return NV;
2823 }
2824
2825 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2826 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2827 return BinaryOperator::CreateFMul(Op0v, Op1v);
2828
2829 return Changed ? &I : 0;
2830}
2831
Chris Lattner76972db2008-07-14 00:15:52 +00002832/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2833/// instruction.
2834bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2835 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2836
2837 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2838 int NonNullOperand = -1;
2839 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2840 if (ST->isNullValue())
2841 NonNullOperand = 2;
2842 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2843 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2844 if (ST->isNullValue())
2845 NonNullOperand = 1;
2846
2847 if (NonNullOperand == -1)
2848 return false;
2849
2850 Value *SelectCond = SI->getOperand(0);
2851
2852 // Change the div/rem to use 'Y' instead of the select.
2853 I.setOperand(1, SI->getOperand(NonNullOperand));
2854
2855 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2856 // problem. However, the select, or the condition of the select may have
2857 // multiple uses. Based on our knowledge that the operand must be non-zero,
2858 // propagate the known value for the select into other uses of it, and
2859 // propagate a known value of the condition into its other users.
2860
2861 // If the select and condition only have a single use, don't bother with this,
2862 // early exit.
2863 if (SI->use_empty() && SelectCond->hasOneUse())
2864 return true;
2865
2866 // Scan the current block backward, looking for other uses of SI.
2867 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2868
2869 while (BBI != BBFront) {
2870 --BBI;
2871 // If we found a call to a function, we can't assume it will return, so
2872 // information from below it cannot be propagated above it.
2873 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2874 break;
2875
2876 // Replace uses of the select or its condition with the known values.
2877 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2878 I != E; ++I) {
2879 if (*I == SI) {
2880 *I = SI->getOperand(NonNullOperand);
2881 AddToWorkList(BBI);
2882 } else if (*I == SelectCond) {
2883 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2884 ConstantInt::getFalse();
2885 AddToWorkList(BBI);
2886 }
2887 }
2888
2889 // If we past the instruction, quit looking for it.
2890 if (&*BBI == SI)
2891 SI = 0;
2892 if (&*BBI == SelectCond)
2893 SelectCond = 0;
2894
2895 // If we ran out of things to eliminate, break out of the loop.
2896 if (SelectCond == 0 && SI == 0)
2897 break;
2898
2899 }
2900 return true;
2901}
2902
2903
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002904/// This function implements the transforms on div instructions that work
2905/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2906/// used by the visitors to those instructions.
2907/// @brief Transforms common to all three div instructions
2908Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2909 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2910
Chris Lattner653ef3c2008-02-19 06:12:18 +00002911 // undef / X -> 0 for integer.
2912 // undef / X -> undef for FP (the undef could be a snan).
2913 if (isa<UndefValue>(Op0)) {
2914 if (Op0->getType()->isFPOrFPVector())
2915 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002916 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002917 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002918
2919 // X / undef -> undef
2920 if (isa<UndefValue>(Op1))
2921 return ReplaceInstUsesWith(I, Op1);
2922
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002923 return 0;
2924}
2925
2926/// This function implements the transforms common to both integer division
2927/// instructions (udiv and sdiv). It is called by the visitors to those integer
2928/// division instructions.
2929/// @brief Common integer divide transforms
2930Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2931 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2932
Chris Lattnercefb36c2008-05-16 02:59:42 +00002933 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002934 if (Op0 == Op1) {
2935 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002936 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002937 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2938 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2939 }
2940
Dan Gohman8fd520a2009-06-15 22:12:54 +00002941 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002942 return ReplaceInstUsesWith(I, CI);
2943 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002944
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002945 if (Instruction *Common = commonDivTransforms(I))
2946 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002947
2948 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2949 // This does not apply for fdiv.
2950 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2951 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002952
2953 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2954 // div X, 1 == X
2955 if (RHS->equalsInt(1))
2956 return ReplaceInstUsesWith(I, Op0);
2957
2958 // (X / C1) / C2 -> X / (C1*C2)
2959 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2960 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2961 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00002962 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2963 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2964 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002965 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002966 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002967 }
2968
2969 if (!RHS->isZero()) { // avoid X udiv 0
2970 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2971 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2972 return R;
2973 if (isa<PHINode>(Op0))
2974 if (Instruction *NV = FoldOpIntoPhi(I))
2975 return NV;
2976 }
2977 }
2978
2979 // 0 / X == 0, we don't need to preserve faults!
2980 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2981 if (LHS->equalsInt(0))
2982 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2983
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002984 // It can't be division by zero, hence it must be division by one.
2985 if (I.getType() == Type::Int1Ty)
2986 return ReplaceInstUsesWith(I, Op0);
2987
Nick Lewycky94418732008-11-27 20:21:08 +00002988 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2989 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2990 // div X, 1 == X
2991 if (X->isOne())
2992 return ReplaceInstUsesWith(I, Op0);
2993 }
2994
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002995 return 0;
2996}
2997
2998Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2999 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3000
3001 // Handle the integer div common cases
3002 if (Instruction *Common = commonIDivTransforms(I))
3003 return Common;
3004
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003005 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00003006 // X udiv C^2 -> X >> C
3007 // Check to see if this is an unsigned division with an exact power of 2,
3008 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003009 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003010 return BinaryOperator::CreateLShr(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003011 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003012
3013 // X udiv C, where C >= signbit
3014 if (C->getValue().isNegative()) {
3015 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
3016 I);
3017 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3018 ConstantInt::get(I.getType(), 1));
3019 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003020 }
3021
3022 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3023 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3024 if (RHSI->getOpcode() == Instruction::Shl &&
3025 isa<ConstantInt>(RHSI->getOperand(0))) {
3026 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3027 if (C1.isPowerOf2()) {
3028 Value *N = RHSI->getOperand(1);
3029 const Type *NTy = N->getType();
3030 if (uint32_t C2 = C1.logBase2()) {
3031 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00003032 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003033 }
Gabor Greifa645dd32008-05-16 19:29:10 +00003034 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003035 }
3036 }
3037 }
3038
3039 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3040 // where C1&C2 are powers of two.
3041 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3042 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3043 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3044 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3045 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3046 // Compute the shift amounts
3047 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3048 // Construct the "on true" case of the select
3049 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003050 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003051 Op0, TC, SI->getName()+".t");
3052 TSI = InsertNewInstBefore(TSI, I);
3053
3054 // Construct the "on false" case of the select
3055 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003056 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003057 Op0, FC, SI->getName()+".f");
3058 FSI = InsertNewInstBefore(FSI, I);
3059
3060 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003061 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003062 }
3063 }
3064 return 0;
3065}
3066
3067Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3068 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3069
3070 // Handle the integer div common cases
3071 if (Instruction *Common = commonIDivTransforms(I))
3072 return Common;
3073
3074 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3075 // sdiv X, -1 == -X
3076 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00003077 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003078 }
3079
3080 // If the sign bits of both operands are zero (i.e. we can prove they are
3081 // unsigned inputs), turn this into a udiv.
3082 if (I.getType()->isInteger()) {
3083 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3084 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00003085 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003086 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003087 }
3088 }
3089
3090 return 0;
3091}
3092
3093Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3094 return commonDivTransforms(I);
3095}
3096
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003097/// This function implements the transforms on rem instructions that work
3098/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3099/// is used by the visitors to those instructions.
3100/// @brief Transforms common to all three rem instructions
3101Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3102 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3103
Chris Lattner653ef3c2008-02-19 06:12:18 +00003104 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3105 if (I.getType()->isFPOrFPVector())
3106 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003107 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003108 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003109 if (isa<UndefValue>(Op1))
3110 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3111
3112 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003113 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3114 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003115
3116 return 0;
3117}
3118
3119/// This function implements the transforms common to both integer remainder
3120/// instructions (urem and srem). It is called by the visitors to those integer
3121/// remainder instructions.
3122/// @brief Common integer remainder transforms
3123Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3124 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3125
3126 if (Instruction *common = commonRemTransforms(I))
3127 return common;
3128
Dale Johannesena51f7372009-01-21 00:35:19 +00003129 // 0 % X == 0 for integer, we don't need to preserve faults!
3130 if (Constant *LHS = dyn_cast<Constant>(Op0))
3131 if (LHS->isNullValue())
3132 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3133
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003134 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3135 // X % 0 == undef, we don't need to preserve faults!
3136 if (RHS->equalsInt(0))
3137 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3138
3139 if (RHS->equalsInt(1)) // X % 1 == 0
3140 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3141
3142 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3143 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3144 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3145 return R;
3146 } else if (isa<PHINode>(Op0I)) {
3147 if (Instruction *NV = FoldOpIntoPhi(I))
3148 return NV;
3149 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003150
3151 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003152 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003153 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003154 }
3155 }
3156
3157 return 0;
3158}
3159
3160Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3161 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3162
3163 if (Instruction *common = commonIRemTransforms(I))
3164 return common;
3165
3166 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3167 // X urem C^2 -> X and C
3168 // Check to see if this is an unsigned remainder with an exact power of 2,
3169 // if so, convert to a bitwise and.
3170 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3171 if (C->getValue().isPowerOf2())
Gabor Greifa645dd32008-05-16 19:29:10 +00003172 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003173 }
3174
3175 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3176 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3177 if (RHSI->getOpcode() == Instruction::Shl &&
3178 isa<ConstantInt>(RHSI->getOperand(0))) {
3179 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3180 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003181 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003182 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003183 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003184 }
3185 }
3186 }
3187
3188 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3189 // where C1&C2 are powers of two.
3190 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3191 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3192 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3193 // STO == 0 and SFO == 0 handled above.
3194 if ((STO->getValue().isPowerOf2()) &&
3195 (SFO->getValue().isPowerOf2())) {
3196 Value *TrueAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003197 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003198 Value *FalseAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003199 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003200 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003201 }
3202 }
3203 }
3204
3205 return 0;
3206}
3207
3208Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3209 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3210
Dan Gohmandb3dd962007-11-05 23:16:33 +00003211 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003212 if (Instruction *common = commonIRemTransforms(I))
3213 return common;
3214
3215 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003216 if (!isa<Constant>(RHSNeg) ||
3217 (isa<ConstantInt>(RHSNeg) &&
3218 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003219 // X % -Y -> X % Y
3220 AddUsesToWorkList(I);
3221 I.setOperand(1, RHSNeg);
3222 return &I;
3223 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003224
Dan Gohmandb3dd962007-11-05 23:16:33 +00003225 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003226 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003227 if (I.getType()->isInteger()) {
3228 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3229 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3230 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003231 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003232 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003233 }
3234
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003235 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003236 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3237 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003238
Nick Lewyckyfd746832008-12-20 16:48:00 +00003239 bool hasNegative = false;
3240 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3241 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3242 if (RHS->getValue().isNegative())
3243 hasNegative = true;
3244
3245 if (hasNegative) {
3246 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003247 for (unsigned i = 0; i != VWidth; ++i) {
3248 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3249 if (RHS->getValue().isNegative())
3250 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3251 else
3252 Elts[i] = RHS;
3253 }
3254 }
3255
3256 Constant *NewRHSV = ConstantVector::get(Elts);
3257 if (NewRHSV != RHSV) {
Nick Lewycky338ecd52008-12-18 06:42:28 +00003258 AddUsesToWorkList(I);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003259 I.setOperand(1, NewRHSV);
3260 return &I;
3261 }
3262 }
3263 }
3264
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003265 return 0;
3266}
3267
3268Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3269 return commonRemTransforms(I);
3270}
3271
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003272// isOneBitSet - Return true if there is exactly one bit set in the specified
3273// constant.
3274static bool isOneBitSet(const ConstantInt *CI) {
3275 return CI->getValue().isPowerOf2();
3276}
3277
3278// isHighOnes - Return true if the constant is of the form 1+0+.
3279// This is the same as lowones(~X).
3280static bool isHighOnes(const ConstantInt *CI) {
3281 return (~CI->getValue() + 1).isPowerOf2();
3282}
3283
3284/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3285/// are carefully arranged to allow folding of expressions such as:
3286///
3287/// (A < B) | (A > B) --> (A != B)
3288///
3289/// Note that this is only valid if the first and second predicates have the
3290/// same sign. Is illegal to do: (A u< B) | (A s> B)
3291///
3292/// Three bits are used to represent the condition, as follows:
3293/// 0 A > B
3294/// 1 A == B
3295/// 2 A < B
3296///
3297/// <=> Value Definition
3298/// 000 0 Always false
3299/// 001 1 A > B
3300/// 010 2 A == B
3301/// 011 3 A >= B
3302/// 100 4 A < B
3303/// 101 5 A != B
3304/// 110 6 A <= B
3305/// 111 7 Always true
3306///
3307static unsigned getICmpCode(const ICmpInst *ICI) {
3308 switch (ICI->getPredicate()) {
3309 // False -> 0
3310 case ICmpInst::ICMP_UGT: return 1; // 001
3311 case ICmpInst::ICMP_SGT: return 1; // 001
3312 case ICmpInst::ICMP_EQ: return 2; // 010
3313 case ICmpInst::ICMP_UGE: return 3; // 011
3314 case ICmpInst::ICMP_SGE: return 3; // 011
3315 case ICmpInst::ICMP_ULT: return 4; // 100
3316 case ICmpInst::ICMP_SLT: return 4; // 100
3317 case ICmpInst::ICMP_NE: return 5; // 101
3318 case ICmpInst::ICMP_ULE: return 6; // 110
3319 case ICmpInst::ICMP_SLE: return 6; // 110
3320 // True -> 7
3321 default:
3322 assert(0 && "Invalid ICmp predicate!");
3323 return 0;
3324 }
3325}
3326
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003327/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3328/// predicate into a three bit mask. It also returns whether it is an ordered
3329/// predicate by reference.
3330static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3331 isOrdered = false;
3332 switch (CC) {
3333 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3334 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003335 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3336 case FCmpInst::FCMP_UGT: return 1; // 001
3337 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3338 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003339 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3340 case FCmpInst::FCMP_UGE: return 3; // 011
3341 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3342 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003343 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3344 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003345 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3346 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003347 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003348 default:
3349 // Not expecting FCMP_FALSE and FCMP_TRUE;
3350 assert(0 && "Unexpected FCmp predicate!");
3351 return 0;
3352 }
3353}
3354
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003355/// getICmpValue - This is the complement of getICmpCode, which turns an
3356/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003357/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003358/// of predicate to use in the new icmp instruction.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003359static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3360 switch (code) {
3361 default: assert(0 && "Illegal ICmp code!");
3362 case 0: return ConstantInt::getFalse();
3363 case 1:
3364 if (sign)
3365 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3366 else
3367 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3368 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3369 case 3:
3370 if (sign)
3371 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3372 else
3373 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3374 case 4:
3375 if (sign)
3376 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3377 else
3378 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3379 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3380 case 6:
3381 if (sign)
3382 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3383 else
3384 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3385 case 7: return ConstantInt::getTrue();
3386 }
3387}
3388
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003389/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3390/// opcode and two operands into either a FCmp instruction. isordered is passed
3391/// in to determine which kind of predicate to use in the new fcmp instruction.
3392static Value *getFCmpValue(bool isordered, unsigned code,
3393 Value *LHS, Value *RHS) {
3394 switch (code) {
Evan Chengf1f2cea2008-10-14 18:13:38 +00003395 default: assert(0 && "Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003396 case 0:
3397 if (isordered)
3398 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3399 else
3400 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3401 case 1:
3402 if (isordered)
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003403 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3404 else
3405 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003406 case 2:
3407 if (isordered)
3408 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3409 else
3410 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003411 case 3:
3412 if (isordered)
3413 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3414 else
3415 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3416 case 4:
3417 if (isordered)
3418 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3419 else
3420 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3421 case 5:
3422 if (isordered)
Evan Chengf1f2cea2008-10-14 18:13:38 +00003423 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3424 else
3425 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3426 case 6:
3427 if (isordered)
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003428 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3429 else
3430 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng72988052008-10-14 18:44:08 +00003431 case 7: return ConstantInt::getTrue();
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003432 }
3433}
3434
Chris Lattner2972b822008-11-16 04:55:20 +00003435/// PredicatesFoldable - Return true if both predicates match sign or if at
3436/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003437static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3438 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattner2972b822008-11-16 04:55:20 +00003439 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3440 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003441}
3442
3443namespace {
3444// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3445struct FoldICmpLogical {
3446 InstCombiner &IC;
3447 Value *LHS, *RHS;
3448 ICmpInst::Predicate pred;
3449 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3450 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3451 pred(ICI->getPredicate()) {}
3452 bool shouldApply(Value *V) const {
3453 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3454 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003455 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3456 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003457 return false;
3458 }
3459 Instruction *apply(Instruction &Log) const {
3460 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3461 if (ICI->getOperand(0) != LHS) {
3462 assert(ICI->getOperand(1) == LHS);
3463 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3464 }
3465
3466 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3467 unsigned LHSCode = getICmpCode(ICI);
3468 unsigned RHSCode = getICmpCode(RHSICI);
3469 unsigned Code;
3470 switch (Log.getOpcode()) {
3471 case Instruction::And: Code = LHSCode & RHSCode; break;
3472 case Instruction::Or: Code = LHSCode | RHSCode; break;
3473 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3474 default: assert(0 && "Illegal logical opcode!"); return 0;
3475 }
3476
3477 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3478 ICmpInst::isSignedPredicate(ICI->getPredicate());
3479
3480 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3481 if (Instruction *I = dyn_cast<Instruction>(RV))
3482 return I;
3483 // Otherwise, it's a constant boolean value...
3484 return IC.ReplaceInstUsesWith(Log, RV);
3485 }
3486};
3487} // end anonymous namespace
3488
3489// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3490// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3491// guaranteed to be a binary operator.
3492Instruction *InstCombiner::OptAndOp(Instruction *Op,
3493 ConstantInt *OpRHS,
3494 ConstantInt *AndRHS,
3495 BinaryOperator &TheAnd) {
3496 Value *X = Op->getOperand(0);
3497 Constant *Together = 0;
3498 if (!Op->isShift())
Dan Gohman8fd520a2009-06-15 22:12:54 +00003499 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003500
3501 switch (Op->getOpcode()) {
3502 case Instruction::Xor:
3503 if (Op->hasOneUse()) {
3504 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003505 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003506 InsertNewInstBefore(And, TheAnd);
3507 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003508 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003509 }
3510 break;
3511 case Instruction::Or:
3512 if (Together == AndRHS) // (X | C) & C --> C
3513 return ReplaceInstUsesWith(TheAnd, AndRHS);
3514
3515 if (Op->hasOneUse() && Together != OpRHS) {
3516 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003517 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003518 InsertNewInstBefore(Or, TheAnd);
3519 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003520 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003521 }
3522 break;
3523 case Instruction::Add:
3524 if (Op->hasOneUse()) {
3525 // Adding a one to a single bit bit-field should be turned into an XOR
3526 // of the bit. First thing to check is to see if this AND is with a
3527 // single bit constant.
3528 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3529
3530 // If there is only one bit set...
3531 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3532 // Ok, at this point, we know that we are masking the result of the
3533 // ADD down to exactly one bit. If the constant we are adding has
3534 // no bits set below this bit, then we can eliminate the ADD.
3535 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3536
3537 // Check to see if any bits below the one bit set in AndRHSV are set.
3538 if ((AddRHS & (AndRHSV-1)) == 0) {
3539 // If not, the only thing that can effect the output of the AND is
3540 // the bit specified by AndRHSV. If that bit is set, the effect of
3541 // the XOR is to toggle the bit. If it is clear, then the ADD has
3542 // no effect.
3543 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3544 TheAnd.setOperand(0, X);
3545 return &TheAnd;
3546 } else {
3547 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003548 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003549 InsertNewInstBefore(NewAnd, TheAnd);
3550 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003551 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003552 }
3553 }
3554 }
3555 }
3556 break;
3557
3558 case Instruction::Shl: {
3559 // We know that the AND will not produce any of the bits shifted in, so if
3560 // the anded constant includes them, clear them now!
3561 //
3562 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3563 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3564 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3565 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3566
3567 if (CI->getValue() == ShlMask) {
3568 // Masking out bits that the shift already masks
3569 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3570 } else if (CI != AndRHS) { // Reducing bits set in and.
3571 TheAnd.setOperand(1, CI);
3572 return &TheAnd;
3573 }
3574 break;
3575 }
3576 case Instruction::LShr:
3577 {
3578 // We know that the AND will not produce any of the bits shifted in, so if
3579 // the anded constant includes them, clear them now! This only applies to
3580 // unsigned shifts, because a signed shr may bring in set bits!
3581 //
3582 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3583 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3584 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3585 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3586
3587 if (CI->getValue() == ShrMask) {
3588 // Masking out bits that the shift already masks.
3589 return ReplaceInstUsesWith(TheAnd, Op);
3590 } else if (CI != AndRHS) {
3591 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3592 return &TheAnd;
3593 }
3594 break;
3595 }
3596 case Instruction::AShr:
3597 // Signed shr.
3598 // See if this is shifting in some sign extension, then masking it out
3599 // with an and.
3600 if (Op->hasOneUse()) {
3601 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3602 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3603 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3604 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3605 if (C == AndRHS) { // Masking out bits shifted in.
3606 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3607 // Make the argument unsigned.
3608 Value *ShVal = Op->getOperand(0);
3609 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003610 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003611 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003612 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003613 }
3614 }
3615 break;
3616 }
3617 return 0;
3618}
3619
3620
3621/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3622/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3623/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3624/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3625/// insert new instructions.
3626Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3627 bool isSigned, bool Inside,
3628 Instruction &IB) {
3629 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3630 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3631 "Lo is not <= Hi in range emission code!");
3632
3633 if (Inside) {
3634 if (Lo == Hi) // Trivially false.
3635 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3636
3637 // V >= Min && V < Hi --> V < Hi
3638 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3639 ICmpInst::Predicate pred = (isSigned ?
3640 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3641 return new ICmpInst(pred, V, Hi);
3642 }
3643
3644 // Emit V-Lo <u Hi-Lo
3645 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003646 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003647 InsertNewInstBefore(Add, IB);
3648 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3649 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3650 }
3651
3652 if (Lo == Hi) // Trivially true.
3653 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3654
3655 // V < Min || V >= Hi -> V > Hi-1
3656 Hi = SubOne(cast<ConstantInt>(Hi));
3657 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3658 ICmpInst::Predicate pred = (isSigned ?
3659 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3660 return new ICmpInst(pred, V, Hi);
3661 }
3662
3663 // Emit V-Lo >u Hi-1-Lo
3664 // Note that Hi has already had one subtracted from it, above.
3665 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003666 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003667 InsertNewInstBefore(Add, IB);
3668 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3669 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3670}
3671
3672// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3673// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3674// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3675// not, since all 1s are not contiguous.
3676static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3677 const APInt& V = Val->getValue();
3678 uint32_t BitWidth = Val->getType()->getBitWidth();
3679 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3680
3681 // look for the first zero bit after the run of ones
3682 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3683 // look for the first non-zero bit
3684 ME = V.getActiveBits();
3685 return true;
3686}
3687
3688/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3689/// where isSub determines whether the operator is a sub. If we can fold one of
3690/// the following xforms:
3691///
3692/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3693/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3694/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3695///
3696/// return (A +/- B).
3697///
3698Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3699 ConstantInt *Mask, bool isSub,
3700 Instruction &I) {
3701 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3702 if (!LHSI || LHSI->getNumOperands() != 2 ||
3703 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3704
3705 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3706
3707 switch (LHSI->getOpcode()) {
3708 default: return 0;
3709 case Instruction::And:
Dan Gohman8fd520a2009-06-15 22:12:54 +00003710 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003711 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3712 if ((Mask->getValue().countLeadingZeros() +
3713 Mask->getValue().countPopulation()) ==
3714 Mask->getValue().getBitWidth())
3715 break;
3716
3717 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3718 // part, we don't need any explicit masks to take them out of A. If that
3719 // is all N is, ignore it.
3720 uint32_t MB = 0, ME = 0;
3721 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3722 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3723 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3724 if (MaskedValueIsZero(RHS, Mask))
3725 break;
3726 }
3727 }
3728 return 0;
3729 case Instruction::Or:
3730 case Instruction::Xor:
3731 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3732 if ((Mask->getValue().countLeadingZeros() +
3733 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Dan Gohman8fd520a2009-06-15 22:12:54 +00003734 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003735 break;
3736 return 0;
3737 }
3738
3739 Instruction *New;
3740 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003741 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003742 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003743 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003744 return InsertNewInstBefore(New, I);
3745}
3746
Chris Lattner0631ea72008-11-16 05:06:21 +00003747/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3748Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3749 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00003750 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00003751 ConstantInt *LHSCst, *RHSCst;
3752 ICmpInst::Predicate LHSCC, RHSCC;
3753
Chris Lattnerf3803482008-11-16 05:10:52 +00003754 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner0631ea72008-11-16 05:06:21 +00003755 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerf3803482008-11-16 05:10:52 +00003756 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00003757 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003758
3759 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3760 // where C is a power of 2
3761 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3762 LHSCst->getValue().isPowerOf2()) {
3763 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3764 InsertNewInstBefore(NewOr, I);
3765 return new ICmpInst(LHSCC, NewOr, LHSCst);
3766 }
3767
3768 // From here on, we only handle:
3769 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3770 if (Val != Val2) return 0;
3771
Chris Lattner0631ea72008-11-16 05:06:21 +00003772 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3773 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3774 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3775 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3776 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3777 return 0;
3778
3779 // We can't fold (ugt x, C) & (sgt x, C2).
3780 if (!PredicatesFoldable(LHSCC, RHSCC))
3781 return 0;
3782
3783 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003784 bool ShouldSwap;
Chris Lattner0631ea72008-11-16 05:06:21 +00003785 if (ICmpInst::isSignedPredicate(LHSCC) ||
3786 (ICmpInst::isEquality(LHSCC) &&
3787 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003788 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003789 else
Chris Lattner665298f2008-11-16 05:14:43 +00003790 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3791
3792 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003793 std::swap(LHS, RHS);
3794 std::swap(LHSCst, RHSCst);
3795 std::swap(LHSCC, RHSCC);
3796 }
3797
3798 // At this point, we know we have have two icmp instructions
3799 // comparing a value against two constants and and'ing the result
3800 // together. Because of the above check, we know that we only have
3801 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3802 // (from the FoldICmpLogical check above), that the two constants
3803 // are not equal and that the larger constant is on the RHS
3804 assert(LHSCst != RHSCst && "Compares not folded above?");
3805
3806 switch (LHSCC) {
3807 default: assert(0 && "Unknown integer condition code!");
3808 case ICmpInst::ICMP_EQ:
3809 switch (RHSCC) {
3810 default: assert(0 && "Unknown integer condition code!");
3811 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3812 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3813 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3814 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3815 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3816 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3817 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3818 return ReplaceInstUsesWith(I, LHS);
3819 }
3820 case ICmpInst::ICMP_NE:
3821 switch (RHSCC) {
3822 default: assert(0 && "Unknown integer condition code!");
3823 case ICmpInst::ICMP_ULT:
3824 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3825 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3826 break; // (X != 13 & X u< 15) -> no change
3827 case ICmpInst::ICMP_SLT:
3828 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3829 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3830 break; // (X != 13 & X s< 15) -> no change
3831 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3832 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3833 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3834 return ReplaceInstUsesWith(I, RHS);
3835 case ICmpInst::ICMP_NE:
3836 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3837 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3838 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3839 Val->getName()+".off");
3840 InsertNewInstBefore(Add, I);
3841 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3842 ConstantInt::get(Add->getType(), 1));
3843 }
3844 break; // (X != 13 & X != 15) -> no change
3845 }
3846 break;
3847 case ICmpInst::ICMP_ULT:
3848 switch (RHSCC) {
3849 default: assert(0 && "Unknown integer condition code!");
3850 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3851 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3852 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3853 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3854 break;
3855 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3856 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3857 return ReplaceInstUsesWith(I, LHS);
3858 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3859 break;
3860 }
3861 break;
3862 case ICmpInst::ICMP_SLT:
3863 switch (RHSCC) {
3864 default: assert(0 && "Unknown integer condition code!");
3865 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3866 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3867 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3868 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3869 break;
3870 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3871 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3872 return ReplaceInstUsesWith(I, LHS);
3873 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3874 break;
3875 }
3876 break;
3877 case ICmpInst::ICMP_UGT:
3878 switch (RHSCC) {
3879 default: assert(0 && "Unknown integer condition code!");
3880 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3881 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3882 return ReplaceInstUsesWith(I, RHS);
3883 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3884 break;
3885 case ICmpInst::ICMP_NE:
3886 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3887 return new ICmpInst(LHSCC, Val, RHSCst);
3888 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003889 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner0631ea72008-11-16 05:06:21 +00003890 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3891 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3892 break;
3893 }
3894 break;
3895 case ICmpInst::ICMP_SGT:
3896 switch (RHSCC) {
3897 default: assert(0 && "Unknown integer condition code!");
3898 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3899 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3900 return ReplaceInstUsesWith(I, RHS);
3901 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3902 break;
3903 case ICmpInst::ICMP_NE:
3904 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3905 return new ICmpInst(LHSCC, Val, RHSCst);
3906 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003907 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner0631ea72008-11-16 05:06:21 +00003908 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3909 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3910 break;
3911 }
3912 break;
3913 }
Chris Lattner0631ea72008-11-16 05:06:21 +00003914
3915 return 0;
3916}
3917
3918
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003919Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3920 bool Changed = SimplifyCommutative(I);
3921 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3922
3923 if (isa<UndefValue>(Op1)) // X & undef -> 0
3924 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3925
3926 // and X, X = X
3927 if (Op0 == Op1)
3928 return ReplaceInstUsesWith(I, Op1);
3929
3930 // See if we can simplify any instructions used by the instruction whose sole
3931 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00003932 if (SimplifyDemandedInstructionBits(I))
3933 return &I;
3934 if (isa<VectorType>(I.getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003935 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3936 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3937 return ReplaceInstUsesWith(I, I.getOperand(0));
3938 } else if (isa<ConstantAggregateZero>(Op1)) {
3939 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3940 }
3941 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00003942
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003943 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3944 const APInt& AndRHSMask = AndRHS->getValue();
3945 APInt NotAndRHS(~AndRHSMask);
3946
3947 // Optimize a variety of ((val OP C1) & C2) combinations...
3948 if (isa<BinaryOperator>(Op0)) {
3949 Instruction *Op0I = cast<Instruction>(Op0);
3950 Value *Op0LHS = Op0I->getOperand(0);
3951 Value *Op0RHS = Op0I->getOperand(1);
3952 switch (Op0I->getOpcode()) {
3953 case Instruction::Xor:
3954 case Instruction::Or:
3955 // If the mask is only needed on one incoming arm, push it up.
3956 if (Op0I->hasOneUse()) {
3957 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3958 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003959 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003960 Op0RHS->getName()+".masked");
3961 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003962 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003963 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3964 }
3965 if (!isa<Constant>(Op0RHS) &&
3966 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3967 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003968 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003969 Op0LHS->getName()+".masked");
3970 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003971 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003972 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3973 }
3974 }
3975
3976 break;
3977 case Instruction::Add:
3978 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3979 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3980 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3981 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003982 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003983 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003984 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003985 break;
3986
3987 case Instruction::Sub:
3988 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3989 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3990 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3991 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003992 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003993
Nick Lewyckya349ba42008-07-10 05:51:40 +00003994 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3995 // has 1's for all bits that the subtraction with A might affect.
3996 if (Op0I->hasOneUse()) {
3997 uint32_t BitWidth = AndRHSMask.getBitWidth();
3998 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3999 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4000
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004001 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004002 if (!(A && A->isZero()) && // avoid infinite recursion.
4003 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004004 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4005 InsertNewInstBefore(NewNeg, I);
4006 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4007 }
4008 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004009 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004010
4011 case Instruction::Shl:
4012 case Instruction::LShr:
4013 // (1 << x) & 1 --> zext(x == 0)
4014 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004015 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004016 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
4017 Constant::getNullValue(I.getType()));
4018 InsertNewInstBefore(NewICmp, I);
4019 return new ZExtInst(NewICmp, I.getType());
4020 }
4021 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004022 }
4023
4024 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4025 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4026 return Res;
4027 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4028 // If this is an integer truncation or change from signed-to-unsigned, and
4029 // if the source is an and/or with immediate, transform it. This
4030 // frequently occurs for bitfield accesses.
4031 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4032 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4033 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004034 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004035 if (CastOp->getOpcode() == Instruction::And) {
4036 // Change: and (cast (and X, C1) to T), C2
4037 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4038 // This will fold the two constants together, which may allow
4039 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00004040 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004041 CastOp->getOperand(0), I.getType(),
4042 CastOp->getName()+".shrunk");
4043 NewCast = InsertNewInstBefore(NewCast, I);
4044 // trunc_or_bitcast(C1)&C2
4045 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4046 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004047 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004048 } else if (CastOp->getOpcode() == Instruction::Or) {
4049 // Change: and (cast (or X, C1) to T), C2
4050 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4051 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4052 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4053 return ReplaceInstUsesWith(I, AndRHS);
4054 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004055 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004056 }
4057 }
4058
4059 // Try to fold constant and into select arguments.
4060 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4061 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4062 return R;
4063 if (isa<PHINode>(Op0))
4064 if (Instruction *NV = FoldOpIntoPhi(I))
4065 return NV;
4066 }
4067
4068 Value *Op0NotVal = dyn_castNotVal(Op0);
4069 Value *Op1NotVal = dyn_castNotVal(Op1);
4070
4071 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4072 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4073
4074 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4075 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004076 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004077 I.getName()+".demorgan");
4078 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004079 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004080 }
4081
4082 {
4083 Value *A = 0, *B = 0, *C = 0, *D = 0;
4084 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4085 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4086 return ReplaceInstUsesWith(I, Op1);
4087
4088 // (A|B) & ~(A&B) -> A^B
4089 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4090 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004091 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004092 }
4093 }
4094
4095 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4096 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4097 return ReplaceInstUsesWith(I, Op0);
4098
4099 // ~(A&B) & (A|B) -> A^B
4100 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4101 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004102 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004103 }
4104 }
4105
4106 if (Op0->hasOneUse() &&
4107 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4108 if (A == Op1) { // (A^B)&A -> A&(A^B)
4109 I.swapOperands(); // Simplify below
4110 std::swap(Op0, Op1);
4111 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4112 cast<BinaryOperator>(Op0)->swapOperands();
4113 I.swapOperands(); // Simplify below
4114 std::swap(Op0, Op1);
4115 }
4116 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004117
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004118 if (Op1->hasOneUse() &&
4119 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4120 if (B == Op0) { // B&(A^B) -> B&(B^A)
4121 cast<BinaryOperator>(Op1)->swapOperands();
4122 std::swap(A, B);
4123 }
4124 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00004125 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004126 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004127 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004128 }
4129 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004130
4131 // (A&((~A)|B)) -> A&B
Chris Lattner9db479f2008-12-01 05:16:26 +00004132 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4133 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4134 return BinaryOperator::CreateAnd(A, Op1);
4135 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4136 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4137 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004138 }
4139
4140 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4141 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4142 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4143 return R;
4144
Chris Lattner0631ea72008-11-16 05:06:21 +00004145 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4146 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4147 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004148 }
4149
4150 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4151 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4152 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4153 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4154 const Type *SrcTy = Op0C->getOperand(0)->getType();
4155 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4156 // Only do this if the casts both really cause code to be generated.
4157 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4158 I.getType(), TD) &&
4159 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4160 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004161 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004162 Op1C->getOperand(0),
4163 I.getName());
4164 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004165 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004166 }
4167 }
4168
4169 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4170 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4171 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4172 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4173 SI0->getOperand(1) == SI1->getOperand(1) &&
4174 (SI0->hasOneUse() || SI1->hasOneUse())) {
4175 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004176 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004177 SI1->getOperand(0),
4178 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004179 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004180 SI1->getOperand(1));
4181 }
4182 }
4183
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004184 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004185 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4186 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4187 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004188 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4189 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner91882432007-10-24 05:38:08 +00004190 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4191 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4192 // If either of the constants are nans, then the whole thing returns
4193 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004194 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004195 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4196 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4197 RHS->getOperand(0));
4198 }
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004199 } else {
4200 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4201 FCmpInst::Predicate Op0CC, Op1CC;
4202 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4203 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Chengf1f2cea2008-10-14 18:13:38 +00004204 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4205 // Swap RHS operands to match LHS.
4206 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4207 std::swap(Op1LHS, Op1RHS);
4208 }
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004209 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4210 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4211 if (Op0CC == Op1CC)
4212 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4213 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4214 Op1CC == FCmpInst::FCMP_FALSE)
4215 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4216 else if (Op0CC == FCmpInst::FCMP_TRUE)
4217 return ReplaceInstUsesWith(I, Op1);
4218 else if (Op1CC == FCmpInst::FCMP_TRUE)
4219 return ReplaceInstUsesWith(I, Op0);
4220 bool Op0Ordered;
4221 bool Op1Ordered;
4222 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4223 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4224 if (Op1Pred == 0) {
4225 std::swap(Op0, Op1);
4226 std::swap(Op0Pred, Op1Pred);
4227 std::swap(Op0Ordered, Op1Ordered);
4228 }
4229 if (Op0Pred == 0) {
4230 // uno && ueq -> uno && (uno || eq) -> ueq
4231 // ord && olt -> ord && (ord && lt) -> olt
4232 if (Op0Ordered == Op1Ordered)
4233 return ReplaceInstUsesWith(I, Op1);
4234 // uno && oeq -> uno && (ord && eq) -> false
4235 // uno && ord -> false
4236 if (!Op0Ordered)
4237 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4238 // ord && ueq -> ord && (uno || eq) -> oeq
4239 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4240 Op0LHS, Op0RHS));
4241 }
4242 }
4243 }
4244 }
Chris Lattner91882432007-10-24 05:38:08 +00004245 }
4246 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004247
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004248 return Changed ? &I : 0;
4249}
4250
Chris Lattner567f5112008-10-05 02:13:19 +00004251/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4252/// capable of providing pieces of a bswap. The subexpression provides pieces
4253/// of a bswap if it is proven that each of the non-zero bytes in the output of
4254/// the expression came from the corresponding "byte swapped" byte in some other
4255/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4256/// we know that the expression deposits the low byte of %X into the high byte
4257/// of the bswap result and that all other bytes are zero. This expression is
4258/// accepted, the high byte of ByteValues is set to X to indicate a correct
4259/// match.
4260///
4261/// This function returns true if the match was unsuccessful and false if so.
4262/// On entry to the function the "OverallLeftShift" is a signed integer value
4263/// indicating the number of bytes that the subexpression is later shifted. For
4264/// example, if the expression is later right shifted by 16 bits, the
4265/// OverallLeftShift value would be -2 on entry. This is used to specify which
4266/// byte of ByteValues is actually being set.
4267///
4268/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4269/// byte is masked to zero by a user. For example, in (X & 255), X will be
4270/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4271/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4272/// always in the local (OverallLeftShift) coordinate space.
4273///
4274static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4275 SmallVector<Value*, 8> &ByteValues) {
4276 if (Instruction *I = dyn_cast<Instruction>(V)) {
4277 // If this is an or instruction, it may be an inner node of the bswap.
4278 if (I->getOpcode() == Instruction::Or) {
4279 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4280 ByteValues) ||
4281 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4282 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004283 }
Chris Lattner567f5112008-10-05 02:13:19 +00004284
4285 // If this is a logical shift by a constant multiple of 8, recurse with
4286 // OverallLeftShift and ByteMask adjusted.
4287 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4288 unsigned ShAmt =
4289 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4290 // Ensure the shift amount is defined and of a byte value.
4291 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4292 return true;
4293
4294 unsigned ByteShift = ShAmt >> 3;
4295 if (I->getOpcode() == Instruction::Shl) {
4296 // X << 2 -> collect(X, +2)
4297 OverallLeftShift += ByteShift;
4298 ByteMask >>= ByteShift;
4299 } else {
4300 // X >>u 2 -> collect(X, -2)
4301 OverallLeftShift -= ByteShift;
4302 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004303 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004304 }
4305
4306 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4307 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4308
4309 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4310 ByteValues);
4311 }
4312
4313 // If this is a logical 'and' with a mask that clears bytes, clear the
4314 // corresponding bytes in ByteMask.
4315 if (I->getOpcode() == Instruction::And &&
4316 isa<ConstantInt>(I->getOperand(1))) {
4317 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4318 unsigned NumBytes = ByteValues.size();
4319 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4320 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4321
4322 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4323 // If this byte is masked out by a later operation, we don't care what
4324 // the and mask is.
4325 if ((ByteMask & (1 << i)) == 0)
4326 continue;
4327
4328 // If the AndMask is all zeros for this byte, clear the bit.
4329 APInt MaskB = AndMask & Byte;
4330 if (MaskB == 0) {
4331 ByteMask &= ~(1U << i);
4332 continue;
4333 }
4334
4335 // If the AndMask is not all ones for this byte, it's not a bytezap.
4336 if (MaskB != Byte)
4337 return true;
4338
4339 // Otherwise, this byte is kept.
4340 }
4341
4342 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4343 ByteValues);
4344 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004345 }
4346
Chris Lattner567f5112008-10-05 02:13:19 +00004347 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4348 // the input value to the bswap. Some observations: 1) if more than one byte
4349 // is demanded from this input, then it could not be successfully assembled
4350 // into a byteswap. At least one of the two bytes would not be aligned with
4351 // their ultimate destination.
4352 if (!isPowerOf2_32(ByteMask)) return true;
4353 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004354
Chris Lattner567f5112008-10-05 02:13:19 +00004355 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4356 // is demanded, it needs to go into byte 0 of the result. This means that the
4357 // byte needs to be shifted until it lands in the right byte bucket. The
4358 // shift amount depends on the position: if the byte is coming from the high
4359 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4360 // low part, it must be shifted left.
4361 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4362 if (InputByteNo < ByteValues.size()/2) {
4363 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4364 return true;
4365 } else {
4366 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4367 return true;
4368 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004369
4370 // If the destination byte value is already defined, the values are or'd
4371 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004372 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004373 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004374 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004375 return false;
4376}
4377
4378/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4379/// If so, insert the new bswap intrinsic and return it.
4380Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4381 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004382 if (!ITy || ITy->getBitWidth() % 16 ||
4383 // ByteMask only allows up to 32-byte values.
4384 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004385 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4386
4387 /// ByteValues - For each byte of the result, we keep track of which value
4388 /// defines each byte.
4389 SmallVector<Value*, 8> ByteValues;
4390 ByteValues.resize(ITy->getBitWidth()/8);
4391
4392 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004393 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4394 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004395 return 0;
4396
4397 // Check to see if all of the bytes come from the same value.
4398 Value *V = ByteValues[0];
4399 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4400
4401 // Check to make sure that all of the bytes come from the same value.
4402 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4403 if (ByteValues[i] != V)
4404 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004405 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004406 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004407 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004408 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004409}
4410
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004411/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4412/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4413/// we can simplify this expression to "cond ? C : D or B".
4414static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4415 Value *C, Value *D) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004416 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004417 Value *Cond = 0;
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004418 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004419 return 0;
4420
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004421 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004422 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004423 return SelectInst::Create(Cond, C, B);
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004424 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004425 return SelectInst::Create(Cond, C, B);
4426 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004427 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004428 return SelectInst::Create(Cond, C, D);
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004429 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004430 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004431 return 0;
4432}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004433
Chris Lattner0c678e52008-11-16 05:20:07 +00004434/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4435Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4436 ICmpInst *LHS, ICmpInst *RHS) {
4437 Value *Val, *Val2;
4438 ConstantInt *LHSCst, *RHSCst;
4439 ICmpInst::Predicate LHSCC, RHSCC;
4440
4441 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4442 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4443 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4444 return 0;
4445
4446 // From here on, we only handle:
4447 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4448 if (Val != Val2) return 0;
4449
4450 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4451 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4452 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4453 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4454 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4455 return 0;
4456
4457 // We can't fold (ugt x, C) | (sgt x, C2).
4458 if (!PredicatesFoldable(LHSCC, RHSCC))
4459 return 0;
4460
4461 // Ensure that the larger constant is on the RHS.
4462 bool ShouldSwap;
4463 if (ICmpInst::isSignedPredicate(LHSCC) ||
4464 (ICmpInst::isEquality(LHSCC) &&
4465 ICmpInst::isSignedPredicate(RHSCC)))
4466 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4467 else
4468 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4469
4470 if (ShouldSwap) {
4471 std::swap(LHS, RHS);
4472 std::swap(LHSCst, RHSCst);
4473 std::swap(LHSCC, RHSCC);
4474 }
4475
4476 // At this point, we know we have have two icmp instructions
4477 // comparing a value against two constants and or'ing the result
4478 // together. Because of the above check, we know that we only have
4479 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4480 // FoldICmpLogical check above), that the two constants are not
4481 // equal.
4482 assert(LHSCst != RHSCst && "Compares not folded above?");
4483
4484 switch (LHSCC) {
4485 default: assert(0 && "Unknown integer condition code!");
4486 case ICmpInst::ICMP_EQ:
4487 switch (RHSCC) {
4488 default: assert(0 && "Unknown integer condition code!");
4489 case ICmpInst::ICMP_EQ:
4490 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4491 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4492 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4493 Val->getName()+".off");
4494 InsertNewInstBefore(Add, I);
Dan Gohman8fd520a2009-06-15 22:12:54 +00004495 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Chris Lattner0c678e52008-11-16 05:20:07 +00004496 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4497 }
4498 break; // (X == 13 | X == 15) -> no change
4499 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4500 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4501 break;
4502 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4503 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4504 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4505 return ReplaceInstUsesWith(I, RHS);
4506 }
4507 break;
4508 case ICmpInst::ICMP_NE:
4509 switch (RHSCC) {
4510 default: assert(0 && "Unknown integer condition code!");
4511 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4512 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4513 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4514 return ReplaceInstUsesWith(I, LHS);
4515 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4516 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4517 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4518 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4519 }
4520 break;
4521 case ICmpInst::ICMP_ULT:
4522 switch (RHSCC) {
4523 default: assert(0 && "Unknown integer condition code!");
4524 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4525 break;
4526 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4527 // If RHSCst is [us]MAXINT, it is always false. Not handling
4528 // this can cause overflow.
4529 if (RHSCst->isMaxValue(false))
4530 return ReplaceInstUsesWith(I, LHS);
4531 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4532 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4533 break;
4534 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4535 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4536 return ReplaceInstUsesWith(I, RHS);
4537 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4538 break;
4539 }
4540 break;
4541 case ICmpInst::ICMP_SLT:
4542 switch (RHSCC) {
4543 default: assert(0 && "Unknown integer condition code!");
4544 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4545 break;
4546 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4547 // If RHSCst is [us]MAXINT, it is always false. Not handling
4548 // this can cause overflow.
4549 if (RHSCst->isMaxValue(true))
4550 return ReplaceInstUsesWith(I, LHS);
4551 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4552 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4553 break;
4554 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4555 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4556 return ReplaceInstUsesWith(I, RHS);
4557 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4558 break;
4559 }
4560 break;
4561 case ICmpInst::ICMP_UGT:
4562 switch (RHSCC) {
4563 default: assert(0 && "Unknown integer condition code!");
4564 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4565 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4566 return ReplaceInstUsesWith(I, LHS);
4567 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4568 break;
4569 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4570 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4571 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4572 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4573 break;
4574 }
4575 break;
4576 case ICmpInst::ICMP_SGT:
4577 switch (RHSCC) {
4578 default: assert(0 && "Unknown integer condition code!");
4579 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4580 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4581 return ReplaceInstUsesWith(I, LHS);
4582 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4583 break;
4584 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4585 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4586 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4587 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4588 break;
4589 }
4590 break;
4591 }
4592 return 0;
4593}
4594
Bill Wendlingdae376a2008-12-01 08:23:25 +00004595/// FoldOrWithConstants - This helper function folds:
4596///
Bill Wendling236a1192008-12-02 05:09:00 +00004597/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004598///
4599/// into:
4600///
Bill Wendling236a1192008-12-02 05:09:00 +00004601/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004602///
Bill Wendling236a1192008-12-02 05:09:00 +00004603/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004604Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004605 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004606 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4607 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004608
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004609 Value *V1 = 0;
4610 ConstantInt *CI2 = 0;
4611 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004612
Bill Wendling86ee3162008-12-02 06:18:11 +00004613 APInt Xor = CI1->getValue() ^ CI2->getValue();
4614 if (!Xor.isAllOnesValue()) return 0;
4615
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004616 if (V1 == A || V1 == B) {
Bill Wendling86ee3162008-12-02 06:18:11 +00004617 Instruction *NewOp =
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004618 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4619 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004620 }
4621
4622 return 0;
4623}
4624
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004625Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4626 bool Changed = SimplifyCommutative(I);
4627 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4628
4629 if (isa<UndefValue>(Op1)) // X | undef -> -1
4630 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4631
4632 // or X, X = X
4633 if (Op0 == Op1)
4634 return ReplaceInstUsesWith(I, Op0);
4635
4636 // See if we can simplify any instructions used by the instruction whose sole
4637 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004638 if (SimplifyDemandedInstructionBits(I))
4639 return &I;
4640 if (isa<VectorType>(I.getType())) {
4641 if (isa<ConstantAggregateZero>(Op1)) {
4642 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4643 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4644 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4645 return ReplaceInstUsesWith(I, I.getOperand(1));
4646 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004647 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004648
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004649 // or X, -1 == -1
4650 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4651 ConstantInt *C1 = 0; Value *X = 0;
4652 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4653 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004654 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004655 InsertNewInstBefore(Or, I);
4656 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004657 return BinaryOperator::CreateAnd(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004658 ConstantInt::get(RHS->getValue() | C1->getValue()));
4659 }
4660
4661 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4662 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004663 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004664 InsertNewInstBefore(Or, I);
4665 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004666 return BinaryOperator::CreateXor(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004667 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4668 }
4669
4670 // Try to fold constant and into select arguments.
4671 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4672 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4673 return R;
4674 if (isa<PHINode>(Op0))
4675 if (Instruction *NV = FoldOpIntoPhi(I))
4676 return NV;
4677 }
4678
4679 Value *A = 0, *B = 0;
4680 ConstantInt *C1 = 0, *C2 = 0;
4681
4682 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4683 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4684 return ReplaceInstUsesWith(I, Op1);
4685 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4686 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4687 return ReplaceInstUsesWith(I, Op0);
4688
4689 // (A | B) | C and A | (B | C) -> bswap if possible.
4690 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4691 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4692 match(Op1, m_Or(m_Value(), m_Value())) ||
4693 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4694 match(Op1, m_Shift(m_Value(), m_Value())))) {
4695 if (Instruction *BSwap = MatchBSwap(I))
4696 return BSwap;
4697 }
4698
4699 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4700 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4701 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004702 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004703 InsertNewInstBefore(NOr, I);
4704 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004705 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004706 }
4707
4708 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4709 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4710 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004711 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004712 InsertNewInstBefore(NOr, I);
4713 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004714 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004715 }
4716
4717 // (A & C)|(B & D)
4718 Value *C = 0, *D = 0;
4719 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4720 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4721 Value *V1 = 0, *V2 = 0, *V3 = 0;
4722 C1 = dyn_cast<ConstantInt>(C);
4723 C2 = dyn_cast<ConstantInt>(D);
4724 if (C1 && C2) { // (A & C1)|(B & C2)
4725 // If we have: ((V + N) & C1) | (V & C2)
4726 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4727 // replace with V+N.
4728 if (C1->getValue() == ~C2->getValue()) {
4729 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4730 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4731 // Add commutes, try both ways.
4732 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4733 return ReplaceInstUsesWith(I, A);
4734 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4735 return ReplaceInstUsesWith(I, A);
4736 }
4737 // Or commutes, try both ways.
4738 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4739 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4740 // Add commutes, try both ways.
4741 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4742 return ReplaceInstUsesWith(I, B);
4743 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4744 return ReplaceInstUsesWith(I, B);
4745 }
4746 }
4747 V1 = 0; V2 = 0; V3 = 0;
4748 }
4749
4750 // Check to see if we have any common things being and'ed. If so, find the
4751 // terms for V1 & (V2|V3).
4752 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4753 if (A == B) // (A & C)|(A & D) == A & (C|D)
4754 V1 = A, V2 = C, V3 = D;
4755 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4756 V1 = A, V2 = B, V3 = C;
4757 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4758 V1 = C, V2 = A, V3 = D;
4759 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4760 V1 = C, V2 = A, V3 = B;
4761
4762 if (V1) {
4763 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004764 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4765 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004766 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004767 }
Dan Gohman279952c2008-10-28 22:38:57 +00004768
Dan Gohman35b76162008-10-30 20:40:10 +00004769 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004770 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4771 return Match;
4772 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4773 return Match;
4774 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4775 return Match;
4776 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4777 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004778
Bill Wendling22ca8352008-11-30 13:52:49 +00004779 // ((A&~B)|(~A&B)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004780 if ((match(C, m_Not(m_Specific(D))) &&
4781 match(B, m_Not(m_Specific(A)))))
4782 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004783 // ((~B&A)|(~A&B)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004784 if ((match(A, m_Not(m_Specific(D))) &&
4785 match(B, m_Not(m_Specific(C)))))
4786 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004787 // ((A&~B)|(B&~A)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004788 if ((match(C, m_Not(m_Specific(B))) &&
4789 match(D, m_Not(m_Specific(A)))))
4790 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004791 // ((~B&A)|(B&~A)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004792 if ((match(A, m_Not(m_Specific(B))) &&
4793 match(D, m_Not(m_Specific(C)))))
4794 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004795 }
4796
4797 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4798 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4799 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4800 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4801 SI0->getOperand(1) == SI1->getOperand(1) &&
4802 (SI0->hasOneUse() || SI1->hasOneUse())) {
4803 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004804 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004805 SI1->getOperand(0),
4806 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004807 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004808 SI1->getOperand(1));
4809 }
4810 }
4811
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004812 // ((A|B)&1)|(B&-2) -> (A&1) | B
4813 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4814 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004815 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004816 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004817 }
4818 // (B&-2)|((A|B)&1) -> (A&1) | B
4819 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4820 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004821 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004822 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004823 }
4824
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004825 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4826 if (A == Op1) // ~A | A == -1
4827 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4828 } else {
4829 A = 0;
4830 }
4831 // Note, A is still live here!
4832 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4833 if (Op0 == B)
4834 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4835
4836 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4837 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004838 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004839 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004840 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004841 }
4842 }
4843
4844 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4845 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4846 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4847 return R;
4848
Chris Lattner0c678e52008-11-16 05:20:07 +00004849 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4850 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4851 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004852 }
4853
4854 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004855 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004856 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4857 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004858 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4859 !isa<ICmpInst>(Op1C->getOperand(0))) {
4860 const Type *SrcTy = Op0C->getOperand(0)->getType();
4861 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4862 // Only do this if the casts both really cause code to be
4863 // generated.
4864 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4865 I.getType(), TD) &&
4866 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4867 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004868 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004869 Op1C->getOperand(0),
4870 I.getName());
4871 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004872 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004873 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004874 }
4875 }
Chris Lattner91882432007-10-24 05:38:08 +00004876 }
4877
4878
4879 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4880 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4881 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4882 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004883 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng72988052008-10-14 18:44:08 +00004884 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner91882432007-10-24 05:38:08 +00004885 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4886 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4887 // If either of the constants are nans, then the whole thing returns
4888 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004889 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004890 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4891
4892 // Otherwise, no need to compare the two constants, compare the
4893 // rest.
4894 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4895 RHS->getOperand(0));
4896 }
Evan Cheng72988052008-10-14 18:44:08 +00004897 } else {
4898 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4899 FCmpInst::Predicate Op0CC, Op1CC;
4900 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4901 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4902 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4903 // Swap RHS operands to match LHS.
4904 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4905 std::swap(Op1LHS, Op1RHS);
4906 }
4907 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4908 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4909 if (Op0CC == Op1CC)
4910 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4911 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4912 Op1CC == FCmpInst::FCMP_TRUE)
4913 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4914 else if (Op0CC == FCmpInst::FCMP_FALSE)
4915 return ReplaceInstUsesWith(I, Op1);
4916 else if (Op1CC == FCmpInst::FCMP_FALSE)
4917 return ReplaceInstUsesWith(I, Op0);
4918 bool Op0Ordered;
4919 bool Op1Ordered;
4920 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4921 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4922 if (Op0Ordered == Op1Ordered) {
4923 // If both are ordered or unordered, return a new fcmp with
4924 // or'ed predicates.
4925 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4926 Op0LHS, Op0RHS);
4927 if (Instruction *I = dyn_cast<Instruction>(RV))
4928 return I;
4929 // Otherwise, it's a constant boolean value...
4930 return ReplaceInstUsesWith(I, RV);
4931 }
4932 }
4933 }
4934 }
Chris Lattner91882432007-10-24 05:38:08 +00004935 }
4936 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004937
4938 return Changed ? &I : 0;
4939}
4940
Dan Gohman089efff2008-05-13 00:00:25 +00004941namespace {
4942
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004943// XorSelf - Implements: X ^ X --> 0
4944struct XorSelf {
4945 Value *RHS;
4946 XorSelf(Value *rhs) : RHS(rhs) {}
4947 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4948 Instruction *apply(BinaryOperator &Xor) const {
4949 return &Xor;
4950 }
4951};
4952
Dan Gohman089efff2008-05-13 00:00:25 +00004953}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004954
4955Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4956 bool Changed = SimplifyCommutative(I);
4957 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4958
Evan Chenge5cd8032008-03-25 20:07:13 +00004959 if (isa<UndefValue>(Op1)) {
4960 if (isa<UndefValue>(Op0))
4961 // Handle undef ^ undef -> 0 special case. This is a common
4962 // idiom (misuse).
4963 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004964 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004965 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004966
4967 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4968 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004969 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004970 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4971 }
4972
4973 // See if we can simplify any instructions used by the instruction whose sole
4974 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004975 if (SimplifyDemandedInstructionBits(I))
4976 return &I;
4977 if (isa<VectorType>(I.getType()))
4978 if (isa<ConstantAggregateZero>(Op1))
4979 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004980
4981 // Is this a ~ operation?
4982 if (Value *NotOp = dyn_castNotVal(&I)) {
4983 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4984 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4985 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4986 if (Op0I->getOpcode() == Instruction::And ||
4987 Op0I->getOpcode() == Instruction::Or) {
4988 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4989 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4990 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00004991 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004992 Op0I->getOperand(1)->getName()+".not");
4993 InsertNewInstBefore(NotY, I);
4994 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00004995 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004996 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004997 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004998 }
4999 }
5000 }
5001 }
5002
5003
5004 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00005005 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005006 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005007 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005008 return new ICmpInst(ICI->getInversePredicate(),
5009 ICI->getOperand(0), ICI->getOperand(1));
5010
Nick Lewycky1405e922007-08-06 20:04:16 +00005011 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5012 return new FCmpInst(FCI->getInversePredicate(),
5013 FCI->getOperand(0), FCI->getOperand(1));
5014 }
5015
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005016 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5017 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5018 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5019 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5020 Instruction::CastOps Opcode = Op0C->getOpcode();
5021 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5022 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
5023 Op0C->getDestTy())) {
5024 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5025 CI->getOpcode(), CI->getInversePredicate(),
5026 CI->getOperand(0), CI->getOperand(1)), I);
5027 NewCI->takeName(CI);
5028 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5029 }
5030 }
5031 }
5032 }
5033 }
5034
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005035 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5036 // ~(c-X) == X-c-1 == X+(-c-1)
5037 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5038 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5039 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5040 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5041 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005042 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005043 }
5044
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005045 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005046 if (Op0I->getOpcode() == Instruction::Add) {
5047 // ~(X-c) --> (-c-1)-X
5048 if (RHS->isAllOnesValue()) {
5049 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005050 return BinaryOperator::CreateSub(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005051 ConstantExpr::getSub(NegOp0CI,
5052 ConstantInt::get(I.getType(), 1)),
5053 Op0I->getOperand(0));
5054 } else if (RHS->getValue().isSignBit()) {
5055 // (X + C) ^ signbit -> (X + C + signbit)
5056 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005057 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005058
5059 }
5060 } else if (Op0I->getOpcode() == Instruction::Or) {
5061 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5062 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5063 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5064 // Anything in both C1 and C2 is known to be zero, remove it from
5065 // NewRHS.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005066 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005067 NewRHS = ConstantExpr::getAnd(NewRHS,
5068 ConstantExpr::getNot(CommonBits));
5069 AddToWorkList(Op0I);
5070 I.setOperand(0, Op0I->getOperand(0));
5071 I.setOperand(1, NewRHS);
5072 return &I;
5073 }
5074 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005075 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005076 }
5077
5078 // Try to fold constant and into select arguments.
5079 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5080 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5081 return R;
5082 if (isa<PHINode>(Op0))
5083 if (Instruction *NV = FoldOpIntoPhi(I))
5084 return NV;
5085 }
5086
5087 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5088 if (X == Op1)
5089 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5090
5091 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5092 if (X == Op0)
5093 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5094
5095
5096 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5097 if (Op1I) {
5098 Value *A, *B;
5099 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5100 if (A == Op0) { // B^(B|A) == (A|B)^B
5101 Op1I->swapOperands();
5102 I.swapOperands();
5103 std::swap(Op0, Op1);
5104 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5105 I.swapOperands(); // Simplified below.
5106 std::swap(Op0, Op1);
5107 }
Chris Lattner3b874082008-11-16 05:38:51 +00005108 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5109 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5110 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5111 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005112 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5113 if (A == Op0) { // A^(A&B) -> A^(B&A)
5114 Op1I->swapOperands();
5115 std::swap(A, B);
5116 }
5117 if (B == Op0) { // A^(B&A) -> (B&A)^A
5118 I.swapOperands(); // Simplified below.
5119 std::swap(Op0, Op1);
5120 }
5121 }
5122 }
5123
5124 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5125 if (Op0I) {
5126 Value *A, *B;
5127 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5128 if (A == Op1) // (B|A)^B == (A|B)^B
5129 std::swap(A, B);
5130 if (B == Op1) { // (A|B)^B == A & ~B
5131 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00005132 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5133 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005134 }
Chris Lattner3b874082008-11-16 05:38:51 +00005135 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5136 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5137 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5138 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005139 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5140 if (A == Op1) // (A&B)^A -> (B&A)^A
5141 std::swap(A, B);
5142 if (B == Op1 && // (B&A)^A == ~B & A
5143 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5144 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00005145 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5146 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005147 }
5148 }
5149 }
5150
5151 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5152 if (Op0I && Op1I && Op0I->isShift() &&
5153 Op0I->getOpcode() == Op1I->getOpcode() &&
5154 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5155 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5156 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005157 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005158 Op1I->getOperand(0),
5159 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005160 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005161 Op1I->getOperand(1));
5162 }
5163
5164 if (Op0I && Op1I) {
5165 Value *A, *B, *C, *D;
5166 // (A & B)^(A | B) -> A ^ B
5167 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5168 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5169 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005170 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005171 }
5172 // (A | B)^(A & B) -> A ^ B
5173 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5174 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5175 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005176 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005177 }
5178
5179 // (A & B)^(C & D)
5180 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5181 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5182 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5183 // (X & Y)^(X & Y) -> (Y^Z) & X
5184 Value *X = 0, *Y = 0, *Z = 0;
5185 if (A == C)
5186 X = A, Y = B, Z = D;
5187 else if (A == D)
5188 X = A, Y = B, Z = C;
5189 else if (B == C)
5190 X = B, Y = A, Z = D;
5191 else if (B == D)
5192 X = B, Y = A, Z = C;
5193
5194 if (X) {
5195 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005196 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5197 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005198 }
5199 }
5200 }
5201
5202 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5203 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5204 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5205 return R;
5206
5207 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005208 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005209 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5210 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5211 const Type *SrcTy = Op0C->getOperand(0)->getType();
5212 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5213 // Only do this if the casts both really cause code to be generated.
5214 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5215 I.getType(), TD) &&
5216 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5217 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00005218 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005219 Op1C->getOperand(0),
5220 I.getName());
5221 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005222 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005223 }
5224 }
Chris Lattner91882432007-10-24 05:38:08 +00005225 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005226
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005227 return Changed ? &I : 0;
5228}
5229
Dan Gohman8fd520a2009-06-15 22:12:54 +00005230static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
5231 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5232}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005233
Dan Gohman8fd520a2009-06-15 22:12:54 +00005234static bool HasAddOverflow(ConstantInt *Result,
5235 ConstantInt *In1, ConstantInt *In2,
5236 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005237 if (IsSigned)
5238 if (In2->getValue().isNegative())
5239 return Result->getValue().sgt(In1->getValue());
5240 else
5241 return Result->getValue().slt(In1->getValue());
5242 else
5243 return Result->getValue().ult(In1->getValue());
5244}
5245
Dan Gohman8fd520a2009-06-15 22:12:54 +00005246/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005247/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005248static bool AddWithOverflow(Constant *&Result, Constant *In1,
5249 Constant *In2, bool IsSigned = false) {
5250 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005251
Dan Gohman8fd520a2009-06-15 22:12:54 +00005252 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5253 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5254 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5255 if (HasAddOverflow(ExtractElement(Result, Idx),
5256 ExtractElement(In1, Idx),
5257 ExtractElement(In2, Idx),
5258 IsSigned))
5259 return true;
5260 }
5261 return false;
5262 }
5263
5264 return HasAddOverflow(cast<ConstantInt>(Result),
5265 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5266 IsSigned);
5267}
5268
5269static bool HasSubOverflow(ConstantInt *Result,
5270 ConstantInt *In1, ConstantInt *In2,
5271 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005272 if (IsSigned)
5273 if (In2->getValue().isNegative())
5274 return Result->getValue().slt(In1->getValue());
5275 else
5276 return Result->getValue().sgt(In1->getValue());
5277 else
5278 return Result->getValue().ugt(In1->getValue());
5279}
5280
Dan Gohman8fd520a2009-06-15 22:12:54 +00005281/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5282/// overflowed for this type.
5283static bool SubWithOverflow(Constant *&Result, Constant *In1,
5284 Constant *In2, bool IsSigned = false) {
5285 Result = ConstantExpr::getSub(In1, In2);
5286
5287 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5288 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5289 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5290 if (HasSubOverflow(ExtractElement(Result, Idx),
5291 ExtractElement(In1, Idx),
5292 ExtractElement(In2, Idx),
5293 IsSigned))
5294 return true;
5295 }
5296 return false;
5297 }
5298
5299 return HasSubOverflow(cast<ConstantInt>(Result),
5300 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5301 IsSigned);
5302}
5303
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005304/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5305/// code necessary to compute the offset from the base pointer (without adding
5306/// in the base pointer). Return the result as a signed integer of intptr size.
5307static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5308 TargetData &TD = IC.getTargetData();
5309 gep_type_iterator GTI = gep_type_begin(GEP);
5310 const Type *IntPtrTy = TD.getIntPtrType();
5311 Value *Result = Constant::getNullValue(IntPtrTy);
5312
5313 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005314 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005315 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5316
Gabor Greif17396002008-06-12 21:37:33 +00005317 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5318 ++i, ++GTI) {
5319 Value *Op = *i;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005320 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005321 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5322 if (OpC->isZero()) continue;
5323
5324 // Handle a struct index, which adds its field offset to the pointer.
5325 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5326 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5327
5328 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5329 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5330 else
5331 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005332 BinaryOperator::CreateAdd(Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005333 ConstantInt::get(IntPtrTy, Size),
5334 GEP->getName()+".offs"), I);
5335 continue;
5336 }
5337
5338 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5339 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5340 Scale = ConstantExpr::getMul(OC, Scale);
5341 if (Constant *RC = dyn_cast<Constant>(Result))
5342 Result = ConstantExpr::getAdd(RC, Scale);
5343 else {
5344 // Emit an add instruction.
5345 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005346 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005347 GEP->getName()+".offs"), I);
5348 }
5349 continue;
5350 }
5351 // Convert to correct type.
5352 if (Op->getType() != IntPtrTy) {
5353 if (Constant *OpC = dyn_cast<Constant>(Op))
Chris Lattner2941a652009-04-07 05:03:34 +00005354 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005355 else
Chris Lattner2941a652009-04-07 05:03:34 +00005356 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5357 true,
5358 Op->getName()+".c"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005359 }
5360 if (Size != 1) {
5361 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5362 if (Constant *OpC = dyn_cast<Constant>(Op))
5363 Op = ConstantExpr::getMul(OpC, Scale);
5364 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00005365 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005366 GEP->getName()+".idx"), I);
5367 }
5368
5369 // Emit an add instruction.
5370 if (isa<Constant>(Op) && isa<Constant>(Result))
5371 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5372 cast<Constant>(Result));
5373 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005374 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005375 GEP->getName()+".offs"), I);
5376 }
5377 return Result;
5378}
5379
Chris Lattnereba75862008-04-22 02:53:33 +00005380
5381/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5382/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5383/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5384/// complex, and scales are involved. The above expression would also be legal
5385/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5386/// later form is less amenable to optimization though, and we are allowed to
5387/// generate the first by knowing that pointer arithmetic doesn't overflow.
5388///
5389/// If we can't emit an optimized form for this expression, this returns null.
5390///
5391static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5392 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00005393 TargetData &TD = IC.getTargetData();
5394 gep_type_iterator GTI = gep_type_begin(GEP);
5395
5396 // Check to see if this gep only has a single variable index. If so, and if
5397 // any constant indices are a multiple of its scale, then we can compute this
5398 // in terms of the scale of the variable index. For example, if the GEP
5399 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5400 // because the expression will cross zero at the same point.
5401 unsigned i, e = GEP->getNumOperands();
5402 int64_t Offset = 0;
5403 for (i = 1; i != e; ++i, ++GTI) {
5404 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5405 // Compute the aggregate offset of constant indices.
5406 if (CI->isZero()) continue;
5407
5408 // Handle a struct index, which adds its field offset to the pointer.
5409 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5410 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5411 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005412 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005413 Offset += Size*CI->getSExtValue();
5414 }
5415 } else {
5416 // Found our variable index.
5417 break;
5418 }
5419 }
5420
5421 // If there are no variable indices, we must have a constant offset, just
5422 // evaluate it the general way.
5423 if (i == e) return 0;
5424
5425 Value *VariableIdx = GEP->getOperand(i);
5426 // Determine the scale factor of the variable element. For example, this is
5427 // 4 if the variable index is into an array of i32.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005428 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005429
5430 // Verify that there are no other variable indices. If so, emit the hard way.
5431 for (++i, ++GTI; i != e; ++i, ++GTI) {
5432 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5433 if (!CI) return 0;
5434
5435 // Compute the aggregate offset of constant indices.
5436 if (CI->isZero()) continue;
5437
5438 // Handle a struct index, which adds its field offset to the pointer.
5439 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5440 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5441 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005442 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005443 Offset += Size*CI->getSExtValue();
5444 }
5445 }
5446
5447 // Okay, we know we have a single variable index, which must be a
5448 // pointer/array/vector index. If there is no offset, life is simple, return
5449 // the index.
5450 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5451 if (Offset == 0) {
5452 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5453 // we don't need to bother extending: the extension won't affect where the
5454 // computation crosses zero.
5455 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5456 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5457 VariableIdx->getNameStart(), &I);
5458 return VariableIdx;
5459 }
5460
5461 // Otherwise, there is an index. The computation we will do will be modulo
5462 // the pointer size, so get it.
5463 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5464
5465 Offset &= PtrSizeMask;
5466 VariableScale &= PtrSizeMask;
5467
5468 // To do this transformation, any constant index must be a multiple of the
5469 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5470 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5471 // multiple of the variable scale.
5472 int64_t NewOffs = Offset / (int64_t)VariableScale;
5473 if (Offset != NewOffs*(int64_t)VariableScale)
5474 return 0;
5475
5476 // Okay, we can do this evaluation. Start by converting the index to intptr.
5477 const Type *IntPtrTy = TD.getIntPtrType();
5478 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005479 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005480 true /*SExt*/,
5481 VariableIdx->getNameStart(), &I);
5482 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005483 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005484}
5485
5486
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005487/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5488/// else. At this point we know that the GEP is on the LHS of the comparison.
5489Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5490 ICmpInst::Predicate Cond,
5491 Instruction &I) {
5492 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5493
Chris Lattnereba75862008-04-22 02:53:33 +00005494 // Look through bitcasts.
5495 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5496 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005497
5498 Value *PtrBase = GEPLHS->getOperand(0);
5499 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005500 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005501 // This transformation (ignoring the base and scales) is valid because we
5502 // know pointers can't overflow. See if we can output an optimized form.
5503 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5504
5505 // If not, synthesize the offset the hard way.
5506 if (Offset == 0)
5507 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattneraf97d022008-02-05 04:45:32 +00005508 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5509 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005510 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5511 // If the base pointers are different, but the indices are the same, just
5512 // compare the base pointer.
5513 if (PtrBase != GEPRHS->getOperand(0)) {
5514 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5515 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5516 GEPRHS->getOperand(0)->getType();
5517 if (IndicesTheSame)
5518 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5519 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5520 IndicesTheSame = false;
5521 break;
5522 }
5523
5524 // If all indices are the same, just compare the base pointers.
5525 if (IndicesTheSame)
5526 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5527 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5528
5529 // Otherwise, the base pointers are different and the indices are
5530 // different, bail out.
5531 return 0;
5532 }
5533
5534 // If one of the GEPs has all zero indices, recurse.
5535 bool AllZeros = true;
5536 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5537 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5538 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5539 AllZeros = false;
5540 break;
5541 }
5542 if (AllZeros)
5543 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5544 ICmpInst::getSwappedPredicate(Cond), I);
5545
5546 // If the other GEP has all zero indices, recurse.
5547 AllZeros = true;
5548 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5549 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5550 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5551 AllZeros = false;
5552 break;
5553 }
5554 if (AllZeros)
5555 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5556
5557 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5558 // If the GEPs only differ by one index, compare it.
5559 unsigned NumDifferences = 0; // Keep track of # differences.
5560 unsigned DiffOperand = 0; // The operand that differs.
5561 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5562 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5563 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5564 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5565 // Irreconcilable differences.
5566 NumDifferences = 2;
5567 break;
5568 } else {
5569 if (NumDifferences++) break;
5570 DiffOperand = i;
5571 }
5572 }
5573
5574 if (NumDifferences == 0) // SAME GEP?
5575 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00005576 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005577 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005578
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005579 else if (NumDifferences == 1) {
5580 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5581 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5582 // Make sure we do a signed comparison here.
5583 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5584 }
5585 }
5586
5587 // Only lower this if the icmp is the only user of the GEP or if we expect
5588 // the result to fold to a constant!
5589 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5590 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5591 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5592 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5593 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5594 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5595 }
5596 }
5597 return 0;
5598}
5599
Chris Lattnere6b62d92008-05-19 20:18:56 +00005600/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5601///
5602Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5603 Instruction *LHSI,
5604 Constant *RHSC) {
5605 if (!isa<ConstantFP>(RHSC)) return 0;
5606 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5607
5608 // Get the width of the mantissa. We don't want to hack on conversions that
5609 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005610 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005611 if (MantissaWidth == -1) return 0; // Unknown.
5612
5613 // Check to see that the input is converted from an integer type that is small
5614 // enough that preserves all bits. TODO: check here for "known" sign bits.
5615 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005616 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005617
5618 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005619 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5620 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005621 ++InputSize;
5622
5623 // If the conversion would lose info, don't hack on this.
5624 if ((int)InputSize > MantissaWidth)
5625 return 0;
5626
5627 // Otherwise, we can potentially simplify the comparison. We know that it
5628 // will always come through as an integer value and we know the constant is
5629 // not a NAN (it would have been previously simplified).
5630 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5631
5632 ICmpInst::Predicate Pred;
5633 switch (I.getPredicate()) {
5634 default: assert(0 && "Unexpected predicate!");
5635 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005636 case FCmpInst::FCMP_OEQ:
5637 Pred = ICmpInst::ICMP_EQ;
5638 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005639 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005640 case FCmpInst::FCMP_OGT:
5641 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5642 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005643 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005644 case FCmpInst::FCMP_OGE:
5645 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5646 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005647 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005648 case FCmpInst::FCMP_OLT:
5649 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5650 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005651 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005652 case FCmpInst::FCMP_OLE:
5653 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5654 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005655 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005656 case FCmpInst::FCMP_ONE:
5657 Pred = ICmpInst::ICMP_NE;
5658 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005659 case FCmpInst::FCMP_ORD:
Eli Friedmanc9c96242008-11-30 22:48:49 +00005660 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005661 case FCmpInst::FCMP_UNO:
Eli Friedmanc9c96242008-11-30 22:48:49 +00005662 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005663 }
5664
5665 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5666
5667 // Now we know that the APFloat is a normal number, zero or inf.
5668
Chris Lattnerf13ff492008-05-20 03:50:52 +00005669 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005670 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005671 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005672
Bill Wendling20636df2008-11-09 04:26:50 +00005673 if (!LHSUnsigned) {
5674 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5675 // and large values.
5676 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5677 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5678 APFloat::rmNearestTiesToEven);
5679 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5680 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5681 Pred == ICmpInst::ICMP_SLE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005682 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5683 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005684 }
5685 } else {
5686 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5687 // +INF and large values.
5688 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5689 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5690 APFloat::rmNearestTiesToEven);
5691 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5692 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5693 Pred == ICmpInst::ICMP_ULE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005694 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5695 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005696 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005697 }
5698
Bill Wendling20636df2008-11-09 04:26:50 +00005699 if (!LHSUnsigned) {
5700 // See if the RHS value is < SignedMin.
5701 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5702 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5703 APFloat::rmNearestTiesToEven);
5704 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5705 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5706 Pred == ICmpInst::ICMP_SGE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005707 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5708 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005709 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005710 }
5711
Bill Wendling20636df2008-11-09 04:26:50 +00005712 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5713 // [0, UMAX], but it may still be fractional. See if it is fractional by
5714 // casting the FP value to the integer value and back, checking for equality.
5715 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005716 Constant *RHSInt = LHSUnsigned
5717 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5718 : ConstantExpr::getFPToSI(RHSC, IntTy);
5719 if (!RHS.isZero()) {
5720 bool Equal = LHSUnsigned
5721 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5722 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5723 if (!Equal) {
5724 // If we had a comparison against a fractional value, we have to adjust
5725 // the compare predicate and sometimes the value. RHSC is rounded towards
5726 // zero at this point.
5727 switch (Pred) {
5728 default: assert(0 && "Unexpected integer comparison!");
5729 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedmanc9c96242008-11-30 22:48:49 +00005730 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Evan Cheng14118132009-05-22 23:10:53 +00005731 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5732 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5733 case ICmpInst::ICMP_ULE:
5734 // (float)int <= 4.4 --> int <= 4
5735 // (float)int <= -4.4 --> false
5736 if (RHS.isNegative())
5737 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5738 break;
5739 case ICmpInst::ICMP_SLE:
5740 // (float)int <= 4.4 --> int <= 4
5741 // (float)int <= -4.4 --> int < -4
5742 if (RHS.isNegative())
5743 Pred = ICmpInst::ICMP_SLT;
5744 break;
5745 case ICmpInst::ICMP_ULT:
5746 // (float)int < -4.4 --> false
5747 // (float)int < 4.4 --> int <= 4
5748 if (RHS.isNegative())
5749 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5750 Pred = ICmpInst::ICMP_ULE;
5751 break;
5752 case ICmpInst::ICMP_SLT:
5753 // (float)int < -4.4 --> int < -4
5754 // (float)int < 4.4 --> int <= 4
5755 if (!RHS.isNegative())
5756 Pred = ICmpInst::ICMP_SLE;
5757 break;
5758 case ICmpInst::ICMP_UGT:
5759 // (float)int > 4.4 --> int > 4
5760 // (float)int > -4.4 --> true
5761 if (RHS.isNegative())
5762 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5763 break;
5764 case ICmpInst::ICMP_SGT:
5765 // (float)int > 4.4 --> int > 4
5766 // (float)int > -4.4 --> int >= -4
5767 if (RHS.isNegative())
5768 Pred = ICmpInst::ICMP_SGE;
5769 break;
5770 case ICmpInst::ICMP_UGE:
5771 // (float)int >= -4.4 --> true
5772 // (float)int >= 4.4 --> int > 4
5773 if (!RHS.isNegative())
5774 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5775 Pred = ICmpInst::ICMP_UGT;
5776 break;
5777 case ICmpInst::ICMP_SGE:
5778 // (float)int >= -4.4 --> int >= -4
5779 // (float)int >= 4.4 --> int > 4
5780 if (!RHS.isNegative())
5781 Pred = ICmpInst::ICMP_SGT;
5782 break;
5783 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005784 }
5785 }
5786
5787 // Lower this FP comparison into an appropriate integer version of the
5788 // comparison.
5789 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5790}
5791
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005792Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5793 bool Changed = SimplifyCompare(I);
5794 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5795
5796 // Fold trivial predicates.
5797 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005798 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005799 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005800 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005801
5802 // Simplify 'fcmp pred X, X'
5803 if (Op0 == Op1) {
5804 switch (I.getPredicate()) {
5805 default: assert(0 && "Unknown predicate!");
5806 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5807 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5808 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedmanc9c96242008-11-30 22:48:49 +00005809 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005810 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5811 case FCmpInst::FCMP_OLT: // True if ordered and less than
5812 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedmanc9c96242008-11-30 22:48:49 +00005813 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005814
5815 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5816 case FCmpInst::FCMP_ULT: // True if unordered or less than
5817 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5818 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5819 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5820 I.setPredicate(FCmpInst::FCMP_UNO);
5821 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5822 return &I;
5823
5824 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5825 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5826 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5827 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5828 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5829 I.setPredicate(FCmpInst::FCMP_ORD);
5830 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5831 return &I;
5832 }
5833 }
5834
5835 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5836 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5837
5838 // Handle fcmp with constant RHS
5839 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005840 // If the constant is a nan, see if we can fold the comparison based on it.
5841 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5842 if (CFP->getValueAPF().isNaN()) {
5843 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedmanc9c96242008-11-30 22:48:49 +00005844 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnerf13ff492008-05-20 03:50:52 +00005845 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5846 "Comparison must be either ordered or unordered!");
5847 // True if unordered.
Eli Friedmanc9c96242008-11-30 22:48:49 +00005848 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005849 }
5850 }
5851
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005852 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5853 switch (LHSI->getOpcode()) {
5854 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005855 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5856 // block. If in the same block, we're encouraging jump threading. If
5857 // not, we are just pessimizing the code by making an i1 phi.
5858 if (LHSI->getParent() == I.getParent())
5859 if (Instruction *NV = FoldOpIntoPhi(I))
5860 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005861 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005862 case Instruction::SIToFP:
5863 case Instruction::UIToFP:
5864 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5865 return NV;
5866 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005867 case Instruction::Select:
5868 // If either operand of the select is a constant, we can fold the
5869 // comparison into the select arms, which will cause one to be
5870 // constant folded and the select turned into a bitwise or.
5871 Value *Op1 = 0, *Op2 = 0;
5872 if (LHSI->hasOneUse()) {
5873 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5874 // Fold the known value into the constant operand.
5875 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5876 // Insert a new FCmp of the other select operand.
5877 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5878 LHSI->getOperand(2), RHSC,
5879 I.getName()), I);
5880 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5881 // Fold the known value into the constant operand.
5882 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5883 // Insert a new FCmp of the other select operand.
5884 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5885 LHSI->getOperand(1), RHSC,
5886 I.getName()), I);
5887 }
5888 }
5889
5890 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005891 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005892 break;
5893 }
5894 }
5895
5896 return Changed ? &I : 0;
5897}
5898
5899Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5900 bool Changed = SimplifyCompare(I);
5901 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5902 const Type *Ty = Op0->getType();
5903
5904 // icmp X, X
5905 if (Op0 == Op1)
5906 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005907 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005908
5909 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5910 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005911
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005912 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5913 // addresses never equal each other! We already know that Op0 != Op1.
5914 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5915 isa<ConstantPointerNull>(Op0)) &&
5916 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5917 isa<ConstantPointerNull>(Op1)))
5918 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005919 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005920
5921 // icmp's with boolean values can always be turned into bitwise operations
5922 if (Ty == Type::Int1Ty) {
5923 switch (I.getPredicate()) {
5924 default: assert(0 && "Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00005925 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005926 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005927 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005928 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005929 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005930 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005931 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005932
5933 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00005934 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005935 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005936 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greifa645dd32008-05-16 19:29:10 +00005937 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005938 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005939 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005940 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005941 case ICmpInst::ICMP_SGT:
5942 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005943 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005944 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5945 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5946 InsertNewInstBefore(Not, I);
5947 return BinaryOperator::CreateAnd(Not, Op0);
5948 }
5949 case ICmpInst::ICMP_UGE:
5950 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5951 // FALL THROUGH
5952 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00005953 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005954 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005955 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005956 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005957 case ICmpInst::ICMP_SGE:
5958 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5959 // FALL THROUGH
5960 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5961 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5962 InsertNewInstBefore(Not, I);
5963 return BinaryOperator::CreateOr(Not, Op0);
5964 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005965 }
5966 }
5967
Dan Gohman7934d592009-04-25 17:12:48 +00005968 unsigned BitWidth = 0;
5969 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00005970 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5971 else if (Ty->isIntOrIntVector())
5972 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00005973
5974 bool isSignBit = false;
5975
Dan Gohman58c09632008-09-16 18:46:06 +00005976 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005977 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00005978 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00005979
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005980 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5981 if (I.isEquality() && CI->isNullValue() &&
5982 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5983 // (icmp cond A B) if cond is equality
5984 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005985 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005986
Dan Gohman58c09632008-09-16 18:46:06 +00005987 // If we have an icmp le or icmp ge instruction, turn it into the
5988 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5989 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00005990 switch (I.getPredicate()) {
5991 default: break;
5992 case ICmpInst::ICMP_ULE:
5993 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5994 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5995 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5996 case ICmpInst::ICMP_SLE:
5997 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5998 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5999 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
6000 case ICmpInst::ICMP_UGE:
6001 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
6002 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6003 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
6004 case ICmpInst::ICMP_SGE:
6005 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
6006 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6007 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
6008 }
6009
Chris Lattnera1308652008-07-11 05:40:05 +00006010 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006011 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006012 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006013 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6014 }
6015
6016 // See if we can fold the comparison based on range information we can get
6017 // by checking whether bits are known to be zero or one in the input.
6018 if (BitWidth != 0) {
6019 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6020 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6021
6022 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006023 isSignBit ? APInt::getSignBit(BitWidth)
6024 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006025 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006026 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006027 if (SimplifyDemandedBits(I.getOperandUse(1),
6028 APInt::getAllOnesValue(BitWidth),
6029 Op1KnownZero, Op1KnownOne, 0))
6030 return &I;
6031
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006032 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006033 // in. Compute the Min, Max and RHS values based on the known bits. For the
6034 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006035 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6036 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6037 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6038 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6039 Op0Min, Op0Max);
6040 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6041 Op1Min, Op1Max);
6042 } else {
6043 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6044 Op0Min, Op0Max);
6045 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6046 Op1Min, Op1Max);
6047 }
6048
Chris Lattnera1308652008-07-11 05:40:05 +00006049 // If Min and Max are known to be the same, then SimplifyDemandedBits
6050 // figured out that the LHS is a constant. Just constant fold this now so
6051 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006052 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6053 return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
6054 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6055 return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
6056
Chris Lattnera1308652008-07-11 05:40:05 +00006057 // Based on the range information we know about the LHS, see if we can
6058 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006059 switch (I.getPredicate()) {
Chris Lattner62d0f232008-07-11 05:08:55 +00006060 default: assert(0 && "Unknown icmp opcode!");
6061 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006062 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner62d0f232008-07-11 05:08:55 +00006063 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6064 break;
6065 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006066 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner62d0f232008-07-11 05:08:55 +00006067 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6068 break;
6069 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006070 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Chris Lattner62d0f232008-07-11 05:08:55 +00006071 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006072 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Chris Lattner62d0f232008-07-11 05:08:55 +00006073 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006074 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Chris Lattnera1308652008-07-11 05:40:05 +00006075 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006076 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6077 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6078 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6079
6080 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6081 if (CI->isMinValue(true))
6082 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Chris Lattnera1308652008-07-11 05:40:05 +00006083 ConstantInt::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006084 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006085 break;
6086 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006087 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Chris Lattner62d0f232008-07-11 05:08:55 +00006088 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006089 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Chris Lattner62d0f232008-07-11 05:08:55 +00006090 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006091
6092 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Chris Lattnera1308652008-07-11 05:40:05 +00006093 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006094 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6095 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6096 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6097
6098 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6099 if (CI->isMaxValue(true))
6100 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6101 ConstantInt::getNullValue(Op0->getType()));
6102 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006103 break;
6104 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006105 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Chris Lattner62d0f232008-07-11 05:08:55 +00006106 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006107 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Chris Lattner62d0f232008-07-11 05:08:55 +00006108 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006109 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Chris Lattnera1308652008-07-11 05:40:05 +00006110 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006111 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6112 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6113 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6114 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006115 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006116 case ICmpInst::ICMP_SGT:
6117 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Chris Lattner62d0f232008-07-11 05:08:55 +00006118 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006119 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Chris Lattner62d0f232008-07-11 05:08:55 +00006120 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006121
6122 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Chris Lattnera1308652008-07-11 05:40:05 +00006123 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006124 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6125 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6126 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6127 }
6128 break;
6129 case ICmpInst::ICMP_SGE:
6130 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6131 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6132 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6133 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6134 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6135 break;
6136 case ICmpInst::ICMP_SLE:
6137 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6138 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6139 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6140 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6141 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6142 break;
6143 case ICmpInst::ICMP_UGE:
6144 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6145 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6146 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6147 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6148 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6149 break;
6150 case ICmpInst::ICMP_ULE:
6151 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6152 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6153 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6154 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6155 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner62d0f232008-07-11 05:08:55 +00006156 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006157 }
Dan Gohman7934d592009-04-25 17:12:48 +00006158
6159 // Turn a signed comparison into an unsigned one if both operands
6160 // are known to have the same sign.
6161 if (I.isSignedPredicate() &&
6162 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6163 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6164 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006165 }
6166
6167 // Test if the ICmpInst instruction is used exclusively by a select as
6168 // part of a minimum or maximum operation. If so, refrain from doing
6169 // any other folding. This helps out other analyses which understand
6170 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6171 // and CodeGen. And in this case, at least one of the comparison
6172 // operands has at least one user besides the compare (the select),
6173 // which would often largely negate the benefit of folding anyway.
6174 if (I.hasOneUse())
6175 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6176 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6177 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6178 return 0;
6179
6180 // See if we are doing a comparison between a constant and an instruction that
6181 // can be folded into the comparison.
6182 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006183 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6184 // instruction, see if that instruction also has constants so that the
6185 // instruction can be folded into the icmp
6186 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6187 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6188 return Res;
6189 }
6190
6191 // Handle icmp with constant (but not simple integer constant) RHS
6192 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6193 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6194 switch (LHSI->getOpcode()) {
6195 case Instruction::GetElementPtr:
6196 if (RHSC->isNullValue()) {
6197 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6198 bool isAllZeros = true;
6199 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6200 if (!isa<Constant>(LHSI->getOperand(i)) ||
6201 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6202 isAllZeros = false;
6203 break;
6204 }
6205 if (isAllZeros)
6206 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6207 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6208 }
6209 break;
6210
6211 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00006212 // Only fold icmp into the PHI if the phi and fcmp are in the same
6213 // block. If in the same block, we're encouraging jump threading. If
6214 // not, we are just pessimizing the code by making an i1 phi.
6215 if (LHSI->getParent() == I.getParent())
6216 if (Instruction *NV = FoldOpIntoPhi(I))
6217 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006218 break;
6219 case Instruction::Select: {
6220 // If either operand of the select is a constant, we can fold the
6221 // comparison into the select arms, which will cause one to be
6222 // constant folded and the select turned into a bitwise or.
6223 Value *Op1 = 0, *Op2 = 0;
6224 if (LHSI->hasOneUse()) {
6225 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6226 // Fold the known value into the constant operand.
6227 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6228 // Insert a new ICmp of the other select operand.
6229 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6230 LHSI->getOperand(2), RHSC,
6231 I.getName()), I);
6232 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6233 // Fold the known value into the constant operand.
6234 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6235 // Insert a new ICmp of the other select operand.
6236 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6237 LHSI->getOperand(1), RHSC,
6238 I.getName()), I);
6239 }
6240 }
6241
6242 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006243 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006244 break;
6245 }
6246 case Instruction::Malloc:
6247 // If we have (malloc != null), and if the malloc has a single use, we
6248 // can assume it is successful and remove the malloc.
6249 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6250 AddToWorkList(LHSI);
6251 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00006252 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006253 }
6254 break;
6255 }
6256 }
6257
6258 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6259 if (User *GEP = dyn_castGetElementPtr(Op0))
6260 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6261 return NI;
6262 if (User *GEP = dyn_castGetElementPtr(Op1))
6263 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6264 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6265 return NI;
6266
6267 // Test to see if the operands of the icmp are casted versions of other
6268 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6269 // now.
6270 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6271 if (isa<PointerType>(Op0->getType()) &&
6272 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6273 // We keep moving the cast from the left operand over to the right
6274 // operand, where it can often be eliminated completely.
6275 Op0 = CI->getOperand(0);
6276
6277 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6278 // so eliminate it as well.
6279 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6280 Op1 = CI2->getOperand(0);
6281
6282 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006283 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006284 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6285 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6286 } else {
6287 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006288 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006289 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006290 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006291 return new ICmpInst(I.getPredicate(), Op0, Op1);
6292 }
6293 }
6294
6295 if (isa<CastInst>(Op0)) {
6296 // Handle the special case of: icmp (cast bool to X), <cst>
6297 // This comes up when you have code like
6298 // int X = A < B;
6299 // if (X) ...
6300 // For generality, we handle any zero-extension of any operand comparison
6301 // with a constant or another cast from the same type.
6302 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6303 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6304 return R;
6305 }
6306
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006307 // See if it's the same type of instruction on the left and right.
6308 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6309 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006310 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006311 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006312 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006313 default: break;
6314 case Instruction::Add:
6315 case Instruction::Sub:
6316 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006317 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Nick Lewyckydac84332009-01-31 21:30:05 +00006318 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6319 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006320 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6321 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6322 if (CI->getValue().isSignBit()) {
6323 ICmpInst::Predicate Pred = I.isSignedPredicate()
6324 ? I.getUnsignedPredicate()
6325 : I.getSignedPredicate();
6326 return new ICmpInst(Pred, Op0I->getOperand(0),
6327 Op1I->getOperand(0));
6328 }
6329
6330 if (CI->getValue().isMaxSignedValue()) {
6331 ICmpInst::Predicate Pred = I.isSignedPredicate()
6332 ? I.getUnsignedPredicate()
6333 : I.getSignedPredicate();
6334 Pred = I.getSwappedPredicate(Pred);
6335 return new ICmpInst(Pred, Op0I->getOperand(0),
6336 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006337 }
6338 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006339 break;
6340 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006341 if (!I.isEquality())
6342 break;
6343
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006344 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6345 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6346 // Mask = -1 >> count-trailing-zeros(Cst).
6347 if (!CI->isZero() && !CI->isOne()) {
6348 const APInt &AP = CI->getValue();
6349 ConstantInt *Mask = ConstantInt::get(
6350 APInt::getLowBitsSet(AP.getBitWidth(),
6351 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006352 AP.countTrailingZeros()));
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006353 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6354 Mask);
6355 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6356 Mask);
6357 InsertNewInstBefore(And1, I);
6358 InsertNewInstBefore(And2, I);
6359 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006360 }
6361 }
6362 break;
6363 }
6364 }
6365 }
6366 }
6367
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006368 // ~x < ~y --> y < x
6369 { Value *A, *B;
6370 if (match(Op0, m_Not(m_Value(A))) &&
6371 match(Op1, m_Not(m_Value(B))))
6372 return new ICmpInst(I.getPredicate(), B, A);
6373 }
6374
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006375 if (I.isEquality()) {
6376 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006377
6378 // -x == -y --> x == y
6379 if (match(Op0, m_Neg(m_Value(A))) &&
6380 match(Op1, m_Neg(m_Value(B))))
6381 return new ICmpInst(I.getPredicate(), A, B);
6382
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006383 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6384 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6385 Value *OtherVal = A == Op1 ? B : A;
6386 return new ICmpInst(I.getPredicate(), OtherVal,
6387 Constant::getNullValue(A->getType()));
6388 }
6389
6390 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6391 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006392 ConstantInt *C1, *C2;
6393 if (match(B, m_ConstantInt(C1)) &&
6394 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6395 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6396 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6397 return new ICmpInst(I.getPredicate(), A,
6398 InsertNewInstBefore(Xor, I));
6399 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006400
6401 // A^B == A^D -> B == D
6402 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6403 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6404 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6405 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6406 }
6407 }
6408
6409 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6410 (A == Op0 || B == Op0)) {
6411 // A == (A^B) -> B == 0
6412 Value *OtherVal = A == Op0 ? B : A;
6413 return new ICmpInst(I.getPredicate(), OtherVal,
6414 Constant::getNullValue(A->getType()));
6415 }
Chris Lattner3b874082008-11-16 05:38:51 +00006416
6417 // (A-B) == A -> B == 0
6418 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6419 return new ICmpInst(I.getPredicate(), B,
6420 Constant::getNullValue(B->getType()));
6421
6422 // A == (A-B) -> B == 0
6423 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006424 return new ICmpInst(I.getPredicate(), B,
6425 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006426
6427 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6428 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6429 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6430 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6431 Value *X = 0, *Y = 0, *Z = 0;
6432
6433 if (A == C) {
6434 X = B; Y = D; Z = A;
6435 } else if (A == D) {
6436 X = B; Y = C; Z = A;
6437 } else if (B == C) {
6438 X = A; Y = D; Z = B;
6439 } else if (B == D) {
6440 X = A; Y = C; Z = B;
6441 }
6442
6443 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00006444 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6445 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006446 I.setOperand(0, Op1);
6447 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6448 return &I;
6449 }
6450 }
6451 }
6452 return Changed ? &I : 0;
6453}
6454
6455
6456/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6457/// and CmpRHS are both known to be integer constants.
6458Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6459 ConstantInt *DivRHS) {
6460 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6461 const APInt &CmpRHSV = CmpRHS->getValue();
6462
6463 // FIXME: If the operand types don't match the type of the divide
6464 // then don't attempt this transform. The code below doesn't have the
6465 // logic to deal with a signed divide and an unsigned compare (and
6466 // vice versa). This is because (x /s C1) <s C2 produces different
6467 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6468 // (x /u C1) <u C2. Simply casting the operands and result won't
6469 // work. :( The if statement below tests that condition and bails
6470 // if it finds it.
6471 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6472 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6473 return 0;
6474 if (DivRHS->isZero())
6475 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006476 if (DivIsSigned && DivRHS->isAllOnesValue())
6477 return 0; // The overflow computation also screws up here
6478 if (DivRHS->isOne())
6479 return 0; // Not worth bothering, and eliminates some funny cases
6480 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006481
6482 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6483 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6484 // C2 (CI). By solving for X we can turn this into a range check
6485 // instead of computing a divide.
Dan Gohman8fd520a2009-06-15 22:12:54 +00006486 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006487
6488 // Determine if the product overflows by seeing if the product is
6489 // not equal to the divide. Make sure we do the same kind of divide
6490 // as in the LHS instruction that we're folding.
6491 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6492 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6493
6494 // Get the ICmp opcode
6495 ICmpInst::Predicate Pred = ICI.getPredicate();
6496
6497 // Figure out the interval that is being checked. For example, a comparison
6498 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6499 // Compute this interval based on the constants involved and the signedness of
6500 // the compare/divide. This computes a half-open interval, keeping track of
6501 // whether either value in the interval overflows. After analysis each
6502 // overflow variable is set to 0 if it's corresponding bound variable is valid
6503 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6504 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006505 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006506
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006507 if (!DivIsSigned) { // udiv
6508 // e.g. X/5 op 3 --> [15, 20)
6509 LoBound = Prod;
6510 HiOverflow = LoOverflow = ProdOV;
6511 if (!HiOverflow)
6512 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006513 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006514 if (CmpRHSV == 0) { // (X / pos) op 0
6515 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6516 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6517 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006518 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006519 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6520 HiOverflow = LoOverflow = ProdOV;
6521 if (!HiOverflow)
6522 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6523 } else { // (X / pos) op neg
6524 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006525 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006526 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6527 if (!LoOverflow) {
6528 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6529 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6530 true) ? -1 : 0;
6531 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006532 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006533 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006534 if (CmpRHSV == 0) { // (X / neg) op 0
6535 // e.g. X/-5 op 0 --> [-4, 5)
6536 LoBound = AddOne(DivRHS);
6537 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6538 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6539 HiOverflow = 1; // [INTMIN+1, overflow)
6540 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6541 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006542 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006543 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006544 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006545 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6546 if (!LoOverflow)
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006547 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006548 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006549 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6550 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006551 if (!HiOverflow)
6552 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006553 }
6554
6555 // Dividing by a negative swaps the condition. LT <-> GT
6556 Pred = ICmpInst::getSwappedPredicate(Pred);
6557 }
6558
6559 Value *X = DivI->getOperand(0);
6560 switch (Pred) {
6561 default: assert(0 && "Unhandled icmp opcode!");
6562 case ICmpInst::ICMP_EQ:
6563 if (LoOverflow && HiOverflow)
6564 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6565 else if (HiOverflow)
6566 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6567 ICmpInst::ICMP_UGE, X, LoBound);
6568 else if (LoOverflow)
6569 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6570 ICmpInst::ICMP_ULT, X, HiBound);
6571 else
6572 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6573 case ICmpInst::ICMP_NE:
6574 if (LoOverflow && HiOverflow)
6575 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6576 else if (HiOverflow)
6577 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6578 ICmpInst::ICMP_ULT, X, LoBound);
6579 else if (LoOverflow)
6580 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6581 ICmpInst::ICMP_UGE, X, HiBound);
6582 else
6583 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6584 case ICmpInst::ICMP_ULT:
6585 case ICmpInst::ICMP_SLT:
6586 if (LoOverflow == +1) // Low bound is greater than input range.
6587 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6588 if (LoOverflow == -1) // Low bound is less than input range.
6589 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6590 return new ICmpInst(Pred, X, LoBound);
6591 case ICmpInst::ICMP_UGT:
6592 case ICmpInst::ICMP_SGT:
6593 if (HiOverflow == +1) // High bound greater than input range.
6594 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6595 else if (HiOverflow == -1) // High bound less than input range.
6596 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6597 if (Pred == ICmpInst::ICMP_UGT)
6598 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6599 else
6600 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6601 }
6602}
6603
6604
6605/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6606///
6607Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6608 Instruction *LHSI,
6609 ConstantInt *RHS) {
6610 const APInt &RHSV = RHS->getValue();
6611
6612 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006613 case Instruction::Trunc:
6614 if (ICI.isEquality() && LHSI->hasOneUse()) {
6615 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6616 // of the high bits truncated out of x are known.
6617 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6618 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6619 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6620 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6621 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6622
6623 // If all the high bits are known, we can do this xform.
6624 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6625 // Pull in the high bits from known-ones set.
6626 APInt NewRHS(RHS->getValue());
6627 NewRHS.zext(SrcBits);
6628 NewRHS |= KnownOne;
6629 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6630 ConstantInt::get(NewRHS));
6631 }
6632 }
6633 break;
6634
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006635 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6636 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6637 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6638 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006639 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6640 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006641 Value *CompareVal = LHSI->getOperand(0);
6642
6643 // If the sign bit of the XorCST is not set, there is no change to
6644 // the operation, just stop using the Xor.
6645 if (!XorCST->getValue().isNegative()) {
6646 ICI.setOperand(0, CompareVal);
6647 AddToWorkList(LHSI);
6648 return &ICI;
6649 }
6650
6651 // Was the old condition true if the operand is positive?
6652 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6653
6654 // If so, the new one isn't.
6655 isTrueIfPositive ^= true;
6656
6657 if (isTrueIfPositive)
6658 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6659 else
6660 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6661 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006662
6663 if (LHSI->hasOneUse()) {
6664 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6665 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6666 const APInt &SignBit = XorCST->getValue();
6667 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6668 ? ICI.getUnsignedPredicate()
6669 : ICI.getSignedPredicate();
6670 return new ICmpInst(Pred, LHSI->getOperand(0),
6671 ConstantInt::get(RHSV ^ SignBit));
6672 }
6673
6674 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006675 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006676 const APInt &NotSignBit = XorCST->getValue();
6677 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6678 ? ICI.getUnsignedPredicate()
6679 : ICI.getSignedPredicate();
6680 Pred = ICI.getSwappedPredicate(Pred);
6681 return new ICmpInst(Pred, LHSI->getOperand(0),
6682 ConstantInt::get(RHSV ^ NotSignBit));
6683 }
6684 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006685 }
6686 break;
6687 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6688 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6689 LHSI->getOperand(0)->hasOneUse()) {
6690 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6691
6692 // If the LHS is an AND of a truncating cast, we can widen the
6693 // and/compare to be the input width without changing the value
6694 // produced, eliminating a cast.
6695 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6696 // We can do this transformation if either the AND constant does not
6697 // have its sign bit set or if it is an equality comparison.
6698 // Extending a relational comparison when we're checking the sign
6699 // bit would not work.
6700 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006701 (ICI.isEquality() ||
6702 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006703 uint32_t BitWidth =
6704 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6705 APInt NewCST = AndCST->getValue();
6706 NewCST.zext(BitWidth);
6707 APInt NewCI = RHSV;
6708 NewCI.zext(BitWidth);
6709 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006710 BinaryOperator::CreateAnd(Cast->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006711 ConstantInt::get(NewCST),LHSI->getName());
6712 InsertNewInstBefore(NewAnd, ICI);
6713 return new ICmpInst(ICI.getPredicate(), NewAnd,
6714 ConstantInt::get(NewCI));
6715 }
6716 }
6717
6718 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6719 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6720 // happens a LOT in code produced by the C front-end, for bitfield
6721 // access.
6722 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6723 if (Shift && !Shift->isShift())
6724 Shift = 0;
6725
6726 ConstantInt *ShAmt;
6727 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6728 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6729 const Type *AndTy = AndCST->getType(); // Type of the and.
6730
6731 // We can fold this as long as we can't shift unknown bits
6732 // into the mask. This can only happen with signed shift
6733 // rights, as they sign-extend.
6734 if (ShAmt) {
6735 bool CanFold = Shift->isLogicalShift();
6736 if (!CanFold) {
6737 // To test for the bad case of the signed shr, see if any
6738 // of the bits shifted in could be tested after the mask.
6739 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6740 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6741
6742 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6743 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6744 AndCST->getValue()) == 0)
6745 CanFold = true;
6746 }
6747
6748 if (CanFold) {
6749 Constant *NewCst;
6750 if (Shift->getOpcode() == Instruction::Shl)
6751 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6752 else
6753 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6754
6755 // Check to see if we are shifting out any of the bits being
6756 // compared.
6757 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6758 // If we shifted bits out, the fold is not going to work out.
6759 // As a special case, check to see if this means that the
6760 // result is always true or false now.
6761 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6762 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6763 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6764 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6765 } else {
6766 ICI.setOperand(1, NewCst);
6767 Constant *NewAndCST;
6768 if (Shift->getOpcode() == Instruction::Shl)
6769 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6770 else
6771 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6772 LHSI->setOperand(1, NewAndCST);
6773 LHSI->setOperand(0, Shift->getOperand(0));
6774 AddToWorkList(Shift); // Shift is dead.
6775 AddUsesToWorkList(ICI);
6776 return &ICI;
6777 }
6778 }
6779 }
6780
6781 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6782 // preferable because it allows the C<<Y expression to be hoisted out
6783 // of a loop if Y is invariant and X is not.
6784 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00006785 ICI.isEquality() && !Shift->isArithmeticShift() &&
6786 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006787 // Compute C << Y.
6788 Value *NS;
6789 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006790 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006791 Shift->getOperand(1), "tmp");
6792 } else {
6793 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006794 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006795 Shift->getOperand(1), "tmp");
6796 }
6797 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6798
6799 // Compute X & (C << Y).
6800 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006801 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006802 InsertNewInstBefore(NewAnd, ICI);
6803
6804 ICI.setOperand(0, NewAnd);
6805 return &ICI;
6806 }
6807 }
6808 break;
6809
6810 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6811 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6812 if (!ShAmt) break;
6813
6814 uint32_t TypeBits = RHSV.getBitWidth();
6815
6816 // Check that the shift amount is in range. If not, don't perform
6817 // undefined shifts. When the shift is visited it will be
6818 // simplified.
6819 if (ShAmt->uge(TypeBits))
6820 break;
6821
6822 if (ICI.isEquality()) {
6823 // If we are comparing against bits always shifted out, the
6824 // comparison cannot succeed.
6825 Constant *Comp =
6826 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6827 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6828 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6829 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6830 return ReplaceInstUsesWith(ICI, Cst);
6831 }
6832
6833 if (LHSI->hasOneUse()) {
6834 // Otherwise strength reduce the shift into an and.
6835 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6836 Constant *Mask =
6837 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6838
6839 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006840 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006841 Mask, LHSI->getName()+".mask");
6842 Value *And = InsertNewInstBefore(AndI, ICI);
6843 return new ICmpInst(ICI.getPredicate(), And,
6844 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6845 }
6846 }
6847
6848 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6849 bool TrueIfSigned = false;
6850 if (LHSI->hasOneUse() &&
6851 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6852 // (X << 31) <s 0 --> (X&1) != 0
6853 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6854 (TypeBits-ShAmt->getZExtValue()-1));
6855 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006856 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006857 Mask, LHSI->getName()+".mask");
6858 Value *And = InsertNewInstBefore(AndI, ICI);
6859
6860 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6861 And, Constant::getNullValue(And->getType()));
6862 }
6863 break;
6864 }
6865
6866 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6867 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006868 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006869 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006870 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006871
Chris Lattner5ee84f82008-03-21 05:19:58 +00006872 // Check that the shift amount is in range. If not, don't perform
6873 // undefined shifts. When the shift is visited it will be
6874 // simplified.
6875 uint32_t TypeBits = RHSV.getBitWidth();
6876 if (ShAmt->uge(TypeBits))
6877 break;
6878
6879 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006880
Chris Lattner5ee84f82008-03-21 05:19:58 +00006881 // If we are comparing against bits always shifted out, the
6882 // comparison cannot succeed.
6883 APInt Comp = RHSV << ShAmtVal;
6884 if (LHSI->getOpcode() == Instruction::LShr)
6885 Comp = Comp.lshr(ShAmtVal);
6886 else
6887 Comp = Comp.ashr(ShAmtVal);
6888
6889 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6890 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6891 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6892 return ReplaceInstUsesWith(ICI, Cst);
6893 }
6894
6895 // Otherwise, check to see if the bits shifted out are known to be zero.
6896 // If so, we can compare against the unshifted value:
6897 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006898 if (LHSI->hasOneUse() &&
6899 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006900 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6901 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6902 ConstantExpr::getShl(RHS, ShAmt));
6903 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006904
Evan Chengfb9292a2008-04-23 00:38:06 +00006905 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006906 // Otherwise strength reduce the shift into an and.
6907 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6908 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006909
Chris Lattner5ee84f82008-03-21 05:19:58 +00006910 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006911 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006912 Mask, LHSI->getName()+".mask");
6913 Value *And = InsertNewInstBefore(AndI, ICI);
6914 return new ICmpInst(ICI.getPredicate(), And,
6915 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006916 }
6917 break;
6918 }
6919
6920 case Instruction::SDiv:
6921 case Instruction::UDiv:
6922 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6923 // Fold this div into the comparison, producing a range check.
6924 // Determine, based on the divide type, what the range is being
6925 // checked. If there is an overflow on the low or high side, remember
6926 // it, otherwise compute the range [low, hi) bounding the new value.
6927 // See: InsertRangeTest above for the kinds of replacements possible.
6928 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6929 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6930 DivRHS))
6931 return R;
6932 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006933
6934 case Instruction::Add:
6935 // Fold: icmp pred (add, X, C1), C2
6936
6937 if (!ICI.isEquality()) {
6938 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6939 if (!LHSC) break;
6940 const APInt &LHSV = LHSC->getValue();
6941
6942 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6943 .subtract(LHSV);
6944
6945 if (ICI.isSignedPredicate()) {
6946 if (CR.getLower().isSignBit()) {
6947 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6948 ConstantInt::get(CR.getUpper()));
6949 } else if (CR.getUpper().isSignBit()) {
6950 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6951 ConstantInt::get(CR.getLower()));
6952 }
6953 } else {
6954 if (CR.getLower().isMinValue()) {
6955 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6956 ConstantInt::get(CR.getUpper()));
6957 } else if (CR.getUpper().isMinValue()) {
6958 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6959 ConstantInt::get(CR.getLower()));
6960 }
6961 }
6962 }
6963 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006964 }
6965
6966 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6967 if (ICI.isEquality()) {
6968 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6969
6970 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6971 // the second operand is a constant, simplify a bit.
6972 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6973 switch (BO->getOpcode()) {
6974 case Instruction::SRem:
6975 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6976 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6977 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6978 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6979 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00006980 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006981 BO->getName());
6982 InsertNewInstBefore(NewRem, ICI);
6983 return new ICmpInst(ICI.getPredicate(), NewRem,
6984 Constant::getNullValue(BO->getType()));
6985 }
6986 }
6987 break;
6988 case Instruction::Add:
6989 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6990 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6991 if (BO->hasOneUse())
6992 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohman8fd520a2009-06-15 22:12:54 +00006993 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006994 } else if (RHSV == 0) {
6995 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6996 // efficiently invertible, or if the add has just this one use.
6997 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6998
6999 if (Value *NegVal = dyn_castNegVal(BOp1))
7000 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7001 else if (Value *NegVal = dyn_castNegVal(BOp0))
7002 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7003 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007004 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007005 InsertNewInstBefore(Neg, ICI);
7006 Neg->takeName(BO);
7007 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7008 }
7009 }
7010 break;
7011 case Instruction::Xor:
7012 // For the xor case, we can xor two constants together, eliminating
7013 // the explicit xor.
7014 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7015 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7016 ConstantExpr::getXor(RHS, BOC));
7017
7018 // FALLTHROUGH
7019 case Instruction::Sub:
7020 // Replace (([sub|xor] A, B) != 0) with (A != B)
7021 if (RHSV == 0)
7022 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7023 BO->getOperand(1));
7024 break;
7025
7026 case Instruction::Or:
7027 // If bits are being or'd in that are not present in the constant we
7028 // are comparing against, then the comparison could never succeed!
7029 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7030 Constant *NotCI = ConstantExpr::getNot(RHS);
7031 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7032 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7033 isICMP_NE));
7034 }
7035 break;
7036
7037 case Instruction::And:
7038 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7039 // If bits are being compared against that are and'd out, then the
7040 // comparison can never succeed!
7041 if ((RHSV & ~BOC->getValue()) != 0)
7042 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7043 isICMP_NE));
7044
7045 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7046 if (RHS == BOC && RHSV.isPowerOf2())
7047 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7048 ICmpInst::ICMP_NE, LHSI,
7049 Constant::getNullValue(RHS->getType()));
7050
7051 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007052 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007053 Value *X = BO->getOperand(0);
7054 Constant *Zero = Constant::getNullValue(X->getType());
7055 ICmpInst::Predicate pred = isICMP_NE ?
7056 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7057 return new ICmpInst(pred, X, Zero);
7058 }
7059
7060 // ((X & ~7) == 0) --> X < 8
7061 if (RHSV == 0 && isHighOnes(BOC)) {
7062 Value *X = BO->getOperand(0);
7063 Constant *NegX = ConstantExpr::getNeg(BOC);
7064 ICmpInst::Predicate pred = isICMP_NE ?
7065 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7066 return new ICmpInst(pred, X, NegX);
7067 }
7068 }
7069 default: break;
7070 }
7071 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7072 // Handle icmp {eq|ne} <intrinsic>, intcst.
7073 if (II->getIntrinsicID() == Intrinsic::bswap) {
7074 AddToWorkList(II);
7075 ICI.setOperand(0, II->getOperand(1));
7076 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
7077 return &ICI;
7078 }
7079 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007080 }
7081 return 0;
7082}
7083
7084/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7085/// We only handle extending casts so far.
7086///
7087Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7088 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7089 Value *LHSCIOp = LHSCI->getOperand(0);
7090 const Type *SrcTy = LHSCIOp->getType();
7091 const Type *DestTy = LHSCI->getType();
7092 Value *RHSCIOp;
7093
7094 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7095 // integer type is the same size as the pointer type.
7096 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7097 getTargetData().getPointerSizeInBits() ==
7098 cast<IntegerType>(DestTy)->getBitWidth()) {
7099 Value *RHSOp = 0;
7100 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7101 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7102 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7103 RHSOp = RHSC->getOperand(0);
7104 // If the pointer types don't match, insert a bitcast.
7105 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00007106 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007107 }
7108
7109 if (RHSOp)
7110 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7111 }
7112
7113 // The code below only handles extension cast instructions, so far.
7114 // Enforce this.
7115 if (LHSCI->getOpcode() != Instruction::ZExt &&
7116 LHSCI->getOpcode() != Instruction::SExt)
7117 return 0;
7118
7119 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7120 bool isSignedCmp = ICI.isSignedPredicate();
7121
7122 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7123 // Not an extension from the same type?
7124 RHSCIOp = CI->getOperand(0);
7125 if (RHSCIOp->getType() != LHSCIOp->getType())
7126 return 0;
7127
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007128 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007129 // and the other is a zext), then we can't handle this.
7130 if (CI->getOpcode() != LHSCI->getOpcode())
7131 return 0;
7132
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007133 // Deal with equality cases early.
7134 if (ICI.isEquality())
7135 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7136
7137 // A signed comparison of sign extended values simplifies into a
7138 // signed comparison.
7139 if (isSignedCmp && isSignedExt)
7140 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7141
7142 // The other three cases all fold into an unsigned comparison.
7143 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007144 }
7145
7146 // If we aren't dealing with a constant on the RHS, exit early
7147 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7148 if (!CI)
7149 return 0;
7150
7151 // Compute the constant that would happen if we truncated to SrcTy then
7152 // reextended to DestTy.
7153 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7154 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
7155
7156 // If the re-extended constant didn't change...
7157 if (Res2 == CI) {
7158 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7159 // For example, we might have:
Dan Gohman9e1657f2009-06-14 23:30:43 +00007160 // %A = sext i16 %X to i32
7161 // %B = icmp ugt i32 %A, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007162 // It is incorrect to transform this into
Dan Gohman9e1657f2009-06-14 23:30:43 +00007163 // %B = icmp ugt i16 %X, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007164 // because %A may have negative value.
7165 //
Chris Lattner3d816532008-07-11 04:09:09 +00007166 // However, we allow this when the compare is EQ/NE, because they are
7167 // signless.
7168 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007169 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00007170 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007171 }
7172
7173 // The re-extended constant changed so the constant cannot be represented
7174 // in the shorter type. Consequently, we cannot emit a simple comparison.
7175
7176 // First, handle some easy cases. We know the result cannot be equal at this
7177 // point so handle the ICI.isEquality() cases
7178 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7179 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
7180 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7181 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
7182
7183 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7184 // should have been folded away previously and not enter in here.
7185 Value *Result;
7186 if (isSignedCmp) {
7187 // We're performing a signed comparison.
7188 if (cast<ConstantInt>(CI)->getValue().isNegative())
7189 Result = ConstantInt::getFalse(); // X < (small) --> false
7190 else
7191 Result = ConstantInt::getTrue(); // X < (large) --> true
7192 } else {
7193 // We're performing an unsigned comparison.
7194 if (isSignedExt) {
7195 // We're performing an unsigned comp with a sign extended value.
7196 // This is true if the input is >= 0. [aka >s -1]
7197 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
7198 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7199 NegOne, ICI.getName()), ICI);
7200 } else {
7201 // Unsigned extend & unsigned compare -> always true.
7202 Result = ConstantInt::getTrue();
7203 }
7204 }
7205
7206 // Finally, return the value computed.
7207 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007208 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007209 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007210
7211 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7212 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7213 "ICmp should be folded!");
7214 if (Constant *CI = dyn_cast<Constant>(Result))
7215 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7216 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007217}
7218
7219Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7220 return commonShiftTransforms(I);
7221}
7222
7223Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7224 return commonShiftTransforms(I);
7225}
7226
7227Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007228 if (Instruction *R = commonShiftTransforms(I))
7229 return R;
7230
7231 Value *Op0 = I.getOperand(0);
7232
7233 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7234 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7235 if (CSI->isAllOnesValue())
7236 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007237
Dan Gohman2526aea2009-06-16 19:55:29 +00007238 // See if we can turn a signed shr into an unsigned shr.
7239 if (MaskedValueIsZero(Op0,
7240 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7241 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7242
7243 // Arithmetic shifting an all-sign-bit value is a no-op.
7244 unsigned NumSignBits = ComputeNumSignBits(Op0);
7245 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7246 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007247
Chris Lattnere3c504f2007-12-06 01:59:46 +00007248 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007249}
7250
7251Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7252 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7253 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7254
7255 // shl X, 0 == X and shr X, 0 == X
7256 // shl 0, X == 0 and shr 0, X == 0
7257 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7258 Op0 == Constant::getNullValue(Op0->getType()))
7259 return ReplaceInstUsesWith(I, Op0);
7260
7261 if (isa<UndefValue>(Op0)) {
7262 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7263 return ReplaceInstUsesWith(I, Op0);
7264 else // undef << X -> 0, undef >>u X -> 0
7265 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7266 }
7267 if (isa<UndefValue>(Op1)) {
7268 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7269 return ReplaceInstUsesWith(I, Op0);
7270 else // X << undef, X >>u undef -> 0
7271 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7272 }
7273
Dan Gohman2bc21562009-05-21 02:28:33 +00007274 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007275 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007276 return &I;
7277
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007278 // Try to fold constant and into select arguments.
7279 if (isa<Constant>(Op0))
7280 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7281 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7282 return R;
7283
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007284 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7285 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7286 return Res;
7287 return 0;
7288}
7289
7290Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7291 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007292 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007293
7294 // See if we can simplify any instructions used by the instruction whose sole
7295 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007296 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007297
Dan Gohman9e1657f2009-06-14 23:30:43 +00007298 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7299 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007300 //
7301 if (Op1->uge(TypeBits)) {
7302 if (I.getOpcode() != Instruction::AShr)
7303 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7304 else {
7305 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7306 return &I;
7307 }
7308 }
7309
7310 // ((X*C1) << C2) == (X * (C1 << C2))
7311 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7312 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7313 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007314 return BinaryOperator::CreateMul(BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007315 ConstantExpr::getShl(BOOp, Op1));
7316
7317 // Try to fold constant and into select arguments.
7318 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7319 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7320 return R;
7321 if (isa<PHINode>(Op0))
7322 if (Instruction *NV = FoldOpIntoPhi(I))
7323 return NV;
7324
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007325 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7326 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7327 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7328 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7329 // place. Don't try to do this transformation in this case. Also, we
7330 // require that the input operand is a shift-by-constant so that we have
7331 // confidence that the shifts will get folded together. We could do this
7332 // xform in more cases, but it is unlikely to be profitable.
7333 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7334 isa<ConstantInt>(TrOp->getOperand(1))) {
7335 // Okay, we'll do this xform. Make the shift of shift.
7336 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00007337 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007338 I.getName());
7339 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7340
7341 // For logical shifts, the truncation has the effect of making the high
7342 // part of the register be zeros. Emulate this by inserting an AND to
7343 // clear the top bits as needed. This 'and' will usually be zapped by
7344 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007345 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7346 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007347 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7348
7349 // The mask we constructed says what the trunc would do if occurring
7350 // between the shifts. We want to know the effect *after* the second
7351 // shift. We know that it is a logical shift by a constant, so adjust the
7352 // mask as appropriate.
7353 if (I.getOpcode() == Instruction::Shl)
7354 MaskV <<= Op1->getZExtValue();
7355 else {
7356 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7357 MaskV = MaskV.lshr(Op1->getZExtValue());
7358 }
7359
Gabor Greifa645dd32008-05-16 19:29:10 +00007360 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007361 TI->getName());
7362 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7363
7364 // Return the value truncated to the interesting size.
7365 return new TruncInst(And, I.getType());
7366 }
7367 }
7368
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007369 if (Op0->hasOneUse()) {
7370 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7371 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7372 Value *V1, *V2;
7373 ConstantInt *CC;
7374 switch (Op0BO->getOpcode()) {
7375 default: break;
7376 case Instruction::Add:
7377 case Instruction::And:
7378 case Instruction::Or:
7379 case Instruction::Xor: {
7380 // These operators commute.
7381 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7382 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattner3b874082008-11-16 05:38:51 +00007383 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greifa645dd32008-05-16 19:29:10 +00007384 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007385 Op0BO->getOperand(0), Op1,
7386 Op0BO->getName());
7387 InsertNewInstBefore(YS, I); // (Y << C)
7388 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007389 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007390 Op0BO->getOperand(1)->getName());
7391 InsertNewInstBefore(X, I); // (X + (Y << C))
7392 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00007393 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007394 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7395 }
7396
7397 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7398 Value *Op0BOOp1 = Op0BO->getOperand(1);
7399 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7400 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007401 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7402 m_ConstantInt(CC))) &&
7403 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007404 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007405 Op0BO->getOperand(0), Op1,
7406 Op0BO->getName());
7407 InsertNewInstBefore(YS, I); // (Y << C)
7408 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00007409 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007410 V1->getName()+".mask");
7411 InsertNewInstBefore(XM, I); // X & (CC << C)
7412
Gabor Greifa645dd32008-05-16 19:29:10 +00007413 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007414 }
7415 }
7416
7417 // FALL THROUGH.
7418 case Instruction::Sub: {
7419 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7420 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattner3b874082008-11-16 05:38:51 +00007421 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greifa645dd32008-05-16 19:29:10 +00007422 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007423 Op0BO->getOperand(1), Op1,
7424 Op0BO->getName());
7425 InsertNewInstBefore(YS, I); // (Y << C)
7426 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007427 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007428 Op0BO->getOperand(0)->getName());
7429 InsertNewInstBefore(X, I); // (X + (Y << C))
7430 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00007431 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007432 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7433 }
7434
7435 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7436 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7437 match(Op0BO->getOperand(0),
7438 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7439 m_ConstantInt(CC))) && V2 == Op1 &&
7440 cast<BinaryOperator>(Op0BO->getOperand(0))
7441 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007442 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007443 Op0BO->getOperand(1), Op1,
7444 Op0BO->getName());
7445 InsertNewInstBefore(YS, I); // (Y << C)
7446 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00007447 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007448 V1->getName()+".mask");
7449 InsertNewInstBefore(XM, I); // X & (CC << C)
7450
Gabor Greifa645dd32008-05-16 19:29:10 +00007451 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007452 }
7453
7454 break;
7455 }
7456 }
7457
7458
7459 // If the operand is an bitwise operator with a constant RHS, and the
7460 // shift is the only use, we can pull it out of the shift.
7461 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7462 bool isValid = true; // Valid only for And, Or, Xor
7463 bool highBitSet = false; // Transform if high bit of constant set?
7464
7465 switch (Op0BO->getOpcode()) {
7466 default: isValid = false; break; // Do not perform transform!
7467 case Instruction::Add:
7468 isValid = isLeftShift;
7469 break;
7470 case Instruction::Or:
7471 case Instruction::Xor:
7472 highBitSet = false;
7473 break;
7474 case Instruction::And:
7475 highBitSet = true;
7476 break;
7477 }
7478
7479 // If this is a signed shift right, and the high bit is modified
7480 // by the logical operation, do not perform the transformation.
7481 // The highBitSet boolean indicates the value of the high bit of
7482 // the constant which would cause it to be modified for this
7483 // operation.
7484 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007485 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007486 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007487
7488 if (isValid) {
7489 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7490
7491 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007492 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007493 InsertNewInstBefore(NewShift, I);
7494 NewShift->takeName(Op0BO);
7495
Gabor Greifa645dd32008-05-16 19:29:10 +00007496 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007497 NewRHS);
7498 }
7499 }
7500 }
7501 }
7502
7503 // Find out if this is a shift of a shift by a constant.
7504 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7505 if (ShiftOp && !ShiftOp->isShift())
7506 ShiftOp = 0;
7507
7508 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7509 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7510 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7511 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7512 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7513 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7514 Value *X = ShiftOp->getOperand(0);
7515
7516 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007517
7518 const IntegerType *Ty = cast<IntegerType>(I.getType());
7519
7520 // Check for (X << c1) << c2 and (X >> c1) >> c2
7521 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007522 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7523 // saturates.
7524 if (AmtSum >= TypeBits) {
7525 if (I.getOpcode() != Instruction::AShr)
7526 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7527 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7528 }
7529
Gabor Greifa645dd32008-05-16 19:29:10 +00007530 return BinaryOperator::Create(I.getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007531 ConstantInt::get(Ty, AmtSum));
7532 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7533 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007534 if (AmtSum >= TypeBits)
7535 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7536
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007537 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greifa645dd32008-05-16 19:29:10 +00007538 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007539 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7540 I.getOpcode() == Instruction::LShr) {
7541 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007542 if (AmtSum >= TypeBits)
7543 AmtSum = TypeBits-1;
7544
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007545 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007546 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007547 InsertNewInstBefore(Shift, I);
7548
7549 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007550 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007551 }
7552
7553 // Okay, if we get here, one shift must be left, and the other shift must be
7554 // right. See if the amounts are equal.
7555 if (ShiftAmt1 == ShiftAmt2) {
7556 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7557 if (I.getOpcode() == Instruction::Shl) {
7558 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00007559 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007560 }
7561 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7562 if (I.getOpcode() == Instruction::LShr) {
7563 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00007564 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007565 }
7566 // We can simplify ((X << C) >>s C) into a trunc + sext.
7567 // NOTE: we could do this for any C, but that would make 'unusual' integer
7568 // types. For now, just stick to ones well-supported by the code
7569 // generators.
7570 const Type *SExtType = 0;
7571 switch (Ty->getBitWidth() - ShiftAmt1) {
7572 case 1 :
7573 case 8 :
7574 case 16 :
7575 case 32 :
7576 case 64 :
7577 case 128:
7578 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7579 break;
7580 default: break;
7581 }
7582 if (SExtType) {
7583 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7584 InsertNewInstBefore(NewTrunc, I);
7585 return new SExtInst(NewTrunc, Ty);
7586 }
7587 // Otherwise, we can't handle it yet.
7588 } else if (ShiftAmt1 < ShiftAmt2) {
7589 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7590
7591 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7592 if (I.getOpcode() == Instruction::Shl) {
7593 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7594 ShiftOp->getOpcode() == Instruction::AShr);
7595 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007596 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007597 InsertNewInstBefore(Shift, I);
7598
7599 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007600 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007601 }
7602
7603 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7604 if (I.getOpcode() == Instruction::LShr) {
7605 assert(ShiftOp->getOpcode() == Instruction::Shl);
7606 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007607 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007608 InsertNewInstBefore(Shift, I);
7609
7610 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007611 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007612 }
7613
7614 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7615 } else {
7616 assert(ShiftAmt2 < ShiftAmt1);
7617 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7618
7619 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7620 if (I.getOpcode() == Instruction::Shl) {
7621 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7622 ShiftOp->getOpcode() == Instruction::AShr);
7623 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007624 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007625 ConstantInt::get(Ty, ShiftDiff));
7626 InsertNewInstBefore(Shift, I);
7627
7628 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007629 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007630 }
7631
7632 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7633 if (I.getOpcode() == Instruction::LShr) {
7634 assert(ShiftOp->getOpcode() == Instruction::Shl);
7635 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007636 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007637 InsertNewInstBefore(Shift, I);
7638
7639 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007640 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007641 }
7642
7643 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7644 }
7645 }
7646 return 0;
7647}
7648
7649
7650/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7651/// expression. If so, decompose it, returning some value X, such that Val is
7652/// X*Scale+Offset.
7653///
7654static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7655 int &Offset) {
7656 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7657 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7658 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007659 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007660 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007661 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7662 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7663 if (I->getOpcode() == Instruction::Shl) {
7664 // This is a value scaled by '1 << the shift amt'.
7665 Scale = 1U << RHS->getZExtValue();
7666 Offset = 0;
7667 return I->getOperand(0);
7668 } else if (I->getOpcode() == Instruction::Mul) {
7669 // This value is scaled by 'RHS'.
7670 Scale = RHS->getZExtValue();
7671 Offset = 0;
7672 return I->getOperand(0);
7673 } else if (I->getOpcode() == Instruction::Add) {
7674 // We have X+C. Check to see if we really have (X*C2)+C1,
7675 // where C1 is divisible by C2.
7676 unsigned SubScale;
7677 Value *SubVal =
7678 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7679 Offset += RHS->getZExtValue();
7680 Scale = SubScale;
7681 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007682 }
7683 }
7684 }
7685
7686 // Otherwise, we can't look past this.
7687 Scale = 1;
7688 Offset = 0;
7689 return Val;
7690}
7691
7692
7693/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7694/// try to eliminate the cast by moving the type information into the alloc.
7695Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7696 AllocationInst &AI) {
7697 const PointerType *PTy = cast<PointerType>(CI.getType());
7698
7699 // Remove any uses of AI that are dead.
7700 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7701
7702 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7703 Instruction *User = cast<Instruction>(*UI++);
7704 if (isInstructionTriviallyDead(User)) {
7705 while (UI != E && *UI == User)
7706 ++UI; // If this instruction uses AI more than once, don't break UI.
7707
7708 ++NumDeadInst;
7709 DOUT << "IC: DCE: " << *User;
7710 EraseInstFromFunction(*User);
7711 }
7712 }
7713
7714 // Get the type really allocated and the type casted to.
7715 const Type *AllocElTy = AI.getAllocatedType();
7716 const Type *CastElTy = PTy->getElementType();
7717 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7718
7719 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7720 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7721 if (CastElTyAlign < AllocElTyAlign) return 0;
7722
7723 // If the allocation has multiple uses, only promote it if we are strictly
7724 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007725 // same, we open the door to infinite loops of various kinds. (A reference
7726 // from a dbg.declare doesn't count as a use for this purpose.)
7727 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7728 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007729
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007730 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7731 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007732 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7733
7734 // See if we can satisfy the modulus by pulling a scale out of the array
7735 // size argument.
7736 unsigned ArraySizeScale;
7737 int ArrayOffset;
7738 Value *NumElements = // See if the array size is a decomposable linear expr.
7739 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7740
7741 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7742 // do the xform.
7743 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7744 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7745
7746 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7747 Value *Amt = 0;
7748 if (Scale == 1) {
7749 Amt = NumElements;
7750 } else {
7751 // If the allocation size is constant, form a constant mul expression
7752 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7753 if (isa<ConstantInt>(NumElements))
Dan Gohman8fd520a2009-06-15 22:12:54 +00007754 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7755 cast<ConstantInt>(Amt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007756 // otherwise multiply the amount and the number of elements
Chris Lattner27cc5472009-03-17 17:55:15 +00007757 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00007758 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007759 Amt = InsertNewInstBefore(Tmp, AI);
7760 }
7761 }
7762
7763 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7764 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007765 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007766 Amt = InsertNewInstBefore(Tmp, AI);
7767 }
7768
7769 AllocationInst *New;
7770 if (isa<MallocInst>(AI))
7771 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7772 else
7773 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7774 InsertNewInstBefore(New, AI);
7775 New->takeName(&AI);
7776
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007777 // If the allocation has one real use plus a dbg.declare, just remove the
7778 // declare.
7779 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7780 EraseInstFromFunction(*DI);
7781 }
7782 // If the allocation has multiple real uses, insert a cast and change all
7783 // things that used it to use the new cast. This will also hack on CI, but it
7784 // will die soon.
7785 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007786 AddUsesToWorkList(AI);
7787 // New is the allocation instruction, pointer typed. AI is the original
7788 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7789 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7790 InsertNewInstBefore(NewCast, AI);
7791 AI.replaceAllUsesWith(NewCast);
7792 }
7793 return ReplaceInstUsesWith(CI, New);
7794}
7795
7796/// CanEvaluateInDifferentType - Return true if we can take the specified value
7797/// and return it as type Ty without inserting any new casts and without
7798/// changing the computed value. This is used by code that tries to decide
7799/// whether promoting or shrinking integer operations to wider or smaller types
7800/// will allow us to eliminate a truncate or extend.
7801///
7802/// This is a truncation operation if Ty is smaller than V->getType(), or an
7803/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007804///
7805/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7806/// should return true if trunc(V) can be computed by computing V in the smaller
7807/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7808/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7809/// efficiently truncated.
7810///
7811/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7812/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7813/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007814bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00007815 unsigned CastOpc,
7816 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007817 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007818 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007819 return true;
7820
7821 Instruction *I = dyn_cast<Instruction>(V);
7822 if (!I) return false;
7823
Dan Gohman8fd520a2009-06-15 22:12:54 +00007824 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007825
Chris Lattneref70bb82007-08-02 06:11:14 +00007826 // If this is an extension or truncate, we can often eliminate it.
7827 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7828 // If this is a cast from the destination type, we can trivially eliminate
7829 // it, and this will remove a cast overall.
7830 if (I->getOperand(0)->getType() == Ty) {
7831 // If the first operand is itself a cast, and is eliminable, do not count
7832 // this as an eliminable cast. We would prefer to eliminate those two
7833 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007834 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007835 ++NumCastsRemoved;
7836 return true;
7837 }
7838 }
7839
7840 // We can't extend or shrink something that has multiple uses: doing so would
7841 // require duplicating the instruction in general, which isn't profitable.
7842 if (!I->hasOneUse()) return false;
7843
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007844 unsigned Opc = I->getOpcode();
7845 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007846 case Instruction::Add:
7847 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007848 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007849 case Instruction::And:
7850 case Instruction::Or:
7851 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007852 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007853 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007854 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007855 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007856 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007857
7858 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007859 // If we are truncating the result of this SHL, and if it's a shift of a
7860 // constant amount, we can always perform a SHL in a smaller type.
7861 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007862 uint32_t BitWidth = Ty->getScalarSizeInBits();
7863 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007864 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007865 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007866 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007867 }
7868 break;
7869 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007870 // If this is a truncate of a logical shr, we can truncate it to a smaller
7871 // lshr iff we know that the bits we would otherwise be shifting in are
7872 // already zeros.
7873 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007874 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7875 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007876 if (BitWidth < OrigBitWidth &&
7877 MaskedValueIsZero(I->getOperand(0),
7878 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7879 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007880 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007881 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007882 }
7883 }
7884 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007885 case Instruction::ZExt:
7886 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007887 case Instruction::Trunc:
7888 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007889 // can safely replace it. Note that replacing it does not reduce the number
7890 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007891 if (Opc == CastOpc)
7892 return true;
7893
7894 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00007895 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007896 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007897 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007898 case Instruction::Select: {
7899 SelectInst *SI = cast<SelectInst>(I);
7900 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007901 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007902 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007903 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007904 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007905 case Instruction::PHI: {
7906 // We can change a phi if we can change all operands.
7907 PHINode *PN = cast<PHINode>(I);
7908 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7909 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007910 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00007911 return false;
7912 return true;
7913 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007914 default:
7915 // TODO: Can handle more cases here.
7916 break;
7917 }
7918
7919 return false;
7920}
7921
7922/// EvaluateInDifferentType - Given an expression that
7923/// CanEvaluateInDifferentType returns true for, actually insert the code to
7924/// evaluate the expression.
7925Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7926 bool isSigned) {
7927 if (Constant *C = dyn_cast<Constant>(V))
7928 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7929
7930 // Otherwise, it must be an instruction.
7931 Instruction *I = cast<Instruction>(V);
7932 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007933 unsigned Opc = I->getOpcode();
7934 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007935 case Instruction::Add:
7936 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007937 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007938 case Instruction::And:
7939 case Instruction::Or:
7940 case Instruction::Xor:
7941 case Instruction::AShr:
7942 case Instruction::LShr:
7943 case Instruction::Shl: {
7944 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7945 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007946 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007947 break;
7948 }
7949 case Instruction::Trunc:
7950 case Instruction::ZExt:
7951 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007952 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007953 // just return the source. There's no need to insert it because it is not
7954 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007955 if (I->getOperand(0)->getType() == Ty)
7956 return I->getOperand(0);
7957
Chris Lattner4200c2062008-06-18 04:00:49 +00007958 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007959 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00007960 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00007961 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007962 case Instruction::Select: {
7963 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7964 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7965 Res = SelectInst::Create(I->getOperand(0), True, False);
7966 break;
7967 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007968 case Instruction::PHI: {
7969 PHINode *OPN = cast<PHINode>(I);
7970 PHINode *NPN = PHINode::Create(Ty);
7971 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7972 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7973 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7974 }
7975 Res = NPN;
7976 break;
7977 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007978 default:
7979 // TODO: Can handle more cases here.
7980 assert(0 && "Unreachable!");
7981 break;
7982 }
7983
Chris Lattner4200c2062008-06-18 04:00:49 +00007984 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007985 return InsertNewInstBefore(Res, *I);
7986}
7987
7988/// @brief Implement the transforms common to all CastInst visitors.
7989Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7990 Value *Src = CI.getOperand(0);
7991
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007992 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7993 // eliminate it now.
7994 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7995 if (Instruction::CastOps opc =
7996 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7997 // The first cast (CSrc) is eliminable so we need to fix up or replace
7998 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00007999 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008000 }
8001 }
8002
8003 // If we are casting a select then fold the cast into the select
8004 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8005 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8006 return NV;
8007
8008 // If we are casting a PHI then fold the cast into the PHI
8009 if (isa<PHINode>(Src))
8010 if (Instruction *NV = FoldOpIntoPhi(CI))
8011 return NV;
8012
8013 return 0;
8014}
8015
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008016/// FindElementAtOffset - Given a type and a constant offset, determine whether
8017/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008018/// the specified offset. If so, fill them into NewIndices and return the
8019/// resultant element type, otherwise return null.
8020static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8021 SmallVectorImpl<Value*> &NewIndices,
8022 const TargetData *TD) {
8023 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008024
8025 // Start with the index over the outer type. Note that the type size
8026 // might be zero (even if the offset isn't zero) if the indexed type
8027 // is something like [0 x {int, int}]
8028 const Type *IntPtrTy = TD->getIntPtrType();
8029 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008030 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008031 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008032 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008033
Chris Lattnerce48c462009-01-11 20:15:20 +00008034 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008035 if (Offset < 0) {
8036 --FirstIdx;
8037 Offset += TySize;
8038 assert(Offset >= 0);
8039 }
8040 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8041 }
8042
8043 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8044
8045 // Index into the types. If we fail, set OrigBase to null.
8046 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008047 // Indexing into tail padding between struct/array elements.
8048 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008049 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008050
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008051 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8052 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008053 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8054 "Offset must stay within the indexed type");
8055
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008056 unsigned Elt = SL->getElementContainingOffset(Offset);
8057 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
8058
8059 Offset -= SL->getElementOffset(Elt);
8060 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008061 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008062 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008063 assert(EltSize && "Cannot index into a zero-sized array");
8064 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8065 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008066 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008067 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008068 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008069 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008070 }
8071 }
8072
Chris Lattner54dddc72009-01-24 01:00:13 +00008073 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008074}
8075
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008076/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8077Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8078 Value *Src = CI.getOperand(0);
8079
8080 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8081 // If casting the result of a getelementptr instruction with no offset, turn
8082 // this into a cast of the original pointer!
8083 if (GEP->hasAllZeroIndices()) {
8084 // Changing the cast operand is usually not a good idea but it is safe
8085 // here because the pointer operand is being replaced with another
8086 // pointer operand so the opcode doesn't need to change.
8087 AddToWorkList(GEP);
8088 CI.setOperand(0, GEP->getOperand(0));
8089 return &CI;
8090 }
8091
8092 // If the GEP has a single use, and the base pointer is a bitcast, and the
8093 // GEP computes a constant offset, see if we can convert these three
8094 // instructions into fewer. This typically happens with unions and other
8095 // non-type-safe code.
8096 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8097 if (GEP->hasAllConstantIndices()) {
8098 // We are guaranteed to get a constant from EmitGEPOffset.
8099 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8100 int64_t Offset = OffsetV->getSExtValue();
8101
8102 // Get the base pointer input of the bitcast, and the type it points to.
8103 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8104 const Type *GEPIdxTy =
8105 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008106 SmallVector<Value*, 8> NewIndices;
8107 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
8108 // If we were able to index down into an element, create the GEP
8109 // and bitcast the result. This eliminates one bitcast, potentially
8110 // two.
8111 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8112 NewIndices.begin(),
8113 NewIndices.end(), "");
8114 InsertNewInstBefore(NGEP, CI);
8115 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008116
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008117 if (isa<BitCastInst>(CI))
8118 return new BitCastInst(NGEP, CI.getType());
8119 assert(isa<PtrToIntInst>(CI));
8120 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008121 }
8122 }
8123 }
8124 }
8125
8126 return commonCastTransforms(CI);
8127}
8128
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008129/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8130/// type like i42. We don't want to introduce operations on random non-legal
8131/// integer types where they don't already exist in the code. In the future,
8132/// we should consider making this based off target-data, so that 32-bit targets
8133/// won't get i64 operations etc.
8134static bool isSafeIntegerType(const Type *Ty) {
8135 switch (Ty->getPrimitiveSizeInBits()) {
8136 case 8:
8137 case 16:
8138 case 32:
8139 case 64:
8140 return true;
8141 default:
8142 return false;
8143 }
8144}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008145
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008146/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8147/// integer types. This function implements the common transforms for all those
8148/// cases.
8149/// @brief Implement the transforms common to CastInst with integer operands
8150Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8151 if (Instruction *Result = commonCastTransforms(CI))
8152 return Result;
8153
8154 Value *Src = CI.getOperand(0);
8155 const Type *SrcTy = Src->getType();
8156 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008157 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8158 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008159
8160 // See if we can simplify any instructions used by the LHS whose sole
8161 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008162 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008163 return &CI;
8164
8165 // If the source isn't an instruction or has more than one use then we
8166 // can't do anything more.
8167 Instruction *SrcI = dyn_cast<Instruction>(Src);
8168 if (!SrcI || !Src->hasOneUse())
8169 return 0;
8170
8171 // Attempt to propagate the cast into the instruction for int->int casts.
8172 int NumCastsRemoved = 0;
8173 if (!isa<BitCastInst>(CI) &&
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008174 // Only do this if the dest type is a simple type, don't convert the
8175 // expression tree to something weird like i93 unless the source is also
8176 // strange.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008177 (isSafeIntegerType(DestTy->getScalarType()) ||
8178 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8179 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng814a00c2009-01-16 02:11:43 +00008180 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008181 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008182 // eliminates the cast, so it is always a win. If this is a zero-extension,
8183 // we need to do an AND to maintain the clear top-part of the computation,
8184 // so we require that the input have eliminated at least one cast. If this
8185 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008186 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008187 bool DoXForm = false;
8188 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008189 switch (CI.getOpcode()) {
8190 default:
8191 // All the others use floating point so we shouldn't actually
8192 // get here because of the check above.
8193 assert(0 && "Unknown cast type");
8194 case Instruction::Trunc:
8195 DoXForm = true;
8196 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008197 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008198 DoXForm = NumCastsRemoved >= 1;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008199 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008200 // If it's unnecessary to issue an AND to clear the high bits, it's
8201 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008202 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008203 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8204 if (MaskedValueIsZero(TryRes, Mask))
8205 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008206
8207 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008208 if (TryI->use_empty())
8209 EraseInstFromFunction(*TryI);
8210 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008211 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008212 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008213 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008214 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008215 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008216 // If we do not have to emit the truncate + sext pair, then it's always
8217 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008218 //
8219 // It's not safe to eliminate the trunc + sext pair if one of the
8220 // eliminated cast is a truncate. e.g.
8221 // t2 = trunc i32 t1 to i16
8222 // t3 = sext i16 t2 to i32
8223 // !=
8224 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008225 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008226 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8227 if (NumSignBits > (DestBitSize - SrcBitSize))
8228 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008229
8230 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008231 if (TryI->use_empty())
8232 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008233 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008234 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008235 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008236 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008237
8238 if (DoXForm) {
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008239 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8240 << " cast: " << CI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008241 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8242 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008243 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008244 // Just replace this cast with the result.
8245 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008246
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008247 assert(Res->getType() == DestTy);
8248 switch (CI.getOpcode()) {
8249 default: assert(0 && "Unknown cast type!");
8250 case Instruction::Trunc:
8251 case Instruction::BitCast:
8252 // Just replace this cast with the result.
8253 return ReplaceInstUsesWith(CI, Res);
8254 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008255 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008256
8257 // If the high bits are already zero, just replace this cast with the
8258 // result.
8259 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8260 if (MaskedValueIsZero(Res, Mask))
8261 return ReplaceInstUsesWith(CI, Res);
8262
8263 // We need to emit an AND to clear the high bits.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008264 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8265 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008266 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008267 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008268 case Instruction::SExt: {
8269 // If the high bits are already filled with sign bit, just replace this
8270 // cast with the result.
8271 unsigned NumSignBits = ComputeNumSignBits(Res);
8272 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008273 return ReplaceInstUsesWith(CI, Res);
8274
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008275 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00008276 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008277 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8278 CI), DestTy);
8279 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008280 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008281 }
8282 }
8283
8284 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8285 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8286
8287 switch (SrcI->getOpcode()) {
8288 case Instruction::Add:
8289 case Instruction::Mul:
8290 case Instruction::And:
8291 case Instruction::Or:
8292 case Instruction::Xor:
8293 // If we are discarding information, rewrite.
8294 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8295 // Don't insert two casts if they cannot be eliminated. We allow
8296 // two casts to be inserted if the sizes are the same. This could
8297 // only be converting signedness, which is a noop.
8298 if (DestBitSize == SrcBitSize ||
8299 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8300 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8301 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedman722b4792008-11-30 21:09:11 +00008302 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8303 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008304 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008305 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8306 }
8307 }
8308
8309 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8310 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8311 SrcI->getOpcode() == Instruction::Xor &&
8312 Op1 == ConstantInt::getTrue() &&
8313 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedman722b4792008-11-30 21:09:11 +00008314 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008315 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008316 }
8317 break;
8318 case Instruction::SDiv:
8319 case Instruction::UDiv:
8320 case Instruction::SRem:
8321 case Instruction::URem:
8322 // If we are just changing the sign, rewrite.
8323 if (DestBitSize == SrcBitSize) {
8324 // Don't insert two casts if they cannot be eliminated. We allow
8325 // two casts to be inserted if the sizes are the same. This could
8326 // only be converting signedness, which is a noop.
8327 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8328 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman722b4792008-11-30 21:09:11 +00008329 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8330 Op0, DestTy, *SrcI);
8331 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8332 Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008333 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008334 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8335 }
8336 }
8337 break;
8338
8339 case Instruction::Shl:
8340 // Allow changing the sign of the source operand. Do not allow
8341 // changing the size of the shift, UNLESS the shift amount is a
8342 // constant. We must not change variable sized shifts to a smaller
8343 // size, because it is undefined to shift more bits out than exist
8344 // in the value.
8345 if (DestBitSize == SrcBitSize ||
8346 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8347 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8348 Instruction::BitCast : Instruction::Trunc);
Eli Friedman722b4792008-11-30 21:09:11 +00008349 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8350 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008351 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008352 }
8353 break;
8354 case Instruction::AShr:
8355 // If this is a signed shr, and if all bits shifted in are about to be
8356 // truncated off, turn it into an unsigned shr to allow greater
8357 // simplifications.
8358 if (DestBitSize < SrcBitSize &&
8359 isa<ConstantInt>(Op1)) {
8360 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8361 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8362 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00008363 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008364 }
8365 }
8366 break;
8367 }
8368 return 0;
8369}
8370
8371Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8372 if (Instruction *Result = commonIntCastTransforms(CI))
8373 return Result;
8374
8375 Value *Src = CI.getOperand(0);
8376 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008377 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8378 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008379
8380 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Dan Gohman2526aea2009-06-16 19:55:29 +00008381 if (DestBitWidth == 1 &&
8382 isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
Chris Lattner32177f82009-03-24 18:15:30 +00008383 Constant *One = ConstantInt::get(Src->getType(), 1);
8384 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8385 Value *Zero = Constant::getNullValue(Src->getType());
8386 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8387 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008388
Chris Lattner32177f82009-03-24 18:15:30 +00008389 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8390 ConstantInt *ShAmtV = 0;
8391 Value *ShiftOp = 0;
8392 if (Src->hasOneUse() &&
8393 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8394 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8395
8396 // Get a mask for the bits shifting in.
8397 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8398 if (MaskedValueIsZero(ShiftOp, Mask)) {
8399 if (ShAmt >= DestBitWidth) // All zeros.
8400 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8401
8402 // Okay, we can shrink this. Truncate the input, then return a new
8403 // shift.
8404 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8405 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8406 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008407 }
8408 }
8409
8410 return 0;
8411}
8412
Evan Chenge3779cf2008-03-24 00:21:34 +00008413/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8414/// in order to eliminate the icmp.
8415Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8416 bool DoXform) {
8417 // If we are just checking for a icmp eq of a single bit and zext'ing it
8418 // to an integer, then shift the bit to the appropriate place and then
8419 // cast to integer to avoid the comparison.
8420 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8421 const APInt &Op1CV = Op1C->getValue();
8422
8423 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8424 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8425 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8426 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8427 if (!DoXform) return ICI;
8428
8429 Value *In = ICI->getOperand(0);
8430 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008431 In->getType()->getScalarSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008432 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00008433 In->getName()+".lobit"),
8434 CI);
8435 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00008436 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00008437 false/*ZExt*/, "tmp", &CI);
8438
8439 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8440 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008441 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00008442 In->getName()+".not"),
8443 CI);
8444 }
8445
8446 return ReplaceInstUsesWith(CI, In);
8447 }
8448
8449
8450
8451 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8452 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8453 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8454 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8455 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8456 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8457 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8458 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8459 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8460 // This only works for EQ and NE
8461 ICI->isEquality()) {
8462 // If Op1C some other power of two, convert:
8463 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8464 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8465 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8466 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8467
8468 APInt KnownZeroMask(~KnownZero);
8469 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8470 if (!DoXform) return ICI;
8471
8472 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8473 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8474 // (X&4) == 2 --> false
8475 // (X&4) != 2 --> true
8476 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8477 Res = ConstantExpr::getZExt(Res, CI.getType());
8478 return ReplaceInstUsesWith(CI, Res);
8479 }
8480
8481 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8482 Value *In = ICI->getOperand(0);
8483 if (ShiftAmt) {
8484 // Perform a logical shr by shiftamt.
8485 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00008486 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chenge3779cf2008-03-24 00:21:34 +00008487 ConstantInt::get(In->getType(), ShiftAmt),
8488 In->getName()+".lobit"), CI);
8489 }
8490
8491 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8492 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008493 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008494 InsertNewInstBefore(cast<Instruction>(In), CI);
8495 }
8496
8497 if (CI.getType() == In->getType())
8498 return ReplaceInstUsesWith(CI, In);
8499 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008500 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008501 }
8502 }
8503 }
8504
8505 return 0;
8506}
8507
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008508Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8509 // If one of the common conversion will work ..
8510 if (Instruction *Result = commonIntCastTransforms(CI))
8511 return Result;
8512
8513 Value *Src = CI.getOperand(0);
8514
Chris Lattner215d56e2009-02-17 20:47:23 +00008515 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8516 // types and if the sizes are just right we can convert this into a logical
8517 // 'and' which will be much cheaper than the pair of casts.
8518 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8519 // Get the sizes of the types involved. We know that the intermediate type
8520 // will be smaller than A or C, but don't know the relation between A and C.
8521 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008522 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8523 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8524 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008525 // If we're actually extending zero bits, then if
8526 // SrcSize < DstSize: zext(a & mask)
8527 // SrcSize == DstSize: a & mask
8528 // SrcSize > DstSize: trunc(a) & mask
8529 if (SrcSize < DstSize) {
8530 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Dan Gohman8fd520a2009-06-15 22:12:54 +00008531 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattner215d56e2009-02-17 20:47:23 +00008532 Instruction *And =
8533 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8534 InsertNewInstBefore(And, CI);
8535 return new ZExtInst(And, CI.getType());
8536 } else if (SrcSize == DstSize) {
8537 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Dan Gohman8fd520a2009-06-15 22:12:54 +00008538 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8539 AndValue));
Chris Lattner215d56e2009-02-17 20:47:23 +00008540 } else if (SrcSize > DstSize) {
8541 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8542 InsertNewInstBefore(Trunc, CI);
8543 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Dan Gohman8fd520a2009-06-15 22:12:54 +00008544 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Trunc->getType(),
8545 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008546 }
8547 }
8548
Evan Chenge3779cf2008-03-24 00:21:34 +00008549 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8550 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008551
Evan Chenge3779cf2008-03-24 00:21:34 +00008552 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8553 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8554 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8555 // of the (zext icmp) will be transformed.
8556 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8557 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8558 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8559 (transformZExtICmp(LHS, CI, false) ||
8560 transformZExtICmp(RHS, CI, false))) {
8561 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8562 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008563 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008564 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008565 }
8566
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008567 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008568 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8569 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8570 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8571 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008572 if (TI0->getType() == CI.getType())
8573 return
8574 BinaryOperator::CreateAnd(TI0,
8575 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008576 }
8577
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008578 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8579 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8580 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8581 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8582 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8583 And->getOperand(1) == C)
8584 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8585 Value *TI0 = TI->getOperand(0);
8586 if (TI0->getType() == CI.getType()) {
8587 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8588 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8589 InsertNewInstBefore(NewAnd, *And);
8590 return BinaryOperator::CreateXor(NewAnd, ZC);
8591 }
8592 }
8593
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008594 return 0;
8595}
8596
8597Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8598 if (Instruction *I = commonIntCastTransforms(CI))
8599 return I;
8600
8601 Value *Src = CI.getOperand(0);
8602
Dan Gohman35b76162008-10-30 20:40:10 +00008603 // Canonicalize sign-extend from i1 to a select.
8604 if (Src->getType() == Type::Int1Ty)
8605 return SelectInst::Create(Src,
8606 ConstantInt::getAllOnesValue(CI.getType()),
8607 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008608
8609 // See if the value being truncated is already sign extended. If so, just
8610 // eliminate the trunc/sext pair.
8611 if (getOpcode(Src) == Instruction::Trunc) {
8612 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008613 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8614 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8615 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008616 unsigned NumSignBits = ComputeNumSignBits(Op);
8617
8618 if (OpBits == DestBits) {
8619 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8620 // bits, it is already ready.
8621 if (NumSignBits > DestBits-MidBits)
8622 return ReplaceInstUsesWith(CI, Op);
8623 } else if (OpBits < DestBits) {
8624 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8625 // bits, just sext from i32.
8626 if (NumSignBits > OpBits-MidBits)
8627 return new SExtInst(Op, CI.getType(), "tmp");
8628 } else {
8629 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8630 // bits, just truncate to i32.
8631 if (NumSignBits > OpBits-MidBits)
8632 return new TruncInst(Op, CI.getType(), "tmp");
8633 }
8634 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008635
8636 // If the input is a shl/ashr pair of a same constant, then this is a sign
8637 // extension from a smaller value. If we could trust arbitrary bitwidth
8638 // integers, we could turn this into a truncate to the smaller bit and then
8639 // use a sext for the whole extension. Since we don't, look deeper and check
8640 // for a truncate. If the source and dest are the same type, eliminate the
8641 // trunc and extend and just do shifts. For example, turn:
8642 // %a = trunc i32 %i to i8
8643 // %b = shl i8 %a, 6
8644 // %c = ashr i8 %b, 6
8645 // %d = sext i8 %c to i32
8646 // into:
8647 // %a = shl i32 %i, 30
8648 // %d = ashr i32 %a, 30
8649 Value *A = 0;
8650 ConstantInt *BA = 0, *CA = 0;
8651 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8652 m_ConstantInt(CA))) &&
8653 BA == CA && isa<TruncInst>(A)) {
8654 Value *I = cast<TruncInst>(A)->getOperand(0);
8655 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008656 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8657 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008658 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8659 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8660 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8661 CI.getName()), CI);
8662 return BinaryOperator::CreateAShr(I, ShAmtV);
8663 }
8664 }
8665
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008666 return 0;
8667}
8668
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008669/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8670/// in the specified FP type without changing its value.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008671static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008672 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008673 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008674 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8675 if (!losesInfo)
Chris Lattner5e0610f2008-04-20 00:41:09 +00008676 return ConstantFP::get(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008677 return 0;
8678}
8679
8680/// LookThroughFPExtensions - If this is an fp extension instruction, look
8681/// through it until we get the source value.
8682static Value *LookThroughFPExtensions(Value *V) {
8683 if (Instruction *I = dyn_cast<Instruction>(V))
8684 if (I->getOpcode() == Instruction::FPExt)
8685 return LookThroughFPExtensions(I->getOperand(0));
8686
8687 // If this value is a constant, return the constant in the smallest FP type
8688 // that can accurately represent it. This allows us to turn
8689 // (float)((double)X+2.0) into x+2.0f.
8690 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8691 if (CFP->getType() == Type::PPC_FP128Ty)
8692 return V; // No constant folding of this.
8693 // See if the value can be truncated to float and then reextended.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008694 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008695 return V;
8696 if (CFP->getType() == Type::DoubleTy)
8697 return V; // Won't shrink.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008698 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008699 return V;
8700 // Don't try to shrink to various long double types.
8701 }
8702
8703 return V;
8704}
8705
8706Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8707 if (Instruction *I = commonCastTransforms(CI))
8708 return I;
8709
Dan Gohman7ce405e2009-06-04 22:49:04 +00008710 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008711 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008712 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008713 // many builtins (sqrt, etc).
8714 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8715 if (OpI && OpI->hasOneUse()) {
8716 switch (OpI->getOpcode()) {
8717 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008718 case Instruction::FAdd:
8719 case Instruction::FSub:
8720 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008721 case Instruction::FDiv:
8722 case Instruction::FRem:
8723 const Type *SrcTy = OpI->getType();
8724 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8725 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8726 if (LHSTrunc->getType() != SrcTy &&
8727 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008728 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008729 // If the source types were both smaller than the destination type of
8730 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008731 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8732 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008733 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8734 CI.getType(), CI);
8735 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8736 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008737 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008738 }
8739 }
8740 break;
8741 }
8742 }
8743 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008744}
8745
8746Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8747 return commonCastTransforms(CI);
8748}
8749
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008750Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008751 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8752 if (OpI == 0)
8753 return commonCastTransforms(FI);
8754
8755 // fptoui(uitofp(X)) --> X
8756 // fptoui(sitofp(X)) --> X
8757 // This is safe if the intermediate type has enough bits in its mantissa to
8758 // accurately represent all values of X. For example, do not do this with
8759 // i64->float->i64. This is also safe for sitofp case, because any negative
8760 // 'X' value would cause an undefined result for the fptoui.
8761 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8762 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008763 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008764 OpI->getType()->getFPMantissaWidth())
8765 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008766
8767 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008768}
8769
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008770Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008771 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8772 if (OpI == 0)
8773 return commonCastTransforms(FI);
8774
8775 // fptosi(sitofp(X)) --> X
8776 // fptosi(uitofp(X)) --> X
8777 // This is safe if the intermediate type has enough bits in its mantissa to
8778 // accurately represent all values of X. For example, do not do this with
8779 // i64->float->i64. This is also safe for sitofp case, because any negative
8780 // 'X' value would cause an undefined result for the fptoui.
8781 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8782 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008783 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008784 OpI->getType()->getFPMantissaWidth())
8785 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008786
8787 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008788}
8789
8790Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8791 return commonCastTransforms(CI);
8792}
8793
8794Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8795 return commonCastTransforms(CI);
8796}
8797
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008798Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8799 // If the destination integer type is smaller than the intptr_t type for
8800 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8801 // trunc to be exposed to other transforms. Don't do this for extending
8802 // ptrtoint's, because we don't know if the target sign or zero extends its
8803 // pointers.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008804 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008805 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8806 TD->getIntPtrType(),
8807 "tmp"), CI);
8808 return new TruncInst(P, CI.getType());
8809 }
8810
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008811 return commonPointerCastTransforms(CI);
8812}
8813
Chris Lattner7c1626482008-01-08 07:23:51 +00008814Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008815 // If the source integer type is larger than the intptr_t type for
8816 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8817 // allows the trunc to be exposed to other transforms. Don't do this for
8818 // extending inttoptr's, because we don't know if the target sign or zero
8819 // extends to pointers.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008820 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008821 TD->getPointerSizeInBits()) {
8822 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8823 TD->getIntPtrType(),
8824 "tmp"), CI);
8825 return new IntToPtrInst(P, CI.getType());
8826 }
8827
Chris Lattner7c1626482008-01-08 07:23:51 +00008828 if (Instruction *I = commonCastTransforms(CI))
8829 return I;
8830
8831 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8832 if (!DestPointee->isSized()) return 0;
8833
8834 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8835 ConstantInt *Cst;
8836 Value *X;
8837 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8838 m_ConstantInt(Cst)))) {
8839 // If the source and destination operands have the same type, see if this
8840 // is a single-index GEP.
8841 if (X->getType() == CI.getType()) {
8842 // Get the size of the pointee type.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008843 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008844
8845 // Convert the constant to intptr type.
8846 APInt Offset = Cst->getValue();
8847 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8848
8849 // If Offset is evenly divisible by Size, we can do this xform.
8850 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8851 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00008852 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00008853 }
8854 }
8855 // TODO: Could handle other cases, e.g. where add is indexing into field of
8856 // struct etc.
8857 } else if (CI.getOperand(0)->hasOneUse() &&
8858 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8859 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8860 // "inttoptr+GEP" instead of "add+intptr".
8861
8862 // Get the size of the pointee type.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008863 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008864
8865 // Convert the constant to intptr type.
8866 APInt Offset = Cst->getValue();
8867 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8868
8869 // If Offset is evenly divisible by Size, we can do this xform.
8870 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8871 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8872
8873 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8874 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008875 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00008876 }
8877 }
8878 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008879}
8880
8881Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8882 // If the operands are integer typed then apply the integer transforms,
8883 // otherwise just apply the common ones.
8884 Value *Src = CI.getOperand(0);
8885 const Type *SrcTy = Src->getType();
8886 const Type *DestTy = CI.getType();
8887
8888 if (SrcTy->isInteger() && DestTy->isInteger()) {
8889 if (Instruction *Result = commonIntCastTransforms(CI))
8890 return Result;
8891 } else if (isa<PointerType>(SrcTy)) {
8892 if (Instruction *I = commonPointerCastTransforms(CI))
8893 return I;
8894 } else {
8895 if (Instruction *Result = commonCastTransforms(CI))
8896 return Result;
8897 }
8898
8899
8900 // Get rid of casts from one type to the same type. These are useless and can
8901 // be replaced by the operand.
8902 if (DestTy == Src->getType())
8903 return ReplaceInstUsesWith(CI, Src);
8904
8905 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8906 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8907 const Type *DstElTy = DstPTy->getElementType();
8908 const Type *SrcElTy = SrcPTy->getElementType();
8909
Nate Begemandf5b3612008-03-31 00:22:16 +00008910 // If the address spaces don't match, don't eliminate the bitcast, which is
8911 // required for changing types.
8912 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8913 return 0;
8914
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008915 // If we are casting a malloc or alloca to a pointer to a type of the same
8916 // size, rewrite the allocation instruction to allocate the "right" type.
8917 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8918 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8919 return V;
8920
8921 // If the source and destination are pointers, and this cast is equivalent
8922 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8923 // This can enhance SROA and other transforms that want type-safe pointers.
8924 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8925 unsigned NumZeros = 0;
8926 while (SrcElTy != DstElTy &&
8927 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8928 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8929 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8930 ++NumZeros;
8931 }
8932
8933 // If we found a path from the src to dest, create the getelementptr now.
8934 if (SrcElTy == DstElTy) {
8935 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008936 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8937 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008938 }
8939 }
8940
8941 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8942 if (SVI->hasOneUse()) {
8943 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8944 // a bitconvert to a vector with the same # elts.
8945 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00008946 cast<VectorType>(DestTy)->getNumElements() ==
8947 SVI->getType()->getNumElements() &&
8948 SVI->getType()->getNumElements() ==
8949 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008950 CastInst *Tmp;
8951 // If either of the operands is a cast from CI.getType(), then
8952 // evaluating the shuffle in the casted destination's type will allow
8953 // us to eliminate at least one cast.
8954 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8955 Tmp->getOperand(0)->getType() == DestTy) ||
8956 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8957 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedman722b4792008-11-30 21:09:11 +00008958 Value *LHS = InsertCastBefore(Instruction::BitCast,
8959 SVI->getOperand(0), DestTy, CI);
8960 Value *RHS = InsertCastBefore(Instruction::BitCast,
8961 SVI->getOperand(1), DestTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008962 // Return a new shuffle vector. Use the same element ID's, as we
8963 // know the vector types match #elts.
8964 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8965 }
8966 }
8967 }
8968 }
8969 return 0;
8970}
8971
8972/// GetSelectFoldableOperands - We want to turn code that looks like this:
8973/// %C = or %A, %B
8974/// %D = select %cond, %C, %A
8975/// into:
8976/// %C = select %cond, %B, 0
8977/// %D = or %A, %C
8978///
8979/// Assuming that the specified instruction is an operand to the select, return
8980/// a bitmask indicating which operands of this instruction are foldable if they
8981/// equal the other incoming value of the select.
8982///
8983static unsigned GetSelectFoldableOperands(Instruction *I) {
8984 switch (I->getOpcode()) {
8985 case Instruction::Add:
8986 case Instruction::Mul:
8987 case Instruction::And:
8988 case Instruction::Or:
8989 case Instruction::Xor:
8990 return 3; // Can fold through either operand.
8991 case Instruction::Sub: // Can only fold on the amount subtracted.
8992 case Instruction::Shl: // Can only fold on the shift amount.
8993 case Instruction::LShr:
8994 case Instruction::AShr:
8995 return 1;
8996 default:
8997 return 0; // Cannot fold
8998 }
8999}
9000
9001/// GetSelectFoldableConstant - For the same transformation as the previous
9002/// function, return the identity constant that goes into the select.
9003static Constant *GetSelectFoldableConstant(Instruction *I) {
9004 switch (I->getOpcode()) {
9005 default: assert(0 && "This cannot happen!"); abort();
9006 case Instruction::Add:
9007 case Instruction::Sub:
9008 case Instruction::Or:
9009 case Instruction::Xor:
9010 case Instruction::Shl:
9011 case Instruction::LShr:
9012 case Instruction::AShr:
9013 return Constant::getNullValue(I->getType());
9014 case Instruction::And:
9015 return Constant::getAllOnesValue(I->getType());
9016 case Instruction::Mul:
9017 return ConstantInt::get(I->getType(), 1);
9018 }
9019}
9020
9021/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9022/// have the same opcode and only one use each. Try to simplify this.
9023Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9024 Instruction *FI) {
9025 if (TI->getNumOperands() == 1) {
9026 // If this is a non-volatile load or a cast from the same type,
9027 // merge.
9028 if (TI->isCast()) {
9029 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9030 return 0;
9031 } else {
9032 return 0; // unknown unary op.
9033 }
9034
9035 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009036 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9037 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009038 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009039 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009040 TI->getType());
9041 }
9042
9043 // Only handle binary operators here.
9044 if (!isa<BinaryOperator>(TI))
9045 return 0;
9046
9047 // Figure out if the operations have any operands in common.
9048 Value *MatchOp, *OtherOpT, *OtherOpF;
9049 bool MatchIsOpZero;
9050 if (TI->getOperand(0) == FI->getOperand(0)) {
9051 MatchOp = TI->getOperand(0);
9052 OtherOpT = TI->getOperand(1);
9053 OtherOpF = FI->getOperand(1);
9054 MatchIsOpZero = true;
9055 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9056 MatchOp = TI->getOperand(1);
9057 OtherOpT = TI->getOperand(0);
9058 OtherOpF = FI->getOperand(0);
9059 MatchIsOpZero = false;
9060 } else if (!TI->isCommutative()) {
9061 return 0;
9062 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9063 MatchOp = TI->getOperand(0);
9064 OtherOpT = TI->getOperand(1);
9065 OtherOpF = FI->getOperand(0);
9066 MatchIsOpZero = true;
9067 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9068 MatchOp = TI->getOperand(1);
9069 OtherOpT = TI->getOperand(0);
9070 OtherOpF = FI->getOperand(1);
9071 MatchIsOpZero = true;
9072 } else {
9073 return 0;
9074 }
9075
9076 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009077 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9078 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009079 InsertNewInstBefore(NewSI, SI);
9080
9081 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9082 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009083 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009084 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009085 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009086 }
9087 assert(0 && "Shouldn't get here");
9088 return 0;
9089}
9090
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009091static bool isSelect01(Constant *C1, Constant *C2) {
9092 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9093 if (!C1I)
9094 return false;
9095 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9096 if (!C2I)
9097 return false;
9098 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9099}
9100
9101/// FoldSelectIntoOp - Try fold the select into one of the operands to
9102/// facilitate further optimization.
9103Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9104 Value *FalseVal) {
9105 // See the comment above GetSelectFoldableOperands for a description of the
9106 // transformation we are doing here.
9107 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9108 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9109 !isa<Constant>(FalseVal)) {
9110 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9111 unsigned OpToFold = 0;
9112 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9113 OpToFold = 1;
9114 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9115 OpToFold = 2;
9116 }
9117
9118 if (OpToFold) {
9119 Constant *C = GetSelectFoldableConstant(TVI);
9120 Value *OOp = TVI->getOperand(2-OpToFold);
9121 // Avoid creating select between 2 constants unless it's selecting
9122 // between 0 and 1.
9123 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9124 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9125 InsertNewInstBefore(NewSel, SI);
9126 NewSel->takeName(TVI);
9127 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9128 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9129 assert(0 && "Unknown instruction!!");
9130 }
9131 }
9132 }
9133 }
9134 }
9135
9136 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9137 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9138 !isa<Constant>(TrueVal)) {
9139 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9140 unsigned OpToFold = 0;
9141 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9142 OpToFold = 1;
9143 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9144 OpToFold = 2;
9145 }
9146
9147 if (OpToFold) {
9148 Constant *C = GetSelectFoldableConstant(FVI);
9149 Value *OOp = FVI->getOperand(2-OpToFold);
9150 // Avoid creating select between 2 constants unless it's selecting
9151 // between 0 and 1.
9152 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9153 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9154 InsertNewInstBefore(NewSel, SI);
9155 NewSel->takeName(FVI);
9156 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9157 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9158 assert(0 && "Unknown instruction!!");
9159 }
9160 }
9161 }
9162 }
9163 }
9164
9165 return 0;
9166}
9167
Dan Gohman58c09632008-09-16 18:46:06 +00009168/// visitSelectInstWithICmp - Visit a SelectInst that has an
9169/// ICmpInst as its first operand.
9170///
9171Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9172 ICmpInst *ICI) {
9173 bool Changed = false;
9174 ICmpInst::Predicate Pred = ICI->getPredicate();
9175 Value *CmpLHS = ICI->getOperand(0);
9176 Value *CmpRHS = ICI->getOperand(1);
9177 Value *TrueVal = SI.getTrueValue();
9178 Value *FalseVal = SI.getFalseValue();
9179
9180 // Check cases where the comparison is with a constant that
9181 // can be adjusted to fit the min/max idiom. We may edit ICI in
9182 // place here, so make sure the select is the only user.
9183 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009184 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009185 switch (Pred) {
9186 default: break;
9187 case ICmpInst::ICMP_ULT:
9188 case ICmpInst::ICMP_SLT: {
9189 // X < MIN ? T : F --> F
9190 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9191 return ReplaceInstUsesWith(SI, FalseVal);
9192 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9193 Constant *AdjustedRHS = SubOne(CI);
9194 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9195 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9196 Pred = ICmpInst::getSwappedPredicate(Pred);
9197 CmpRHS = AdjustedRHS;
9198 std::swap(FalseVal, TrueVal);
9199 ICI->setPredicate(Pred);
9200 ICI->setOperand(1, CmpRHS);
9201 SI.setOperand(1, TrueVal);
9202 SI.setOperand(2, FalseVal);
9203 Changed = true;
9204 }
9205 break;
9206 }
9207 case ICmpInst::ICMP_UGT:
9208 case ICmpInst::ICMP_SGT: {
9209 // X > MAX ? T : F --> F
9210 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9211 return ReplaceInstUsesWith(SI, FalseVal);
9212 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9213 Constant *AdjustedRHS = AddOne(CI);
9214 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9215 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9216 Pred = ICmpInst::getSwappedPredicate(Pred);
9217 CmpRHS = AdjustedRHS;
9218 std::swap(FalseVal, TrueVal);
9219 ICI->setPredicate(Pred);
9220 ICI->setOperand(1, CmpRHS);
9221 SI.setOperand(1, TrueVal);
9222 SI.setOperand(2, FalseVal);
9223 Changed = true;
9224 }
9225 break;
9226 }
9227 }
9228
Dan Gohman35b76162008-10-30 20:40:10 +00009229 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9230 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009231 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner73c1ddb2009-01-05 23:53:12 +00009232 if (match(TrueVal, m_ConstantInt<-1>()) &&
9233 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009234 Pred = ICI->getPredicate();
Chris Lattner73c1ddb2009-01-05 23:53:12 +00009235 else if (match(TrueVal, m_ConstantInt<0>()) &&
9236 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009237 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9238
Dan Gohman35b76162008-10-30 20:40:10 +00009239 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9240 // If we are just checking for a icmp eq of a single bit and zext'ing it
9241 // to an integer, then shift the bit to the appropriate place and then
9242 // cast to integer to avoid the comparison.
9243 const APInt &Op1CV = CI->getValue();
9244
9245 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9246 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9247 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009248 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009249 Value *In = ICI->getOperand(0);
9250 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009251 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009252 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9253 In->getName()+".lobit"),
9254 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009255 if (In->getType() != SI.getType())
9256 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009257 true/*SExt*/, "tmp", ICI);
9258
9259 if (Pred == ICmpInst::ICMP_SGT)
9260 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9261 In->getName()+".not"), *ICI);
9262
9263 return ReplaceInstUsesWith(SI, In);
9264 }
9265 }
9266 }
9267
Dan Gohman58c09632008-09-16 18:46:06 +00009268 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9269 // Transform (X == Y) ? X : Y -> Y
9270 if (Pred == ICmpInst::ICMP_EQ)
9271 return ReplaceInstUsesWith(SI, FalseVal);
9272 // Transform (X != Y) ? X : Y -> X
9273 if (Pred == ICmpInst::ICMP_NE)
9274 return ReplaceInstUsesWith(SI, TrueVal);
9275 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9276
9277 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9278 // Transform (X == Y) ? Y : X -> X
9279 if (Pred == ICmpInst::ICMP_EQ)
9280 return ReplaceInstUsesWith(SI, FalseVal);
9281 // Transform (X != Y) ? Y : X -> Y
9282 if (Pred == ICmpInst::ICMP_NE)
9283 return ReplaceInstUsesWith(SI, TrueVal);
9284 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9285 }
9286
9287 /// NOTE: if we wanted to, this is where to detect integer ABS
9288
9289 return Changed ? &SI : 0;
9290}
9291
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009292Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9293 Value *CondVal = SI.getCondition();
9294 Value *TrueVal = SI.getTrueValue();
9295 Value *FalseVal = SI.getFalseValue();
9296
9297 // select true, X, Y -> X
9298 // select false, X, Y -> Y
9299 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9300 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9301
9302 // select C, X, X -> X
9303 if (TrueVal == FalseVal)
9304 return ReplaceInstUsesWith(SI, TrueVal);
9305
9306 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9307 return ReplaceInstUsesWith(SI, FalseVal);
9308 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9309 return ReplaceInstUsesWith(SI, TrueVal);
9310 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9311 if (isa<Constant>(TrueVal))
9312 return ReplaceInstUsesWith(SI, TrueVal);
9313 else
9314 return ReplaceInstUsesWith(SI, FalseVal);
9315 }
9316
9317 if (SI.getType() == Type::Int1Ty) {
9318 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9319 if (C->getZExtValue()) {
9320 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009321 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009322 } else {
9323 // Change: A = select B, false, C --> A = and !B, C
9324 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00009325 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009326 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009327 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009328 }
9329 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9330 if (C->getZExtValue() == false) {
9331 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009332 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009333 } else {
9334 // Change: A = select B, C, true --> A = or !B, C
9335 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00009336 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009337 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009338 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009339 }
9340 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009341
9342 // select a, b, a -> a&b
9343 // select a, a, b -> a|b
9344 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009345 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009346 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009347 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009348 }
9349
9350 // Selecting between two integer constants?
9351 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9352 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9353 // select C, 1, 0 -> zext C to int
9354 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009355 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009356 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9357 // select C, 0, 1 -> zext !C to int
9358 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00009359 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009360 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009361 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009362 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009363
9364 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9365
9366 // (x <s 0) ? -1 : 0 -> ashr x, 31
9367 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9368 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9369 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9370 // The comparison constant and the result are not neccessarily the
9371 // same width. Make an all-ones value by inserting a AShr.
9372 Value *X = IC->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00009373 uint32_t Bits = X->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009374 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00009375 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009376 ShAmt, "ones");
9377 InsertNewInstBefore(SRA, SI);
Eli Friedman722b4792008-11-30 21:09:11 +00009378
9379 // Then cast to the appropriate width.
9380 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009381 }
9382 }
9383
9384
9385 // If one of the constants is zero (we know they can't both be) and we
9386 // have an icmp instruction with zero, and we have an 'and' with the
9387 // non-constant value, eliminate this whole mess. This corresponds to
9388 // cases like this: ((X & 27) ? 27 : 0)
9389 if (TrueValC->isZero() || FalseValC->isZero())
9390 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9391 cast<Constant>(IC->getOperand(1))->isNullValue())
9392 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9393 if (ICA->getOpcode() == Instruction::And &&
9394 isa<ConstantInt>(ICA->getOperand(1)) &&
9395 (ICA->getOperand(1) == TrueValC ||
9396 ICA->getOperand(1) == FalseValC) &&
9397 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9398 // Okay, now we know that everything is set up, we just don't
9399 // know whether we have a icmp_ne or icmp_eq and whether the
9400 // true or false val is the zero.
9401 bool ShouldNotVal = !TrueValC->isZero();
9402 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9403 Value *V = ICA;
9404 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009405 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009406 Instruction::Xor, V, ICA->getOperand(1)), SI);
9407 return ReplaceInstUsesWith(SI, V);
9408 }
9409 }
9410 }
9411
9412 // See if we are selecting two values based on a comparison of the two values.
9413 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9414 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9415 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009416 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9417 // This is not safe in general for floating point:
9418 // consider X== -0, Y== +0.
9419 // It becomes safe if either operand is a nonzero constant.
9420 ConstantFP *CFPt, *CFPf;
9421 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9422 !CFPt->getValueAPF().isZero()) ||
9423 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9424 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009425 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009426 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009427 // Transform (X != Y) ? X : Y -> X
9428 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9429 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009430 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009431
9432 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9433 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009434 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9435 // This is not safe in general for floating point:
9436 // consider X== -0, Y== +0.
9437 // It becomes safe if either operand is a nonzero constant.
9438 ConstantFP *CFPt, *CFPf;
9439 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9440 !CFPt->getValueAPF().isZero()) ||
9441 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9442 !CFPf->getValueAPF().isZero()))
9443 return ReplaceInstUsesWith(SI, FalseVal);
9444 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009445 // Transform (X != Y) ? Y : X -> Y
9446 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9447 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009448 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009449 }
Dan Gohman58c09632008-09-16 18:46:06 +00009450 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009451 }
9452
9453 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009454 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9455 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9456 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009457
9458 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9459 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9460 if (TI->hasOneUse() && FI->hasOneUse()) {
9461 Instruction *AddOp = 0, *SubOp = 0;
9462
9463 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9464 if (TI->getOpcode() == FI->getOpcode())
9465 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9466 return IV;
9467
9468 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9469 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009470 if ((TI->getOpcode() == Instruction::Sub &&
9471 FI->getOpcode() == Instruction::Add) ||
9472 (TI->getOpcode() == Instruction::FSub &&
9473 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009474 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009475 } else if ((FI->getOpcode() == Instruction::Sub &&
9476 TI->getOpcode() == Instruction::Add) ||
9477 (FI->getOpcode() == Instruction::FSub &&
9478 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009479 AddOp = TI; SubOp = FI;
9480 }
9481
9482 if (AddOp) {
9483 Value *OtherAddOp = 0;
9484 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9485 OtherAddOp = AddOp->getOperand(1);
9486 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9487 OtherAddOp = AddOp->getOperand(0);
9488 }
9489
9490 if (OtherAddOp) {
9491 // So at this point we know we have (Y -> OtherAddOp):
9492 // select C, (add X, Y), (sub X, Z)
9493 Value *NegVal; // Compute -Z
9494 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9495 NegVal = ConstantExpr::getNeg(C);
9496 } else {
9497 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00009498 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009499 }
9500
9501 Value *NewTrueOp = OtherAddOp;
9502 Value *NewFalseOp = NegVal;
9503 if (AddOp != TI)
9504 std::swap(NewTrueOp, NewFalseOp);
9505 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009506 SelectInst::Create(CondVal, NewTrueOp,
9507 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009508
9509 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009510 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009511 }
9512 }
9513 }
9514
9515 // See if we can fold the select into one of our operands.
9516 if (SI.getType()->isInteger()) {
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009517 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9518 if (FoldI)
9519 return FoldI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009520 }
9521
9522 if (BinaryOperator::isNot(CondVal)) {
9523 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9524 SI.setOperand(1, FalseVal);
9525 SI.setOperand(2, TrueVal);
9526 return &SI;
9527 }
9528
9529 return 0;
9530}
9531
Dan Gohman2d648bb2008-04-10 18:43:06 +00009532/// EnforceKnownAlignment - If the specified pointer points to an object that
9533/// we control, modify the object's alignment to PrefAlign. This isn't
9534/// often possible though. If alignment is important, a more reliable approach
9535/// is to simply align all global variables and allocation instructions to
9536/// their preferred alignment from the beginning.
9537///
9538static unsigned EnforceKnownAlignment(Value *V,
9539 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009540
Dan Gohman2d648bb2008-04-10 18:43:06 +00009541 User *U = dyn_cast<User>(V);
9542 if (!U) return Align;
9543
9544 switch (getOpcode(U)) {
9545 default: break;
9546 case Instruction::BitCast:
9547 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9548 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009549 // If all indexes are zero, it is just the alignment of the base pointer.
9550 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009551 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009552 if (!isa<Constant>(*i) ||
9553 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009554 AllZeroOperands = false;
9555 break;
9556 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009557
9558 if (AllZeroOperands) {
9559 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009560 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009561 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009562 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009563 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009564 }
9565
9566 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9567 // If there is a large requested alignment and we can, bump up the alignment
9568 // of the global.
9569 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009570 if (GV->getAlignment() >= PrefAlign)
9571 Align = GV->getAlignment();
9572 else {
9573 GV->setAlignment(PrefAlign);
9574 Align = PrefAlign;
9575 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009576 }
9577 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9578 // If there is a requested alignment and if this is an alloca, round up. We
9579 // don't do this for malloc, because some systems can't respect the request.
9580 if (isa<AllocaInst>(AI)) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009581 if (AI->getAlignment() >= PrefAlign)
9582 Align = AI->getAlignment();
9583 else {
9584 AI->setAlignment(PrefAlign);
9585 Align = PrefAlign;
9586 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009587 }
9588 }
9589
9590 return Align;
9591}
9592
9593/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9594/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9595/// and it is more than the alignment of the ultimate object, see if we can
9596/// increase the alignment of the ultimate object, making this check succeed.
9597unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9598 unsigned PrefAlign) {
9599 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9600 sizeof(PrefAlign) * CHAR_BIT;
9601 APInt Mask = APInt::getAllOnesValue(BitWidth);
9602 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9603 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9604 unsigned TrailZ = KnownZero.countTrailingOnes();
9605 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9606
9607 if (PrefAlign > Align)
9608 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9609
9610 // We don't need to make any adjustment.
9611 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009612}
9613
Chris Lattner00ae5132008-01-13 23:50:23 +00009614Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009615 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009616 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009617 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009618 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009619
9620 if (CopyAlign < MinAlign) {
Chris Lattner3947da72009-03-08 03:59:00 +00009621 MI->setAlignment(MinAlign);
Chris Lattner00ae5132008-01-13 23:50:23 +00009622 return MI;
9623 }
9624
9625 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9626 // load/store.
9627 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9628 if (MemOpLength == 0) return 0;
9629
Chris Lattnerc669fb62008-01-14 00:28:35 +00009630 // Source and destination pointer types are always "i8*" for intrinsic. See
9631 // if the size is something we can handle with a single primitive load/store.
9632 // A single load+store correctly handles overlapping memory in the memmove
9633 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009634 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009635 if (Size == 0) return MI; // Delete this mem transfer.
9636
9637 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009638 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009639
Chris Lattnerc669fb62008-01-14 00:28:35 +00009640 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00009641 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009642
9643 // Memcpy forces the use of i8* for the source and destination. That means
9644 // that if you're using memcpy to move one double around, you'll get a cast
9645 // from double* to i8*. We'd much rather use a double load+store rather than
9646 // an i64 load+store, here because this improves the odds that the source or
9647 // dest address will be promotable. See if we can find a better type than the
9648 // integer datatype.
9649 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9650 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9651 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9652 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9653 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009654 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009655 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9656 if (STy->getNumElements() == 1)
9657 SrcETy = STy->getElementType(0);
9658 else
9659 break;
9660 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9661 if (ATy->getNumElements() == 1)
9662 SrcETy = ATy->getElementType();
9663 else
9664 break;
9665 } else
9666 break;
9667 }
9668
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009669 if (SrcETy->isSingleValueType())
Chris Lattnerc669fb62008-01-14 00:28:35 +00009670 NewPtrTy = PointerType::getUnqual(SrcETy);
9671 }
9672 }
9673
9674
Chris Lattner00ae5132008-01-13 23:50:23 +00009675 // If the memcpy/memmove provides better alignment info than we can
9676 // infer, use it.
9677 SrcAlign = std::max(SrcAlign, CopyAlign);
9678 DstAlign = std::max(DstAlign, CopyAlign);
9679
9680 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9681 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009682 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9683 InsertNewInstBefore(L, *MI);
9684 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9685
9686 // Set the size of the copy to 0, it will be deleted on the next iteration.
9687 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9688 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009689}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009690
Chris Lattner5af8a912008-04-30 06:39:11 +00009691Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9692 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009693 if (MI->getAlignment() < Alignment) {
9694 MI->setAlignment(Alignment);
Chris Lattner5af8a912008-04-30 06:39:11 +00009695 return MI;
9696 }
9697
9698 // Extract the length and alignment and fill if they are constant.
9699 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9700 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9701 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9702 return 0;
9703 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009704 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009705
9706 // If the length is zero, this is a no-op
9707 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9708
9709 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9710 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9711 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9712
9713 Value *Dest = MI->getDest();
9714 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9715
9716 // Alignment 0 is identity for alignment 1 for memset, but not store.
9717 if (Alignment == 0) Alignment = 1;
9718
9719 // Extract the fill value and store.
9720 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9721 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9722 Alignment), *MI);
9723
9724 // Set the size of the copy to 0, it will be deleted on the next iteration.
9725 MI->setLength(Constant::getNullValue(LenC->getType()));
9726 return MI;
9727 }
9728
9729 return 0;
9730}
9731
9732
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009733/// visitCallInst - CallInst simplification. This mostly only handles folding
9734/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9735/// the heavy lifting.
9736///
9737Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraa295aa2009-05-13 17:39:14 +00009738 // If the caller function is nounwind, mark the call as nounwind, even if the
9739 // callee isn't.
9740 if (CI.getParent()->getParent()->doesNotThrow() &&
9741 !CI.doesNotThrow()) {
9742 CI.setDoesNotThrow();
9743 return &CI;
9744 }
9745
9746
9747
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009748 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9749 if (!II) return visitCallSite(&CI);
9750
9751 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9752 // visitCallSite.
9753 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9754 bool Changed = false;
9755
9756 // memmove/cpy/set of zero bytes is a noop.
9757 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9758 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9759
9760 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9761 if (CI->getZExtValue() == 1) {
9762 // Replace the instruction with just byte operations. We would
9763 // transform other cases to loads/stores, but we don't know if
9764 // alignment is sufficient.
9765 }
9766 }
9767
9768 // If we have a memmove and the source operation is a constant global,
9769 // then the source and dest pointers can't alias, so we can change this
9770 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009771 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009772 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9773 if (GVSrc->isConstant()) {
9774 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009775 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9776 const Type *Tys[1];
9777 Tys[0] = CI.getOperand(3)->getType();
9778 CI.setOperand(0,
9779 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009780 Changed = true;
9781 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009782
9783 // memmove(x,x,size) -> noop.
9784 if (MMI->getSource() == MMI->getDest())
9785 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009786 }
9787
9788 // If we can determine a pointer alignment that is bigger than currently
9789 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009790 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009791 if (Instruction *I = SimplifyMemTransfer(MI))
9792 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009793 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9794 if (Instruction *I = SimplifyMemSet(MSI))
9795 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009796 }
9797
9798 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009799 }
9800
9801 switch (II->getIntrinsicID()) {
9802 default: break;
9803 case Intrinsic::bswap:
9804 // bswap(bswap(x)) -> x
9805 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9806 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9807 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9808 break;
9809 case Intrinsic::ppc_altivec_lvx:
9810 case Intrinsic::ppc_altivec_lvxl:
9811 case Intrinsic::x86_sse_loadu_ps:
9812 case Intrinsic::x86_sse2_loadu_pd:
9813 case Intrinsic::x86_sse2_loadu_dq:
9814 // Turn PPC lvx -> load if the pointer is known aligned.
9815 // Turn X86 loadups -> load if the pointer is known aligned.
9816 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9817 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9818 PointerType::getUnqual(II->getType()),
9819 CI);
9820 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009821 }
Chris Lattner989ba312008-06-18 04:33:20 +00009822 break;
9823 case Intrinsic::ppc_altivec_stvx:
9824 case Intrinsic::ppc_altivec_stvxl:
9825 // Turn stvx -> store if the pointer is known aligned.
9826 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9827 const Type *OpPtrTy =
9828 PointerType::getUnqual(II->getOperand(1)->getType());
9829 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9830 return new StoreInst(II->getOperand(1), Ptr);
9831 }
9832 break;
9833 case Intrinsic::x86_sse_storeu_ps:
9834 case Intrinsic::x86_sse2_storeu_pd:
9835 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009836 // Turn X86 storeu -> store if the pointer is known aligned.
9837 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9838 const Type *OpPtrTy =
9839 PointerType::getUnqual(II->getOperand(2)->getType());
9840 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9841 return new StoreInst(II->getOperand(2), Ptr);
9842 }
9843 break;
9844
9845 case Intrinsic::x86_sse_cvttss2si: {
9846 // These intrinsics only demands the 0th element of its input vector. If
9847 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00009848 unsigned VWidth =
9849 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9850 APInt DemandedElts(VWidth, 1);
9851 APInt UndefElts(VWidth, 0);
9852 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00009853 UndefElts)) {
9854 II->setOperand(1, V);
9855 return II;
9856 }
9857 break;
9858 }
9859
9860 case Intrinsic::ppc_altivec_vperm:
9861 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9862 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9863 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009864
Chris Lattner989ba312008-06-18 04:33:20 +00009865 // Check that all of the elements are integer constants or undefs.
9866 bool AllEltsOk = true;
9867 for (unsigned i = 0; i != 16; ++i) {
9868 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9869 !isa<UndefValue>(Mask->getOperand(i))) {
9870 AllEltsOk = false;
9871 break;
9872 }
9873 }
9874
9875 if (AllEltsOk) {
9876 // Cast the input vectors to byte vectors.
9877 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9878 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9879 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009880
Chris Lattner989ba312008-06-18 04:33:20 +00009881 // Only extract each element once.
9882 Value *ExtractedElts[32];
9883 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9884
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009885 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00009886 if (isa<UndefValue>(Mask->getOperand(i)))
9887 continue;
9888 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9889 Idx &= 31; // Match the hardware behavior.
9890
9891 if (ExtractedElts[Idx] == 0) {
9892 Instruction *Elt =
9893 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9894 InsertNewInstBefore(Elt, CI);
9895 ExtractedElts[Idx] = Elt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009896 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009897
Chris Lattner989ba312008-06-18 04:33:20 +00009898 // Insert this value into the result vector.
9899 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9900 i, "tmp");
9901 InsertNewInstBefore(cast<Instruction>(Result), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009902 }
Chris Lattner989ba312008-06-18 04:33:20 +00009903 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009904 }
Chris Lattner989ba312008-06-18 04:33:20 +00009905 }
9906 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009907
Chris Lattner989ba312008-06-18 04:33:20 +00009908 case Intrinsic::stackrestore: {
9909 // If the save is right next to the restore, remove the restore. This can
9910 // happen when variable allocas are DCE'd.
9911 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9912 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9913 BasicBlock::iterator BI = SS;
9914 if (&*++BI == II)
9915 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009916 }
Chris Lattner989ba312008-06-18 04:33:20 +00009917 }
9918
9919 // Scan down this block to see if there is another stack restore in the
9920 // same block without an intervening call/alloca.
9921 BasicBlock::iterator BI = II;
9922 TerminatorInst *TI = II->getParent()->getTerminator();
9923 bool CannotRemove = false;
9924 for (++BI; &*BI != TI; ++BI) {
9925 if (isa<AllocaInst>(BI)) {
9926 CannotRemove = true;
9927 break;
9928 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00009929 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9930 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9931 // If there is a stackrestore below this one, remove this one.
9932 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9933 return EraseInstFromFunction(CI);
9934 // Otherwise, ignore the intrinsic.
9935 } else {
9936 // If we found a non-intrinsic call, we can't remove the stack
9937 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00009938 CannotRemove = true;
9939 break;
9940 }
Chris Lattner989ba312008-06-18 04:33:20 +00009941 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009942 }
Chris Lattner989ba312008-06-18 04:33:20 +00009943
9944 // If the stack restore is in a return/unwind block and if there are no
9945 // allocas or calls between the restore and the return, nuke the restore.
9946 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9947 return EraseInstFromFunction(CI);
9948 break;
9949 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009950 }
9951
9952 return visitCallSite(II);
9953}
9954
9955// InvokeInst simplification
9956//
9957Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9958 return visitCallSite(&II);
9959}
9960
Dale Johannesen96021832008-04-25 21:16:07 +00009961/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9962/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00009963static bool isSafeToEliminateVarargsCast(const CallSite CS,
9964 const CastInst * const CI,
9965 const TargetData * const TD,
9966 const int ix) {
9967 if (!CI->isLosslessCast())
9968 return false;
9969
9970 // The size of ByVal arguments is derived from the type, so we
9971 // can't change to a type with a different size. If the size were
9972 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +00009973 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +00009974 return true;
9975
9976 const Type* SrcTy =
9977 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9978 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9979 if (!SrcTy->isSized() || !DstTy->isSized())
9980 return false;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00009981 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +00009982 return false;
9983 return true;
9984}
9985
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009986// visitCallSite - Improvements for call and invoke instructions.
9987//
9988Instruction *InstCombiner::visitCallSite(CallSite CS) {
9989 bool Changed = false;
9990
9991 // If the callee is a constexpr cast of a function, attempt to move the cast
9992 // to the arguments of the call/invoke.
9993 if (transformConstExprCastCall(CS)) return 0;
9994
9995 Value *Callee = CS.getCalledValue();
9996
9997 if (Function *CalleeF = dyn_cast<Function>(Callee))
9998 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9999 Instruction *OldCall = CS.getInstruction();
10000 // If the call and callee calling conventions don't match, this call must
10001 // be unreachable, as the call is undefined.
10002 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000010003 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
10004 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010005 if (!OldCall->use_empty())
10006 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10007 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10008 return EraseInstFromFunction(*OldCall);
10009 return 0;
10010 }
10011
10012 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10013 // This instruction is not reachable, just remove it. We insert a store to
10014 // undef so that we know that this code is not reachable, despite the fact
10015 // that we can't modify the CFG here.
10016 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000010017 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010018 CS.getInstruction());
10019
10020 if (!CS.getInstruction()->use_empty())
10021 CS.getInstruction()->
10022 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10023
10024 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10025 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010026 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10027 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010028 }
10029 return EraseInstFromFunction(*CS.getInstruction());
10030 }
10031
Duncan Sands74833f22007-09-17 10:26:40 +000010032 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10033 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10034 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10035 return transformCallThroughTrampoline(CS);
10036
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010037 const PointerType *PTy = cast<PointerType>(Callee->getType());
10038 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10039 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +000010040 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010041 // See if we can optimize any arguments passed through the varargs area of
10042 // the call.
10043 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +000010044 E = CS.arg_end(); I != E; ++I, ++ix) {
10045 CastInst *CI = dyn_cast<CastInst>(*I);
10046 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10047 *I = CI->getOperand(0);
10048 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010049 }
Dale Johannesen35615462008-04-23 18:34:37 +000010050 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010051 }
10052
Duncan Sands2937e352007-12-19 21:13:37 +000010053 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010054 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010055 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010056 Changed = true;
10057 }
10058
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010059 return Changed ? CS.getInstruction() : 0;
10060}
10061
10062// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10063// attempt to move the cast to the arguments of the call/invoke.
10064//
10065bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10066 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10067 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10068 if (CE->getOpcode() != Instruction::BitCast ||
10069 !isa<Function>(CE->getOperand(0)))
10070 return false;
10071 Function *Callee = cast<Function>(CE->getOperand(0));
10072 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010073 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010074
10075 // Okay, this is a cast from a function to a different type. Unless doing so
10076 // would cause a type conversion of one of our arguments, change this call to
10077 // be a direct call with arguments casted to the appropriate types.
10078 //
10079 const FunctionType *FT = Callee->getFunctionType();
10080 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010081 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010082
Duncan Sands7901ce12008-06-01 07:38:42 +000010083 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010084 return false; // TODO: Handle multiple return values.
10085
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010086 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010087 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010088 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010089 // Conversion is ok if changing from one pointer type to another or from
10090 // a pointer to an integer of the same size.
10091 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands886cadb2008-06-17 15:55:30 +000010092 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010093 return false; // Cannot transform this return value.
10094
Duncan Sands5c489582008-01-06 10:12:28 +000010095 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010096 // void -> non-void is handled specially
Duncan Sands7901ce12008-06-01 07:38:42 +000010097 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010098 return false; // Cannot transform this return value.
10099
Chris Lattner1c8733e2008-03-12 17:45:29 +000010100 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010101 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010102 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010103 return false; // Attribute not compatible with transformed value.
10104 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010105
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010106 // If the callsite is an invoke instruction, and the return value is used by
10107 // a PHI node in a successor, we cannot change the return type of the call
10108 // because there is no place to put the cast instruction (without breaking
10109 // the critical edge). Bail out in this case.
10110 if (!Caller->use_empty())
10111 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10112 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10113 UI != E; ++UI)
10114 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10115 if (PN->getParent() == II->getNormalDest() ||
10116 PN->getParent() == II->getUnwindDest())
10117 return false;
10118 }
10119
10120 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10121 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10122
10123 CallSite::arg_iterator AI = CS.arg_begin();
10124 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10125 const Type *ParamTy = FT->getParamType(i);
10126 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010127
10128 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010129 return false; // Cannot transform this parameter value.
10130
Devang Patelf2a4a922008-09-26 22:53:05 +000010131 if (CallerPAL.getParamAttributes(i + 1)
10132 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010133 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010134
Duncan Sands7901ce12008-06-01 07:38:42 +000010135 // Converting from one pointer type to another or between a pointer and an
10136 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010137 bool isConvertible = ActTy == ParamTy ||
Duncan Sands7901ce12008-06-01 07:38:42 +000010138 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10139 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010140 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010141 }
10142
10143 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10144 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010145 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010146
Chris Lattner1c8733e2008-03-12 17:45:29 +000010147 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10148 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010149 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010150 // won't be dropping them. Check that these extra arguments have attributes
10151 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010152 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10153 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010154 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010155 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010156 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010157 return false;
10158 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010159
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010160 // Okay, we decided that this is a safe thing to do: go ahead and start
10161 // inserting cast instructions as necessary...
10162 std::vector<Value*> Args;
10163 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010164 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010165 attrVec.reserve(NumCommonArgs);
10166
10167 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010168 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010169
10170 // If the return value is not being used, the type may not be compatible
10171 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010172 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010173
10174 // Add the new return attributes.
10175 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010176 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010177
10178 AI = CS.arg_begin();
10179 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10180 const Type *ParamTy = FT->getParamType(i);
10181 if ((*AI)->getType() == ParamTy) {
10182 Args.push_back(*AI);
10183 } else {
10184 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10185 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010186 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010187 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10188 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010189
10190 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010191 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010192 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010193 }
10194
10195 // If the function takes more arguments than the call was taking, add them
10196 // now...
10197 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10198 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10199
10200 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010201 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010202 if (!FT->isVarArg()) {
10203 cerr << "WARNING: While resolving call to function '"
10204 << Callee->getName() << "' arguments were dropped!\n";
10205 } else {
10206 // Add all of the arguments in their promoted form to the arg list...
10207 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10208 const Type *PTy = getPromotedType((*AI)->getType());
10209 if (PTy != (*AI)->getType()) {
10210 // Must promote to pass through va_arg area!
10211 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10212 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010213 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010214 InsertNewInstBefore(Cast, *Caller);
10215 Args.push_back(Cast);
10216 } else {
10217 Args.push_back(*AI);
10218 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010219
Duncan Sands4ced1f82008-01-13 08:02:44 +000010220 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010221 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010222 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010223 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010224 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010225 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010226
Devang Patelf2a4a922008-09-26 22:53:05 +000010227 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10228 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10229
Duncan Sands7901ce12008-06-01 07:38:42 +000010230 if (NewRetTy == Type::VoidTy)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010231 Caller->setName(""); // Void type should not have a name.
10232
Devang Pateld222f862008-09-25 21:00:45 +000010233 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010234
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010235 Instruction *NC;
10236 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010237 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010238 Args.begin(), Args.end(),
10239 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010240 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010241 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010242 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010243 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10244 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010245 CallInst *CI = cast<CallInst>(Caller);
10246 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010247 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010248 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010249 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010250 }
10251
10252 // Insert a cast of the return type as necessary.
10253 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010254 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010255 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010256 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010257 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010258 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010259
10260 // If this is an invoke instruction, we should insert it after the first
10261 // non-phi, instruction in the normal successor block.
10262 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010263 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010264 InsertNewInstBefore(NC, *I);
10265 } else {
10266 // Otherwise, it's a call, just insert cast right after the call instr
10267 InsertNewInstBefore(NC, *Caller);
10268 }
10269 AddUsersToWorkList(*Caller);
10270 } else {
10271 NV = UndefValue::get(Caller->getType());
10272 }
10273 }
10274
10275 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10276 Caller->replaceAllUsesWith(NV);
10277 Caller->eraseFromParent();
10278 RemoveFromWorkList(Caller);
10279 return true;
10280}
10281
Duncan Sands74833f22007-09-17 10:26:40 +000010282// transformCallThroughTrampoline - Turn a call to a function created by the
10283// init_trampoline intrinsic into a direct call to the underlying function.
10284//
10285Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10286 Value *Callee = CS.getCalledValue();
10287 const PointerType *PTy = cast<PointerType>(Callee->getType());
10288 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010289 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010290
10291 // If the call already has the 'nest' attribute somewhere then give up -
10292 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010293 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010294 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010295
10296 IntrinsicInst *Tramp =
10297 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10298
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010299 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010300 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10301 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10302
Devang Pateld222f862008-09-25 21:00:45 +000010303 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010304 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010305 unsigned NestIdx = 1;
10306 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010307 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010308
10309 // Look for a parameter marked with the 'nest' attribute.
10310 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10311 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010312 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010313 // Record the parameter type and any other attributes.
10314 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010315 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010316 break;
10317 }
10318
10319 if (NestTy) {
10320 Instruction *Caller = CS.getInstruction();
10321 std::vector<Value*> NewArgs;
10322 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10323
Devang Pateld222f862008-09-25 21:00:45 +000010324 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010325 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010326
Duncan Sands74833f22007-09-17 10:26:40 +000010327 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010328 // mean appending it. Likewise for attributes.
10329
Devang Patelf2a4a922008-09-26 22:53:05 +000010330 // Add any result attributes.
10331 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010332 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010333
Duncan Sands74833f22007-09-17 10:26:40 +000010334 {
10335 unsigned Idx = 1;
10336 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10337 do {
10338 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010339 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010340 Value *NestVal = Tramp->getOperand(3);
10341 if (NestVal->getType() != NestTy)
10342 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10343 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010344 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010345 }
10346
10347 if (I == E)
10348 break;
10349
Duncan Sands48b81112008-01-14 19:52:09 +000010350 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010351 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010352 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010353 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010354 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010355
10356 ++Idx, ++I;
10357 } while (1);
10358 }
10359
Devang Patelf2a4a922008-09-26 22:53:05 +000010360 // Add any function attributes.
10361 if (Attributes Attr = Attrs.getFnAttributes())
10362 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10363
Duncan Sands74833f22007-09-17 10:26:40 +000010364 // The trampoline may have been bitcast to a bogus type (FTy).
10365 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010366 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010367
Duncan Sands74833f22007-09-17 10:26:40 +000010368 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010369 NewTypes.reserve(FTy->getNumParams()+1);
10370
Duncan Sands74833f22007-09-17 10:26:40 +000010371 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010372 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010373 {
10374 unsigned Idx = 1;
10375 FunctionType::param_iterator I = FTy->param_begin(),
10376 E = FTy->param_end();
10377
10378 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010379 if (Idx == NestIdx)
10380 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010381 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010382
10383 if (I == E)
10384 break;
10385
Duncan Sands48b81112008-01-14 19:52:09 +000010386 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010387 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010388
10389 ++Idx, ++I;
10390 } while (1);
10391 }
10392
10393 // Replace the trampoline call with a direct call. Let the generic
10394 // code sort out any function type mismatches.
10395 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010396 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +000010397 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10398 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Pateld222f862008-09-25 21:00:45 +000010399 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010400
10401 Instruction *NewCaller;
10402 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010403 NewCaller = InvokeInst::Create(NewCallee,
10404 II->getNormalDest(), II->getUnwindDest(),
10405 NewArgs.begin(), NewArgs.end(),
10406 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010407 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010408 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010409 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010410 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10411 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010412 if (cast<CallInst>(Caller)->isTailCall())
10413 cast<CallInst>(NewCaller)->setTailCall();
10414 cast<CallInst>(NewCaller)->
10415 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010416 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010417 }
10418 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10419 Caller->replaceAllUsesWith(NewCaller);
10420 Caller->eraseFromParent();
10421 RemoveFromWorkList(Caller);
10422 return 0;
10423 }
10424 }
10425
10426 // Replace the trampoline call with a direct call. Since there is no 'nest'
10427 // parameter, there is no need to adjust the argument list. Let the generic
10428 // code sort out any function type mismatches.
10429 Constant *NewCallee =
10430 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10431 CS.setCalledFunction(NewCallee);
10432 return CS.getInstruction();
10433}
10434
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010435/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10436/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10437/// and a single binop.
10438Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10439 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010440 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010441 unsigned Opc = FirstInst->getOpcode();
10442 Value *LHSVal = FirstInst->getOperand(0);
10443 Value *RHSVal = FirstInst->getOperand(1);
10444
10445 const Type *LHSType = LHSVal->getType();
10446 const Type *RHSType = RHSVal->getType();
10447
10448 // Scan to see if all operands are the same opcode, all have one use, and all
10449 // kill their operands (i.e. the operands have one use).
Chris Lattner9e1916e2008-12-01 02:34:36 +000010450 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010451 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10452 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10453 // Verify type of the LHS matches so we don't fold cmp's of different
10454 // types or GEP's with different index types.
10455 I->getOperand(0)->getType() != LHSType ||
10456 I->getOperand(1)->getType() != RHSType)
10457 return 0;
10458
10459 // If they are CmpInst instructions, check their predicates
10460 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10461 if (cast<CmpInst>(I)->getPredicate() !=
10462 cast<CmpInst>(FirstInst)->getPredicate())
10463 return 0;
10464
10465 // Keep track of which operand needs a phi node.
10466 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10467 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10468 }
10469
Chris Lattner30078012008-12-01 03:42:51 +000010470 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010471
10472 Value *InLHS = FirstInst->getOperand(0);
10473 Value *InRHS = FirstInst->getOperand(1);
10474 PHINode *NewLHS = 0, *NewRHS = 0;
10475 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010476 NewLHS = PHINode::Create(LHSType,
10477 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010478 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10479 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10480 InsertNewInstBefore(NewLHS, PN);
10481 LHSVal = NewLHS;
10482 }
10483
10484 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010485 NewRHS = PHINode::Create(RHSType,
10486 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010487 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10488 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10489 InsertNewInstBefore(NewRHS, PN);
10490 RHSVal = NewRHS;
10491 }
10492
10493 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010494 if (NewLHS || NewRHS) {
10495 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10496 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10497 if (NewLHS) {
10498 Value *NewInLHS = InInst->getOperand(0);
10499 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10500 }
10501 if (NewRHS) {
10502 Value *NewInRHS = InInst->getOperand(1);
10503 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10504 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010505 }
10506 }
10507
10508 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010509 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010510 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10511 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10512 RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010513}
10514
Chris Lattner9e1916e2008-12-01 02:34:36 +000010515Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10516 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10517
10518 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10519 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010520 // This is true if all GEP bases are allocas and if all indices into them are
10521 // constants.
10522 bool AllBasePointersAreAllocas = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010523
10524 // Scan to see if all operands are the same opcode, all have one use, and all
10525 // kill their operands (i.e. the operands have one use).
10526 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10527 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10528 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10529 GEP->getNumOperands() != FirstInst->getNumOperands())
10530 return 0;
10531
Chris Lattneradf354b2009-02-21 00:46:50 +000010532 // Keep track of whether or not all GEPs are of alloca pointers.
10533 if (AllBasePointersAreAllocas &&
10534 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10535 !GEP->hasAllConstantIndices()))
10536 AllBasePointersAreAllocas = false;
10537
Chris Lattner9e1916e2008-12-01 02:34:36 +000010538 // Compare the operand lists.
10539 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10540 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10541 continue;
10542
10543 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10544 // if one of the PHIs has a constant for the index. The index may be
10545 // substantially cheaper to compute for the constants, so making it a
10546 // variable index could pessimize the path. This also handles the case
10547 // for struct indices, which must always be constant.
10548 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10549 isa<ConstantInt>(GEP->getOperand(op)))
10550 return 0;
10551
10552 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10553 return 0;
10554 FixedOperands[op] = 0; // Needs a PHI.
10555 }
10556 }
10557
Chris Lattneradf354b2009-02-21 00:46:50 +000010558 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010559 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010560 // offset calculation, but all the predecessors will have to materialize the
10561 // stack address into a register anyway. We'd actually rather *clone* the
10562 // load up into the predecessors so that we have a load of a gep of an alloca,
10563 // which can usually all be folded into the load.
10564 if (AllBasePointersAreAllocas)
10565 return 0;
10566
Chris Lattner9e1916e2008-12-01 02:34:36 +000010567 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10568 // that is variable.
10569 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10570
10571 bool HasAnyPHIs = false;
10572 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10573 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10574 Value *FirstOp = FirstInst->getOperand(i);
10575 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10576 FirstOp->getName()+".pn");
10577 InsertNewInstBefore(NewPN, PN);
10578
10579 NewPN->reserveOperandSpace(e);
10580 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10581 OperandPhis[i] = NewPN;
10582 FixedOperands[i] = NewPN;
10583 HasAnyPHIs = true;
10584 }
10585
10586
10587 // Add all operands to the new PHIs.
10588 if (HasAnyPHIs) {
10589 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10590 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10591 BasicBlock *InBB = PN.getIncomingBlock(i);
10592
10593 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10594 if (PHINode *OpPhi = OperandPhis[op])
10595 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10596 }
10597 }
10598
10599 Value *Base = FixedOperands[0];
10600 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10601 FixedOperands.end());
10602}
10603
10604
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010605/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10606/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010607/// obvious the value of the load is not changed from the point of the load to
10608/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010609///
10610/// Finally, it is safe, but not profitable, to sink a load targetting a
10611/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10612/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010613static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010614 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10615
10616 for (++BBI; BBI != E; ++BBI)
10617 if (BBI->mayWriteToMemory())
10618 return false;
10619
10620 // Check for non-address taken alloca. If not address-taken already, it isn't
10621 // profitable to do this xform.
10622 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10623 bool isAddressTaken = false;
10624 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10625 UI != E; ++UI) {
10626 if (isa<LoadInst>(UI)) continue;
10627 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10628 // If storing TO the alloca, then the address isn't taken.
10629 if (SI->getOperand(1) == AI) continue;
10630 }
10631 isAddressTaken = true;
10632 break;
10633 }
10634
Chris Lattneradf354b2009-02-21 00:46:50 +000010635 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010636 return false;
10637 }
10638
Chris Lattneradf354b2009-02-21 00:46:50 +000010639 // If this load is a load from a GEP with a constant offset from an alloca,
10640 // then we don't want to sink it. In its present form, it will be
10641 // load [constant stack offset]. Sinking it will cause us to have to
10642 // materialize the stack addresses in each predecessor in a register only to
10643 // do a shared load from register in the successor.
10644 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10645 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10646 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10647 return false;
10648
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010649 return true;
10650}
10651
10652
10653// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10654// operator and they all are only used by the PHI, PHI together their
10655// inputs, and do the operation once, to the result of the PHI.
10656Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10657 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10658
10659 // Scan the instruction, looking for input operations that can be folded away.
10660 // If all input operands to the phi are the same instruction (e.g. a cast from
10661 // the same type or "+42") we can pull the operation through the PHI, reducing
10662 // code size and simplifying code.
10663 Constant *ConstantOp = 0;
10664 const Type *CastSrcTy = 0;
10665 bool isVolatile = false;
10666 if (isa<CastInst>(FirstInst)) {
10667 CastSrcTy = FirstInst->getOperand(0)->getType();
10668 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10669 // Can fold binop, compare or shift here if the RHS is a constant,
10670 // otherwise call FoldPHIArgBinOpIntoPHI.
10671 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10672 if (ConstantOp == 0)
10673 return FoldPHIArgBinOpIntoPHI(PN);
10674 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10675 isVolatile = LI->isVolatile();
10676 // We can't sink the load if the loaded value could be modified between the
10677 // load and the PHI.
10678 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010679 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010680 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010681
10682 // If the PHI is of volatile loads and the load block has multiple
10683 // successors, sinking it would remove a load of the volatile value from
10684 // the path through the other successor.
10685 if (isVolatile &&
10686 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10687 return 0;
10688
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010689 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010690 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010691 } else {
10692 return 0; // Cannot fold this operation.
10693 }
10694
10695 // Check to see if all arguments are the same operation.
10696 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10697 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10698 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10699 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10700 return 0;
10701 if (CastSrcTy) {
10702 if (I->getOperand(0)->getType() != CastSrcTy)
10703 return 0; // Cast operation must match.
10704 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10705 // We can't sink the load if the loaded value could be modified between
10706 // the load and the PHI.
10707 if (LI->isVolatile() != isVolatile ||
10708 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010709 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010710 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010711
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010712 // If the PHI is of volatile loads and the load block has multiple
10713 // successors, sinking it would remove a load of the volatile value from
10714 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010715 if (isVolatile &&
10716 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10717 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010718
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010719 } else if (I->getOperand(1) != ConstantOp) {
10720 return 0;
10721 }
10722 }
10723
10724 // Okay, they are all the same operation. Create a new PHI node of the
10725 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010726 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10727 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010728 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10729
10730 Value *InVal = FirstInst->getOperand(0);
10731 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10732
10733 // Add all operands to the new PHI.
10734 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10735 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10736 if (NewInVal != InVal)
10737 InVal = 0;
10738 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10739 }
10740
10741 Value *PhiVal;
10742 if (InVal) {
10743 // The new PHI unions all of the same values together. This is really
10744 // common, so we handle it intelligently here for compile-time speed.
10745 PhiVal = InVal;
10746 delete NewPN;
10747 } else {
10748 InsertNewInstBefore(NewPN, PN);
10749 PhiVal = NewPN;
10750 }
10751
10752 // Insert and return the new operation.
10753 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010754 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010755 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010756 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010757 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010758 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010759 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010760 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10761
10762 // If this was a volatile load that we are merging, make sure to loop through
10763 // and mark all the input loads as non-volatile. If we don't do this, we will
10764 // insert a new volatile load and the old ones will not be deletable.
10765 if (isVolatile)
10766 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10767 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10768
10769 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010770}
10771
10772/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10773/// that is dead.
10774static bool DeadPHICycle(PHINode *PN,
10775 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10776 if (PN->use_empty()) return true;
10777 if (!PN->hasOneUse()) return false;
10778
10779 // Remember this node, and if we find the cycle, return.
10780 if (!PotentiallyDeadPHIs.insert(PN))
10781 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010782
10783 // Don't scan crazily complex things.
10784 if (PotentiallyDeadPHIs.size() == 16)
10785 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010786
10787 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10788 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10789
10790 return false;
10791}
10792
Chris Lattner27b695d2007-11-06 21:52:06 +000010793/// PHIsEqualValue - Return true if this phi node is always equal to
10794/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10795/// z = some value; x = phi (y, z); y = phi (x, z)
10796static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10797 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10798 // See if we already saw this PHI node.
10799 if (!ValueEqualPHIs.insert(PN))
10800 return true;
10801
10802 // Don't scan crazily complex things.
10803 if (ValueEqualPHIs.size() == 16)
10804 return false;
10805
10806 // Scan the operands to see if they are either phi nodes or are equal to
10807 // the value.
10808 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10809 Value *Op = PN->getIncomingValue(i);
10810 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10811 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10812 return false;
10813 } else if (Op != NonPhiInVal)
10814 return false;
10815 }
10816
10817 return true;
10818}
10819
10820
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010821// PHINode simplification
10822//
10823Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10824 // If LCSSA is around, don't mess with Phi nodes
10825 if (MustPreserveLCSSA) return 0;
10826
10827 if (Value *V = PN.hasConstantValue())
10828 return ReplaceInstUsesWith(PN, V);
10829
10830 // If all PHI operands are the same operation, pull them through the PHI,
10831 // reducing code size.
10832 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010833 isa<Instruction>(PN.getIncomingValue(1)) &&
10834 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10835 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10836 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10837 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010838 PN.getIncomingValue(0)->hasOneUse())
10839 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10840 return Result;
10841
10842 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10843 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10844 // PHI)... break the cycle.
10845 if (PN.hasOneUse()) {
10846 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10847 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10848 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10849 PotentiallyDeadPHIs.insert(&PN);
10850 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10851 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10852 }
10853
10854 // If this phi has a single use, and if that use just computes a value for
10855 // the next iteration of a loop, delete the phi. This occurs with unused
10856 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10857 // common case here is good because the only other things that catch this
10858 // are induction variable analysis (sometimes) and ADCE, which is only run
10859 // late.
10860 if (PHIUser->hasOneUse() &&
10861 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10862 PHIUser->use_back() == &PN) {
10863 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10864 }
10865 }
10866
Chris Lattner27b695d2007-11-06 21:52:06 +000010867 // We sometimes end up with phi cycles that non-obviously end up being the
10868 // same value, for example:
10869 // z = some value; x = phi (y, z); y = phi (x, z)
10870 // where the phi nodes don't necessarily need to be in the same block. Do a
10871 // quick check to see if the PHI node only contains a single non-phi value, if
10872 // so, scan to see if the phi cycle is actually equal to that value.
10873 {
10874 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10875 // Scan for the first non-phi operand.
10876 while (InValNo != NumOperandVals &&
10877 isa<PHINode>(PN.getIncomingValue(InValNo)))
10878 ++InValNo;
10879
10880 if (InValNo != NumOperandVals) {
10881 Value *NonPhiInVal = PN.getOperand(InValNo);
10882
10883 // Scan the rest of the operands to see if there are any conflicts, if so
10884 // there is no need to recursively scan other phis.
10885 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10886 Value *OpVal = PN.getIncomingValue(InValNo);
10887 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10888 break;
10889 }
10890
10891 // If we scanned over all operands, then we have one unique value plus
10892 // phi values. Scan PHI nodes to see if they all merge in each other or
10893 // the value.
10894 if (InValNo == NumOperandVals) {
10895 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10896 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10897 return ReplaceInstUsesWith(PN, NonPhiInVal);
10898 }
10899 }
10900 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010901 return 0;
10902}
10903
10904static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10905 Instruction *InsertPoint,
10906 InstCombiner *IC) {
Dan Gohman8fd520a2009-06-15 22:12:54 +000010907 unsigned PtrSize = DTy->getScalarSizeInBits();
10908 unsigned VTySize = V->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010909 // We must cast correctly to the pointer type. Ensure that we
10910 // sign extend the integer value if it is smaller as this is
10911 // used for address computation.
10912 Instruction::CastOps opcode =
10913 (VTySize < PtrSize ? Instruction::SExt :
10914 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10915 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10916}
10917
10918
10919Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10920 Value *PtrOp = GEP.getOperand(0);
10921 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10922 // If so, eliminate the noop.
10923 if (GEP.getNumOperands() == 1)
10924 return ReplaceInstUsesWith(GEP, PtrOp);
10925
10926 if (isa<UndefValue>(GEP.getOperand(0)))
10927 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10928
10929 bool HasZeroPointerIndex = false;
10930 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10931 HasZeroPointerIndex = C->isNullValue();
10932
10933 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10934 return ReplaceInstUsesWith(GEP, PtrOp);
10935
10936 // Eliminate unneeded casts for indices.
10937 bool MadeChange = false;
10938
10939 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif17396002008-06-12 21:37:33 +000010940 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10941 i != e; ++i, ++GTI) {
Sanjiv Gupta7f712d82009-04-24 02:37:54 +000010942 if (isa<SequentialType>(*GTI)) {
Gabor Greif17396002008-06-12 21:37:33 +000010943 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010944 if (CI->getOpcode() == Instruction::ZExt ||
10945 CI->getOpcode() == Instruction::SExt) {
10946 const Type *SrcTy = CI->getOperand(0)->getType();
10947 // We can eliminate a cast from i32 to i64 iff the target
10948 // is a 32-bit pointer target.
Dan Gohman8fd520a2009-06-15 22:12:54 +000010949 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010950 MadeChange = true;
Gabor Greif17396002008-06-12 21:37:33 +000010951 *i = CI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010952 }
10953 }
10954 }
10955 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman5d639ed2008-09-11 23:06:38 +000010956 // to what we need. If narrower, sign-extend it to what we need.
10957 // If the incoming value needs a cast instruction,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010958 // insert it. This explicit cast can make subsequent optimizations more
10959 // obvious.
Gabor Greif17396002008-06-12 21:37:33 +000010960 Value *Op = *i;
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010961 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010962 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif17396002008-06-12 21:37:33 +000010963 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010964 MadeChange = true;
10965 } else {
10966 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10967 GEP);
Gabor Greif17396002008-06-12 21:37:33 +000010968 *i = Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010969 MadeChange = true;
10970 }
Dan Gohman5d639ed2008-09-11 23:06:38 +000010971 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10972 if (Constant *C = dyn_cast<Constant>(Op)) {
10973 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10974 MadeChange = true;
10975 } else {
10976 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10977 GEP);
10978 *i = Op;
10979 MadeChange = true;
10980 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010981 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010982 }
10983 }
10984 if (MadeChange) return &GEP;
10985
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010986 // Combine Indices - If the source pointer to this getelementptr instruction
10987 // is a getelementptr instruction, combine the indices of the two
10988 // getelementptr instructions into a single instruction.
10989 //
10990 SmallVector<Value*, 8> SrcGEPOperands;
10991 if (User *Src = dyn_castGetElementPtr(PtrOp))
10992 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10993
10994 if (!SrcGEPOperands.empty()) {
10995 // Note that if our source is a gep chain itself that we wait for that
10996 // chain to be resolved before we perform this transformation. This
10997 // avoids us creating a TON of code in some cases.
10998 //
10999 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11000 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11001 return 0; // Wait until our source is folded to completion.
11002
11003 SmallVector<Value*, 8> Indices;
11004
11005 // Find out whether the last index in the source GEP is a sequential idx.
11006 bool EndsWithSequential = false;
11007 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11008 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11009 EndsWithSequential = !isa<StructType>(*I);
11010
11011 // Can we combine the two pointer arithmetics offsets?
11012 if (EndsWithSequential) {
11013 // Replace: gep (gep %P, long B), long A, ...
11014 // With: T = long A+B; gep %P, T, ...
11015 //
11016 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11017 if (SO1 == Constant::getNullValue(SO1->getType())) {
11018 Sum = GO1;
11019 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11020 Sum = SO1;
11021 } else {
11022 // If they aren't the same type, convert both to an integer of the
11023 // target's pointer size.
11024 if (SO1->getType() != GO1->getType()) {
11025 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11026 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
11027 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11028 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
11029 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011030 unsigned PS = TD->getPointerSizeInBits();
11031 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011032 // Convert GO1 to SO1's type.
11033 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11034
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011035 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011036 // Convert SO1 to GO1's type.
11037 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11038 } else {
11039 const Type *PT = TD->getIntPtrType();
11040 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11041 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11042 }
11043 }
11044 }
11045 if (isa<Constant>(SO1) && isa<Constant>(GO1))
11046 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
11047 else {
Gabor Greifa645dd32008-05-16 19:29:10 +000011048 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011049 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11050 }
11051 }
11052
11053 // Recycle the GEP we already have if possible.
11054 if (SrcGEPOperands.size() == 2) {
11055 GEP.setOperand(0, SrcGEPOperands[0]);
11056 GEP.setOperand(1, Sum);
11057 return &GEP;
11058 } else {
11059 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11060 SrcGEPOperands.end()-1);
11061 Indices.push_back(Sum);
11062 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11063 }
11064 } else if (isa<Constant>(*GEP.idx_begin()) &&
11065 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11066 SrcGEPOperands.size() != 1) {
11067 // Otherwise we can do the fold if the first index of the GEP is a zero
11068 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11069 SrcGEPOperands.end());
11070 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11071 }
11072
11073 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +000011074 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11075 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011076
11077 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11078 // GEP of global variable. If all of the indices for this GEP are
11079 // constants, we can promote this to a constexpr instead of an instruction.
11080
11081 // Scan for nonconstants...
11082 SmallVector<Constant*, 8> Indices;
11083 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11084 for (; I != E && isa<Constant>(*I); ++I)
11085 Indices.push_back(cast<Constant>(*I));
11086
11087 if (I == E) { // If they are all constants...
11088 Constant *CE = ConstantExpr::getGetElementPtr(GV,
11089 &Indices[0],Indices.size());
11090
11091 // Replace all uses of the GEP with the new constexpr...
11092 return ReplaceInstUsesWith(GEP, CE);
11093 }
11094 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
11095 if (!isa<PointerType>(X->getType())) {
11096 // Not interesting. Source pointer must be a cast from pointer.
11097 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011098 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11099 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011100 //
Duncan Sandscf866e62009-03-02 09:18:21 +000011101 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11102 // into : GEP i8* X, ...
11103 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011104 // This occurs when the program declares an array extern like "int X[];"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011105 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11106 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011107 if (const ArrayType *CATy =
11108 dyn_cast<ArrayType>(CPTy->getElementType())) {
11109 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11110 if (CATy->getElementType() == XTy->getElementType()) {
11111 // -> GEP i8* X, ...
11112 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11113 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11114 GEP.getName());
11115 } else if (const ArrayType *XATy =
11116 dyn_cast<ArrayType>(XTy->getElementType())) {
11117 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011118 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011119 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011120 // At this point, we know that the cast source type is a pointer
11121 // to an array of the same type as the destination pointer
11122 // array. Because the array type is never stepped over (there
11123 // is a leading zero) we can fold the cast into this GEP.
11124 GEP.setOperand(0, X);
11125 return &GEP;
11126 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011127 }
11128 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011129 } else if (GEP.getNumOperands() == 2) {
11130 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011131 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11132 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011133 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11134 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11135 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011136 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11137 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011138 Value *Idx[2];
11139 Idx[0] = Constant::getNullValue(Type::Int32Ty);
11140 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011141 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +000011142 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011143 // V and GEP are both pointer types --> BitCast
11144 return new BitCastInst(V, GEP.getType());
11145 }
11146
11147 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011148 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011149 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011150 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011151
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011152 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011153 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011154 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011155
11156 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11157 // allow either a mul, shift, or constant here.
11158 Value *NewIdx = 0;
11159 ConstantInt *Scale = 0;
11160 if (ArrayEltSize == 1) {
11161 NewIdx = GEP.getOperand(1);
Dan Gohman8fd520a2009-06-15 22:12:54 +000011162 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011163 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11164 NewIdx = ConstantInt::get(CI->getType(), 1);
11165 Scale = CI;
11166 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11167 if (Inst->getOpcode() == Instruction::Shl &&
11168 isa<ConstantInt>(Inst->getOperand(1))) {
11169 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11170 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Dan Gohman8fd520a2009-06-15 22:12:54 +000011171 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11172 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011173 NewIdx = Inst->getOperand(0);
11174 } else if (Inst->getOpcode() == Instruction::Mul &&
11175 isa<ConstantInt>(Inst->getOperand(1))) {
11176 Scale = cast<ConstantInt>(Inst->getOperand(1));
11177 NewIdx = Inst->getOperand(0);
11178 }
11179 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011180
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011181 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011182 // out, perform the transformation. Note, we don't know whether Scale is
11183 // signed or not. We'll use unsigned version of division/modulo
11184 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011185 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011186 Scale->getZExtValue() % ArrayEltSize == 0) {
11187 Scale = ConstantInt::get(Scale->getType(),
11188 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011189 if (Scale->getZExtValue() != 1) {
11190 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011191 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000011192 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011193 NewIdx = InsertNewInstBefore(Sc, GEP);
11194 }
11195
11196 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011197 Value *Idx[2];
11198 Idx[0] = Constant::getNullValue(Type::Int32Ty);
11199 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011200 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000011201 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011202 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11203 // The NewGEP must be pointer typed, so must the old one -> BitCast
11204 return new BitCastInst(NewGEP, GEP.getType());
11205 }
11206 }
11207 }
11208 }
Chris Lattner111ea772009-01-09 04:53:57 +000011209
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011210 /// See if we can simplify:
11211 /// X = bitcast A to B*
11212 /// Y = gep X, <...constant indices...>
11213 /// into a gep of the original struct. This is important for SROA and alias
11214 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011215 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011216 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11217 // Determine how much the GEP moves the pointer. We are guaranteed to get
11218 // a constant back from EmitGEPOffset.
11219 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11220 int64_t Offset = OffsetV->getSExtValue();
11221
11222 // If this GEP instruction doesn't move the pointer, just replace the GEP
11223 // with a bitcast of the real input to the dest type.
11224 if (Offset == 0) {
11225 // If the bitcast is of an allocation, and the allocation will be
11226 // converted to match the type of the cast, don't touch this.
11227 if (isa<AllocationInst>(BCI->getOperand(0))) {
11228 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11229 if (Instruction *I = visitBitCast(*BCI)) {
11230 if (I != BCI) {
11231 I->takeName(BCI);
11232 BCI->getParent()->getInstList().insert(BCI, I);
11233 ReplaceInstUsesWith(*BCI, I);
11234 }
11235 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011236 }
Chris Lattner111ea772009-01-09 04:53:57 +000011237 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011238 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011239 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011240
11241 // Otherwise, if the offset is non-zero, we need to find out if there is a
11242 // field at Offset in 'A's type. If so, we can pull the cast through the
11243 // GEP.
11244 SmallVector<Value*, 8> NewIndices;
11245 const Type *InTy =
11246 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11247 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
11248 Instruction *NGEP =
11249 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11250 NewIndices.end());
11251 if (NGEP->getType() == GEP.getType()) return NGEP;
11252 InsertNewInstBefore(NGEP, GEP);
11253 NGEP->takeName(&GEP);
11254 return new BitCastInst(NGEP, GEP.getType());
11255 }
Chris Lattner111ea772009-01-09 04:53:57 +000011256 }
11257 }
11258
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011259 return 0;
11260}
11261
11262Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11263 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011264 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011265 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11266 const Type *NewTy =
11267 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11268 AllocationInst *New = 0;
11269
11270 // Create and insert the replacement instruction...
11271 if (isa<MallocInst>(AI))
11272 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11273 else {
11274 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11275 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11276 }
11277
11278 InsertNewInstBefore(New, AI);
11279
11280 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011281 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011282 //
11283 BasicBlock::iterator It = New;
Dale Johannesena499d0d2009-03-11 22:19:43 +000011284 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011285
11286 // Now that I is pointing to the first non-allocation-inst in the block,
11287 // insert our getelementptr instruction...
11288 //
11289 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011290 Value *Idx[2];
11291 Idx[0] = NullIdx;
11292 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000011293 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11294 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011295
11296 // Now make everything use the getelementptr instead of the original
11297 // allocation.
11298 return ReplaceInstUsesWith(AI, V);
11299 } else if (isa<UndefValue>(AI.getArraySize())) {
11300 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11301 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011302 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011303
Dan Gohman28e78f02009-01-13 20:18:38 +000011304 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11305 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011306 // Note that we only do this for alloca's, because malloc should allocate
11307 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011308 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Dan Gohman28e78f02009-01-13 20:18:38 +000011309 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11310
11311 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11312 if (AI.getAlignment() == 0)
11313 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11314 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011315
11316 return 0;
11317}
11318
11319Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11320 Value *Op = FI.getOperand(0);
11321
11322 // free undef -> unreachable.
11323 if (isa<UndefValue>(Op)) {
11324 // Insert a new store to null because we cannot modify the CFG here.
11325 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000011326 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011327 return EraseInstFromFunction(FI);
11328 }
11329
11330 // If we have 'free null' delete the instruction. This can happen in stl code
11331 // when lots of inlining happens.
11332 if (isa<ConstantPointerNull>(Op))
11333 return EraseInstFromFunction(FI);
11334
11335 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11336 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11337 FI.setOperand(0, CI->getOperand(0));
11338 return &FI;
11339 }
11340
11341 // Change free (gep X, 0,0,0,0) into free(X)
11342 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11343 if (GEPI->hasAllZeroIndices()) {
11344 AddToWorkList(GEPI);
11345 FI.setOperand(0, GEPI->getOperand(0));
11346 return &FI;
11347 }
11348 }
11349
11350 // Change free(malloc) into nothing, if the malloc has a single use.
11351 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11352 if (MI->hasOneUse()) {
11353 EraseInstFromFunction(FI);
11354 return EraseInstFromFunction(*MI);
11355 }
11356
11357 return 0;
11358}
11359
11360
11361/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011362static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011363 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011364 User *CI = cast<User>(LI.getOperand(0));
11365 Value *CastOp = CI->getOperand(0);
11366
Nick Lewycky291c5942009-05-08 06:47:37 +000011367 if (TD) {
11368 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11369 // Instead of loading constant c string, use corresponding integer value
11370 // directly if string length is small enough.
11371 std::string Str;
11372 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11373 unsigned len = Str.length();
11374 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11375 unsigned numBits = Ty->getPrimitiveSizeInBits();
11376 // Replace LI with immediate integer store.
11377 if ((numBits >> 3) == len + 1) {
11378 APInt StrVal(numBits, 0);
11379 APInt SingleChar(numBits, 0);
11380 if (TD->isLittleEndian()) {
11381 for (signed i = len-1; i >= 0; i--) {
11382 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11383 StrVal = (StrVal << 8) | SingleChar;
11384 }
11385 } else {
11386 for (unsigned i = 0; i < len; i++) {
11387 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11388 StrVal = (StrVal << 8) | SingleChar;
11389 }
11390 // Append NULL at the end.
11391 SingleChar = 0;
Bill Wendling44a36ea2008-02-26 10:53:30 +000011392 StrVal = (StrVal << 8) | SingleChar;
11393 }
Nick Lewycky291c5942009-05-08 06:47:37 +000011394 Value *NL = ConstantInt::get(StrVal);
11395 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling44a36ea2008-02-26 10:53:30 +000011396 }
Devang Patela0f8ea82007-10-18 19:52:32 +000011397 }
11398 }
11399 }
11400
Mon P Wangbd05ed82009-02-07 22:19:29 +000011401 const PointerType *DestTy = cast<PointerType>(CI->getType());
11402 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011403 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011404
11405 // If the address spaces don't match, don't eliminate the cast.
11406 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11407 return 0;
11408
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011409 const Type *SrcPTy = SrcTy->getElementType();
11410
11411 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11412 isa<VectorType>(DestPTy)) {
11413 // If the source is an array, the code below will not succeed. Check to
11414 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11415 // constants.
11416 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11417 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11418 if (ASrcTy->getNumElements() != 0) {
11419 Value *Idxs[2];
11420 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11421 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11422 SrcTy = cast<PointerType>(CastOp->getType());
11423 SrcPTy = SrcTy->getElementType();
11424 }
11425
11426 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11427 isa<VectorType>(SrcPTy)) &&
11428 // Do not allow turning this into a load of an integer, which is then
11429 // casted to a pointer, this pessimizes pointer analysis a lot.
11430 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11431 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11432 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11433
11434 // Okay, we are casting from one integer or pointer type to another of
11435 // the same size. Instead of casting the pointer before the load, cast
11436 // the result of the loaded value.
11437 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11438 CI->getName(),
11439 LI.isVolatile()),LI);
11440 // Now cast the result of the load.
11441 return new BitCastInst(NewLoad, LI.getType());
11442 }
11443 }
11444 }
11445 return 0;
11446}
11447
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011448Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11449 Value *Op = LI.getOperand(0);
11450
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011451 // Attempt to improve the alignment.
Dan Gohman37192572009-02-16 00:44:23 +000011452 unsigned KnownAlign =
11453 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohman2d648bb2008-04-10 18:43:06 +000011454 if (KnownAlign >
11455 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11456 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011457 LI.setAlignment(KnownAlign);
11458
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011459 // load (cast X) --> cast (load X) iff safe
11460 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011461 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011462 return Res;
11463
11464 // None of the following transforms are legal for volatile loads.
11465 if (LI.isVolatile()) return 0;
11466
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011467 // Do really simple store-to-load forwarding and load CSE, to catch cases
11468 // where there are several consequtive memory accesses to the same location,
11469 // separated by a few arithmetic operations.
11470 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011471 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11472 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011473
Christopher Lamb2c175392007-12-29 07:56:53 +000011474 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11475 const Value *GEPI0 = GEPI->getOperand(0);
11476 // TODO: Consider a target hook for valid address spaces for this xform.
11477 if (isa<ConstantPointerNull>(GEPI0) &&
11478 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011479 // Insert a new store to null instruction before the load to indicate
11480 // that this code is not reachable. We do this instead of inserting
11481 // an unreachable instruction directly because we cannot modify the
11482 // CFG.
11483 new StoreInst(UndefValue::get(LI.getType()),
11484 Constant::getNullValue(Op->getType()), &LI);
11485 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11486 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011487 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011488
11489 if (Constant *C = dyn_cast<Constant>(Op)) {
11490 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000011491 // TODO: Consider a target hook for valid address spaces for this xform.
11492 if (isa<UndefValue>(C) || (C->isNullValue() &&
11493 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011494 // Insert a new store to null instruction before the load to indicate that
11495 // this code is not reachable. We do this instead of inserting an
11496 // unreachable instruction directly because we cannot modify the CFG.
11497 new StoreInst(UndefValue::get(LI.getType()),
11498 Constant::getNullValue(Op->getType()), &LI);
11499 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11500 }
11501
11502 // Instcombine load (constant global) into the value loaded.
11503 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands54e70f62009-03-21 21:27:31 +000011504 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011505 return ReplaceInstUsesWith(LI, GV->getInitializer());
11506
11507 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011508 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011509 if (CE->getOpcode() == Instruction::GetElementPtr) {
11510 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +000011511 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011512 if (Constant *V =
11513 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11514 return ReplaceInstUsesWith(LI, V);
11515 if (CE->getOperand(0)->isNullValue()) {
11516 // Insert a new store to null instruction before the load to indicate
11517 // that this code is not reachable. We do this instead of inserting
11518 // an unreachable instruction directly because we cannot modify the
11519 // CFG.
11520 new StoreInst(UndefValue::get(LI.getType()),
11521 Constant::getNullValue(Op->getType()), &LI);
11522 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11523 }
11524
11525 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000011526 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011527 return Res;
11528 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011529 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011530 }
Chris Lattner0270a112007-08-11 18:48:48 +000011531
11532 // If this load comes from anywhere in a constant global, and if the global
11533 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000011534 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands54e70f62009-03-21 21:27:31 +000011535 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner0270a112007-08-11 18:48:48 +000011536 if (GV->getInitializer()->isNullValue())
11537 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11538 else if (isa<UndefValue>(GV->getInitializer()))
11539 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11540 }
11541 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011542
11543 if (Op->hasOneUse()) {
11544 // Change select and PHI nodes to select values instead of addresses: this
11545 // helps alias analysis out a lot, allows many others simplifications, and
11546 // exposes redundancy in the code.
11547 //
11548 // Note that we cannot do the transformation unless we know that the
11549 // introduced loads cannot trap! Something like this is valid as long as
11550 // the condition is always false: load (select bool %C, int* null, int* %G),
11551 // but it would not be valid if we transformed it to load from null
11552 // unconditionally.
11553 //
11554 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11555 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11556 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11557 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11558 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11559 SI->getOperand(1)->getName()+".val"), LI);
11560 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11561 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000011562 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011563 }
11564
11565 // load (select (cond, null, P)) -> load P
11566 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11567 if (C->isNullValue()) {
11568 LI.setOperand(0, SI->getOperand(2));
11569 return &LI;
11570 }
11571
11572 // load (select (cond, P, null)) -> load P
11573 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11574 if (C->isNullValue()) {
11575 LI.setOperand(0, SI->getOperand(1));
11576 return &LI;
11577 }
11578 }
11579 }
11580 return 0;
11581}
11582
11583/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011584/// when possible. This makes it generally easy to do alias analysis and/or
11585/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011586static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11587 User *CI = cast<User>(SI.getOperand(1));
11588 Value *CastOp = CI->getOperand(0);
11589
11590 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011591 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11592 if (SrcTy == 0) return 0;
11593
11594 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011595
Chris Lattnera032c0e2009-01-16 20:08:59 +000011596 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11597 return 0;
11598
Chris Lattner54dddc72009-01-24 01:00:13 +000011599 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11600 /// to its first element. This allows us to handle things like:
11601 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11602 /// on 32-bit hosts.
11603 SmallVector<Value*, 4> NewGEPIndices;
11604
Chris Lattnera032c0e2009-01-16 20:08:59 +000011605 // If the source is an array, the code below will not succeed. Check to
11606 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11607 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011608 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11609 // Index through pointer.
11610 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11611 NewGEPIndices.push_back(Zero);
11612
11613 while (1) {
11614 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011615 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011616 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011617 NewGEPIndices.push_back(Zero);
11618 SrcPTy = STy->getElementType(0);
11619 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11620 NewGEPIndices.push_back(Zero);
11621 SrcPTy = ATy->getElementType();
11622 } else {
11623 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011624 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011625 }
11626
11627 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11628 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011629
11630 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11631 return 0;
11632
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011633 // If the pointers point into different address spaces or if they point to
11634 // values with different sizes, we can't do the transformation.
11635 if (SrcTy->getAddressSpace() !=
11636 cast<PointerType>(CI->getType())->getAddressSpace() ||
11637 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattnera032c0e2009-01-16 20:08:59 +000011638 IC.getTargetData().getTypeSizeInBits(DestPTy))
11639 return 0;
11640
11641 // Okay, we are casting from one integer or pointer type to another of
11642 // the same size. Instead of casting the pointer before
11643 // the store, cast the value to be stored.
11644 Value *NewCast;
11645 Value *SIOp0 = SI.getOperand(0);
11646 Instruction::CastOps opcode = Instruction::BitCast;
11647 const Type* CastSrcTy = SIOp0->getType();
11648 const Type* CastDstTy = SrcPTy;
11649 if (isa<PointerType>(CastDstTy)) {
11650 if (CastSrcTy->isInteger())
11651 opcode = Instruction::IntToPtr;
11652 } else if (isa<IntegerType>(CastDstTy)) {
11653 if (isa<PointerType>(SIOp0->getType()))
11654 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011655 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011656
11657 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11658 // emit a GEP to index into its first field.
11659 if (!NewGEPIndices.empty()) {
11660 if (Constant *C = dyn_cast<Constant>(CastOp))
11661 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11662 NewGEPIndices.size());
11663 else
11664 CastOp = IC.InsertNewInstBefore(
11665 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11666 NewGEPIndices.end()), SI);
11667 }
11668
Chris Lattnera032c0e2009-01-16 20:08:59 +000011669 if (Constant *C = dyn_cast<Constant>(SIOp0))
11670 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11671 else
11672 NewCast = IC.InsertNewInstBefore(
11673 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11674 SI);
11675 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011676}
11677
Chris Lattner6fd8c802008-11-27 08:56:30 +000011678/// equivalentAddressValues - Test if A and B will obviously have the same
11679/// value. This includes recognizing that %t0 and %t1 will have the same
11680/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000011681/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011682/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000011683/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011684/// %t2 = load i32* %t1
11685///
11686static bool equivalentAddressValues(Value *A, Value *B) {
11687 // Test if the values are trivially equivalent.
11688 if (A == B) return true;
11689
11690 // Test if the values come form identical arithmetic instructions.
11691 if (isa<BinaryOperator>(A) ||
11692 isa<CastInst>(A) ||
11693 isa<PHINode>(A) ||
11694 isa<GetElementPtrInst>(A))
11695 if (Instruction *BI = dyn_cast<Instruction>(B))
11696 if (cast<Instruction>(A)->isIdenticalTo(BI))
11697 return true;
11698
11699 // Otherwise they may not be equivalent.
11700 return false;
11701}
11702
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011703// If this instruction has two uses, one of which is a llvm.dbg.declare,
11704// return the llvm.dbg.declare.
11705DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11706 if (!V->hasNUses(2))
11707 return 0;
11708 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11709 UI != E; ++UI) {
11710 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11711 return DI;
11712 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11713 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11714 return DI;
11715 }
11716 }
11717 return 0;
11718}
11719
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011720Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11721 Value *Val = SI.getOperand(0);
11722 Value *Ptr = SI.getOperand(1);
11723
11724 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11725 EraseInstFromFunction(SI);
11726 ++NumCombined;
11727 return 0;
11728 }
11729
11730 // If the RHS is an alloca with a single use, zapify the store, making the
11731 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011732 // If the RHS is an alloca with a two uses, the other one being a
11733 // llvm.dbg.declare, zapify the store and the declare, making the
11734 // alloca dead. We must do this to prevent declare's from affecting
11735 // codegen.
11736 if (!SI.isVolatile()) {
11737 if (Ptr->hasOneUse()) {
11738 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011739 EraseInstFromFunction(SI);
11740 ++NumCombined;
11741 return 0;
11742 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011743 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11744 if (isa<AllocaInst>(GEP->getOperand(0))) {
11745 if (GEP->getOperand(0)->hasOneUse()) {
11746 EraseInstFromFunction(SI);
11747 ++NumCombined;
11748 return 0;
11749 }
11750 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11751 EraseInstFromFunction(*DI);
11752 EraseInstFromFunction(SI);
11753 ++NumCombined;
11754 return 0;
11755 }
11756 }
11757 }
11758 }
11759 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11760 EraseInstFromFunction(*DI);
11761 EraseInstFromFunction(SI);
11762 ++NumCombined;
11763 return 0;
11764 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011765 }
11766
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011767 // Attempt to improve the alignment.
Dan Gohman37192572009-02-16 00:44:23 +000011768 unsigned KnownAlign =
11769 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohman2d648bb2008-04-10 18:43:06 +000011770 if (KnownAlign >
11771 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11772 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011773 SI.setAlignment(KnownAlign);
11774
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011775 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011776 // stores to the same location, separated by a few arithmetic operations. This
11777 // situation often occurs with bitfield accesses.
11778 BasicBlock::iterator BBI = &SI;
11779 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11780 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000011781 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000011782 // Don't count debug info directives, lest they affect codegen,
11783 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11784 // It is necessary for correctness to skip those that feed into a
11785 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000011786 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000011787 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011788 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011789 continue;
11790 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011791
11792 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11793 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011794 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11795 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011796 ++NumDeadStore;
11797 ++BBI;
11798 EraseInstFromFunction(*PrevSI);
11799 continue;
11800 }
11801 break;
11802 }
11803
11804 // If this is a load, we have to stop. However, if the loaded value is from
11805 // the pointer we're loading and is producing the pointer we're storing,
11806 // then *this* store is dead (X = load P; store X -> P).
11807 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011808 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11809 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011810 EraseInstFromFunction(SI);
11811 ++NumCombined;
11812 return 0;
11813 }
11814 // Otherwise, this is a load from some other location. Stores before it
11815 // may not be dead.
11816 break;
11817 }
11818
11819 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011820 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011821 break;
11822 }
11823
11824
11825 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11826
11827 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner96e0a652009-06-11 17:54:56 +000011828 if (isa<ConstantPointerNull>(Ptr) &&
11829 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011830 if (!isa<UndefValue>(Val)) {
11831 SI.setOperand(0, UndefValue::get(Val->getType()));
11832 if (Instruction *U = dyn_cast<Instruction>(Val))
11833 AddToWorkList(U); // Dropped a use.
11834 ++NumCombined;
11835 }
11836 return 0; // Do not modify these!
11837 }
11838
11839 // store undef, Ptr -> noop
11840 if (isa<UndefValue>(Val)) {
11841 EraseInstFromFunction(SI);
11842 ++NumCombined;
11843 return 0;
11844 }
11845
11846 // If the pointer destination is a cast, see if we can fold the cast into the
11847 // source instead.
11848 if (isa<CastInst>(Ptr))
11849 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11850 return Res;
11851 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11852 if (CE->isCast())
11853 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11854 return Res;
11855
11856
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011857 // If this store is the last instruction in the basic block (possibly
11858 // excepting debug info instructions and the pointer bitcasts that feed
11859 // into them), and if the block ends with an unconditional branch, try
11860 // to move it to the successor block.
11861 BBI = &SI;
11862 do {
11863 ++BBI;
11864 } while (isa<DbgInfoIntrinsic>(BBI) ||
11865 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011866 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11867 if (BI->isUnconditional())
11868 if (SimplifyStoreAtEndOfBlock(SI))
11869 return 0; // xform done!
11870
11871 return 0;
11872}
11873
11874/// SimplifyStoreAtEndOfBlock - Turn things like:
11875/// if () { *P = v1; } else { *P = v2 }
11876/// into a phi node with a store in the successor.
11877///
11878/// Simplify things like:
11879/// *P = v1; if () { *P = v2; }
11880/// into a phi node with a store in the successor.
11881///
11882bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11883 BasicBlock *StoreBB = SI.getParent();
11884
11885 // Check to see if the successor block has exactly two incoming edges. If
11886 // so, see if the other predecessor contains a store to the same location.
11887 // if so, insert a PHI node (if needed) and move the stores down.
11888 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11889
11890 // Determine whether Dest has exactly two predecessors and, if so, compute
11891 // the other predecessor.
11892 pred_iterator PI = pred_begin(DestBB);
11893 BasicBlock *OtherBB = 0;
11894 if (*PI != StoreBB)
11895 OtherBB = *PI;
11896 ++PI;
11897 if (PI == pred_end(DestBB))
11898 return false;
11899
11900 if (*PI != StoreBB) {
11901 if (OtherBB)
11902 return false;
11903 OtherBB = *PI;
11904 }
11905 if (++PI != pred_end(DestBB))
11906 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000011907
11908 // Bail out if all the relevant blocks aren't distinct (this can happen,
11909 // for example, if SI is in an infinite loop)
11910 if (StoreBB == DestBB || OtherBB == DestBB)
11911 return false;
11912
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011913 // Verify that the other block ends in a branch and is not otherwise empty.
11914 BasicBlock::iterator BBI = OtherBB->getTerminator();
11915 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11916 if (!OtherBr || BBI == OtherBB->begin())
11917 return false;
11918
11919 // If the other block ends in an unconditional branch, check for the 'if then
11920 // else' case. there is an instruction before the branch.
11921 StoreInst *OtherStore = 0;
11922 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011923 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011924 // Skip over debugging info.
11925 while (isa<DbgInfoIntrinsic>(BBI) ||
11926 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11927 if (BBI==OtherBB->begin())
11928 return false;
11929 --BBI;
11930 }
11931 // If this isn't a store, or isn't a store to the same location, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011932 OtherStore = dyn_cast<StoreInst>(BBI);
11933 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11934 return false;
11935 } else {
11936 // Otherwise, the other block ended with a conditional branch. If one of the
11937 // destinations is StoreBB, then we have the if/then case.
11938 if (OtherBr->getSuccessor(0) != StoreBB &&
11939 OtherBr->getSuccessor(1) != StoreBB)
11940 return false;
11941
11942 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11943 // if/then triangle. See if there is a store to the same ptr as SI that
11944 // lives in OtherBB.
11945 for (;; --BBI) {
11946 // Check to see if we find the matching store.
11947 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11948 if (OtherStore->getOperand(1) != SI.getOperand(1))
11949 return false;
11950 break;
11951 }
Eli Friedman3a311d52008-06-13 22:02:12 +000011952 // If we find something that may be using or overwriting the stored
11953 // value, or if we run out of instructions, we can't do the xform.
11954 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011955 BBI == OtherBB->begin())
11956 return false;
11957 }
11958
11959 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000011960 // make sure nothing reads or overwrites the stored value in
11961 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011962 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11963 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000011964 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011965 return false;
11966 }
11967 }
11968
11969 // Insert a PHI node now if we need it.
11970 Value *MergedVal = OtherStore->getOperand(0);
11971 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000011972 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011973 PN->reserveOperandSpace(2);
11974 PN->addIncoming(SI.getOperand(0), SI.getParent());
11975 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11976 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11977 }
11978
11979 // Advance to a place where it is safe to insert the new store and
11980 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000011981 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011982 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11983 OtherStore->isVolatile()), *BBI);
11984
11985 // Nuke the old stores.
11986 EraseInstFromFunction(SI);
11987 EraseInstFromFunction(*OtherStore);
11988 ++NumCombined;
11989 return true;
11990}
11991
11992
11993Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11994 // Change br (not X), label True, label False to: br X, label False, True
11995 Value *X = 0;
11996 BasicBlock *TrueDest;
11997 BasicBlock *FalseDest;
11998 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11999 !isa<Constant>(X)) {
12000 // Swap Destinations and condition...
12001 BI.setCondition(X);
12002 BI.setSuccessor(0, FalseDest);
12003 BI.setSuccessor(1, TrueDest);
12004 return &BI;
12005 }
12006
12007 // Cannonicalize fcmp_one -> fcmp_oeq
12008 FCmpInst::Predicate FPred; Value *Y;
12009 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
12010 TrueDest, FalseDest)))
12011 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12012 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12013 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12014 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12015 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
12016 NewSCC->takeName(I);
12017 // Swap Destinations and condition...
12018 BI.setCondition(NewSCC);
12019 BI.setSuccessor(0, FalseDest);
12020 BI.setSuccessor(1, TrueDest);
12021 RemoveFromWorkList(I);
12022 I->eraseFromParent();
12023 AddToWorkList(NewSCC);
12024 return &BI;
12025 }
12026
12027 // Cannonicalize icmp_ne -> icmp_eq
12028 ICmpInst::Predicate IPred;
12029 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12030 TrueDest, FalseDest)))
12031 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12032 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12033 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12034 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12035 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12036 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
12037 NewSCC->takeName(I);
12038 // Swap Destinations and condition...
12039 BI.setCondition(NewSCC);
12040 BI.setSuccessor(0, FalseDest);
12041 BI.setSuccessor(1, TrueDest);
12042 RemoveFromWorkList(I);
12043 I->eraseFromParent();;
12044 AddToWorkList(NewSCC);
12045 return &BI;
12046 }
12047
12048 return 0;
12049}
12050
12051Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12052 Value *Cond = SI.getCondition();
12053 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12054 if (I->getOpcode() == Instruction::Add)
12055 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12056 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12057 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12058 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12059 AddRHS));
12060 SI.setOperand(0, I->getOperand(0));
12061 AddToWorkList(I);
12062 return &SI;
12063 }
12064 }
12065 return 0;
12066}
12067
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012068Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012069 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012070
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012071 if (!EV.hasIndices())
12072 return ReplaceInstUsesWith(EV, Agg);
12073
12074 if (Constant *C = dyn_cast<Constant>(Agg)) {
12075 if (isa<UndefValue>(C))
12076 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12077
12078 if (isa<ConstantAggregateZero>(C))
12079 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12080
12081 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12082 // Extract the element indexed by the first index out of the constant
12083 Value *V = C->getOperand(*EV.idx_begin());
12084 if (EV.getNumIndices() > 1)
12085 // Extract the remaining indices out of the constant indexed by the
12086 // first index
12087 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12088 else
12089 return ReplaceInstUsesWith(EV, V);
12090 }
12091 return 0; // Can't handle other constants
12092 }
12093 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12094 // We're extracting from an insertvalue instruction, compare the indices
12095 const unsigned *exti, *exte, *insi, *inse;
12096 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12097 exte = EV.idx_end(), inse = IV->idx_end();
12098 exti != exte && insi != inse;
12099 ++exti, ++insi) {
12100 if (*insi != *exti)
12101 // The insert and extract both reference distinctly different elements.
12102 // This means the extract is not influenced by the insert, and we can
12103 // replace the aggregate operand of the extract with the aggregate
12104 // operand of the insert. i.e., replace
12105 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12106 // %E = extractvalue { i32, { i32 } } %I, 0
12107 // with
12108 // %E = extractvalue { i32, { i32 } } %A, 0
12109 return ExtractValueInst::Create(IV->getAggregateOperand(),
12110 EV.idx_begin(), EV.idx_end());
12111 }
12112 if (exti == exte && insi == inse)
12113 // Both iterators are at the end: Index lists are identical. Replace
12114 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12115 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12116 // with "i32 42"
12117 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12118 if (exti == exte) {
12119 // The extract list is a prefix of the insert list. i.e. replace
12120 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12121 // %E = extractvalue { i32, { i32 } } %I, 1
12122 // with
12123 // %X = extractvalue { i32, { i32 } } %A, 1
12124 // %E = insertvalue { i32 } %X, i32 42, 0
12125 // by switching the order of the insert and extract (though the
12126 // insertvalue should be left in, since it may have other uses).
12127 Value *NewEV = InsertNewInstBefore(
12128 ExtractValueInst::Create(IV->getAggregateOperand(),
12129 EV.idx_begin(), EV.idx_end()),
12130 EV);
12131 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12132 insi, inse);
12133 }
12134 if (insi == inse)
12135 // The insert list is a prefix of the extract list
12136 // We can simply remove the common indices from the extract and make it
12137 // operate on the inserted value instead of the insertvalue result.
12138 // i.e., replace
12139 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12140 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12141 // with
12142 // %E extractvalue { i32 } { i32 42 }, 0
12143 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12144 exti, exte);
12145 }
12146 // Can't simplify extracts from other values. Note that nested extracts are
12147 // already simplified implicitely by the above (extract ( extract (insert) )
12148 // will be translated into extract ( insert ( extract ) ) first and then just
12149 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012150 return 0;
12151}
12152
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012153/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12154/// is to leave as a vector operation.
12155static bool CheapToScalarize(Value *V, bool isConstant) {
12156 if (isa<ConstantAggregateZero>(V))
12157 return true;
12158 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12159 if (isConstant) return true;
12160 // If all elts are the same, we can extract.
12161 Constant *Op0 = C->getOperand(0);
12162 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12163 if (C->getOperand(i) != Op0)
12164 return false;
12165 return true;
12166 }
12167 Instruction *I = dyn_cast<Instruction>(V);
12168 if (!I) return false;
12169
12170 // Insert element gets simplified to the inserted element or is deleted if
12171 // this is constant idx extract element and its a constant idx insertelt.
12172 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12173 isa<ConstantInt>(I->getOperand(2)))
12174 return true;
12175 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12176 return true;
12177 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12178 if (BO->hasOneUse() &&
12179 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12180 CheapToScalarize(BO->getOperand(1), isConstant)))
12181 return true;
12182 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12183 if (CI->hasOneUse() &&
12184 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12185 CheapToScalarize(CI->getOperand(1), isConstant)))
12186 return true;
12187
12188 return false;
12189}
12190
12191/// Read and decode a shufflevector mask.
12192///
12193/// It turns undef elements into values that are larger than the number of
12194/// elements in the input.
12195static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12196 unsigned NElts = SVI->getType()->getNumElements();
12197 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12198 return std::vector<unsigned>(NElts, 0);
12199 if (isa<UndefValue>(SVI->getOperand(2)))
12200 return std::vector<unsigned>(NElts, 2*NElts);
12201
12202 std::vector<unsigned> Result;
12203 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012204 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12205 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012206 Result.push_back(NElts*2); // undef -> 8
12207 else
Gabor Greif17396002008-06-12 21:37:33 +000012208 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012209 return Result;
12210}
12211
12212/// FindScalarElement - Given a vector and an element number, see if the scalar
12213/// value is already around as a register, for example if it were inserted then
12214/// extracted from the vector.
12215static Value *FindScalarElement(Value *V, unsigned EltNo) {
12216 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12217 const VectorType *PTy = cast<VectorType>(V->getType());
12218 unsigned Width = PTy->getNumElements();
12219 if (EltNo >= Width) // Out of range access.
12220 return UndefValue::get(PTy->getElementType());
12221
12222 if (isa<UndefValue>(V))
12223 return UndefValue::get(PTy->getElementType());
12224 else if (isa<ConstantAggregateZero>(V))
12225 return Constant::getNullValue(PTy->getElementType());
12226 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12227 return CP->getOperand(EltNo);
12228 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12229 // If this is an insert to a variable element, we don't know what it is.
12230 if (!isa<ConstantInt>(III->getOperand(2)))
12231 return 0;
12232 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12233
12234 // If this is an insert to the element we are looking for, return the
12235 // inserted value.
12236 if (EltNo == IIElt)
12237 return III->getOperand(1);
12238
12239 // Otherwise, the insertelement doesn't modify the value, recurse on its
12240 // vector input.
12241 return FindScalarElement(III->getOperand(0), EltNo);
12242 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012243 unsigned LHSWidth =
12244 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012245 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012246 if (InEl < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012247 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012248 else if (InEl < LHSWidth*2)
12249 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012250 else
12251 return UndefValue::get(PTy->getElementType());
12252 }
12253
12254 // Otherwise, we don't know.
12255 return 0;
12256}
12257
12258Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012259 // If vector val is undef, replace extract with scalar undef.
12260 if (isa<UndefValue>(EI.getOperand(0)))
12261 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12262
12263 // If vector val is constant 0, replace extract with scalar 0.
12264 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12265 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12266
12267 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012268 // If vector val is constant with all elements the same, replace EI with
12269 // that element. When the elements are not identical, we cannot replace yet
12270 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012271 Constant *op0 = C->getOperand(0);
12272 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12273 if (C->getOperand(i) != op0) {
12274 op0 = 0;
12275 break;
12276 }
12277 if (op0)
12278 return ReplaceInstUsesWith(EI, op0);
12279 }
12280
12281 // If extracting a specified index from the vector, see if we can recursively
12282 // find a previously computed scalar that was inserted into the vector.
12283 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12284 unsigned IndexVal = IdxC->getZExtValue();
12285 unsigned VectorWidth =
12286 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12287
12288 // If this is extracting an invalid index, turn this into undef, to avoid
12289 // crashing the code below.
12290 if (IndexVal >= VectorWidth)
12291 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12292
12293 // This instruction only demands the single element from the input vector.
12294 // If the input vector has a single use, simplify it based on this use
12295 // property.
12296 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012297 APInt UndefElts(VectorWidth, 0);
12298 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012299 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012300 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012301 EI.setOperand(0, V);
12302 return &EI;
12303 }
12304 }
12305
12306 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
12307 return ReplaceInstUsesWith(EI, Elt);
12308
12309 // If the this extractelement is directly using a bitcast from a vector of
12310 // the same number of elements, see if we can find the source element from
12311 // it. In this case, we will end up needing to bitcast the scalars.
12312 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12313 if (const VectorType *VT =
12314 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12315 if (VT->getNumElements() == VectorWidth)
12316 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12317 return new BitCastInst(Elt, EI.getType());
12318 }
12319 }
12320
12321 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12322 if (I->hasOneUse()) {
12323 // Push extractelement into predecessor operation if legal and
12324 // profitable to do so
12325 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12326 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12327 if (CheapToScalarize(BO, isConstantElt)) {
12328 ExtractElementInst *newEI0 =
12329 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12330 EI.getName()+".lhs");
12331 ExtractElementInst *newEI1 =
12332 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12333 EI.getName()+".rhs");
12334 InsertNewInstBefore(newEI0, EI);
12335 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000012336 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012337 }
12338 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000012339 unsigned AS =
12340 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000012341 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12342 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000012343 GetElementPtrInst *GEP =
12344 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012345 InsertNewInstBefore(GEP, EI);
12346 return new LoadInst(GEP);
12347 }
12348 }
12349 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12350 // Extracting the inserted element?
12351 if (IE->getOperand(2) == EI.getOperand(1))
12352 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12353 // If the inserted and extracted elements are constants, they must not
12354 // be the same value, extract from the pre-inserted value instead.
12355 if (isa<Constant>(IE->getOperand(2)) &&
12356 isa<Constant>(EI.getOperand(1))) {
12357 AddUsesToWorkList(EI);
12358 EI.setOperand(0, IE->getOperand(0));
12359 return &EI;
12360 }
12361 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12362 // If this is extracting an element from a shufflevector, figure out where
12363 // it came from and extract from the appropriate input element instead.
12364 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12365 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12366 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012367 unsigned LHSWidth =
12368 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12369
12370 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012371 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012372 else if (SrcIdx < LHSWidth*2) {
12373 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012374 Src = SVI->getOperand(1);
12375 } else {
12376 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12377 }
12378 return new ExtractElementInst(Src, SrcIdx);
12379 }
12380 }
12381 }
12382 return 0;
12383}
12384
12385/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12386/// elements from either LHS or RHS, return the shuffle mask and true.
12387/// Otherwise, return false.
12388static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12389 std::vector<Constant*> &Mask) {
12390 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12391 "Invalid CollectSingleShuffleElements");
12392 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12393
12394 if (isa<UndefValue>(V)) {
12395 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12396 return true;
12397 } else if (V == LHS) {
12398 for (unsigned i = 0; i != NumElts; ++i)
12399 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12400 return true;
12401 } else if (V == RHS) {
12402 for (unsigned i = 0; i != NumElts; ++i)
12403 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12404 return true;
12405 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12406 // If this is an insert of an extract from some other vector, include it.
12407 Value *VecOp = IEI->getOperand(0);
12408 Value *ScalarOp = IEI->getOperand(1);
12409 Value *IdxOp = IEI->getOperand(2);
12410
12411 if (!isa<ConstantInt>(IdxOp))
12412 return false;
12413 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12414
12415 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12416 // Okay, we can handle this if the vector we are insertinting into is
12417 // transitively ok.
12418 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12419 // If so, update the mask to reflect the inserted undef.
12420 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12421 return true;
12422 }
12423 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12424 if (isa<ConstantInt>(EI->getOperand(1)) &&
12425 EI->getOperand(0)->getType() == V->getType()) {
12426 unsigned ExtractedIdx =
12427 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12428
12429 // This must be extracting from either LHS or RHS.
12430 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12431 // Okay, we can handle this if the vector we are insertinting into is
12432 // transitively ok.
12433 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12434 // If so, update the mask to reflect the inserted value.
12435 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012436 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012437 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12438 } else {
12439 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012440 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012441 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12442
12443 }
12444 return true;
12445 }
12446 }
12447 }
12448 }
12449 }
12450 // TODO: Handle shufflevector here!
12451
12452 return false;
12453}
12454
12455/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12456/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12457/// that computes V and the LHS value of the shuffle.
12458static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12459 Value *&RHS) {
12460 assert(isa<VectorType>(V->getType()) &&
12461 (RHS == 0 || V->getType() == RHS->getType()) &&
12462 "Invalid shuffle!");
12463 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12464
12465 if (isa<UndefValue>(V)) {
12466 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12467 return V;
12468 } else if (isa<ConstantAggregateZero>(V)) {
12469 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12470 return V;
12471 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12472 // If this is an insert of an extract from some other vector, include it.
12473 Value *VecOp = IEI->getOperand(0);
12474 Value *ScalarOp = IEI->getOperand(1);
12475 Value *IdxOp = IEI->getOperand(2);
12476
12477 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12478 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12479 EI->getOperand(0)->getType() == V->getType()) {
12480 unsigned ExtractedIdx =
12481 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12482 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12483
12484 // Either the extracted from or inserted into vector must be RHSVec,
12485 // otherwise we'd end up with a shuffle of three inputs.
12486 if (EI->getOperand(0) == RHS || RHS == 0) {
12487 RHS = EI->getOperand(0);
12488 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012489 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012490 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12491 return V;
12492 }
12493
12494 if (VecOp == RHS) {
12495 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12496 // Everything but the extracted element is replaced with the RHS.
12497 for (unsigned i = 0; i != NumElts; ++i) {
12498 if (i != InsertedIdx)
12499 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12500 }
12501 return V;
12502 }
12503
12504 // If this insertelement is a chain that comes from exactly these two
12505 // vectors, return the vector and the effective shuffle.
12506 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12507 return EI->getOperand(0);
12508
12509 }
12510 }
12511 }
12512 // TODO: Handle shufflevector here!
12513
12514 // Otherwise, can't do anything fancy. Return an identity vector.
12515 for (unsigned i = 0; i != NumElts; ++i)
12516 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12517 return V;
12518}
12519
12520Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12521 Value *VecOp = IE.getOperand(0);
12522 Value *ScalarOp = IE.getOperand(1);
12523 Value *IdxOp = IE.getOperand(2);
12524
12525 // Inserting an undef or into an undefined place, remove this.
12526 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12527 ReplaceInstUsesWith(IE, VecOp);
12528
12529 // If the inserted element was extracted from some other vector, and if the
12530 // indexes are constant, try to turn this into a shufflevector operation.
12531 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12532 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12533 EI->getOperand(0)->getType() == IE.getType()) {
12534 unsigned NumVectorElts = IE.getType()->getNumElements();
12535 unsigned ExtractedIdx =
12536 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12537 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12538
12539 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12540 return ReplaceInstUsesWith(IE, VecOp);
12541
12542 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12543 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12544
12545 // If we are extracting a value from a vector, then inserting it right
12546 // back into the same place, just use the input vector.
12547 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12548 return ReplaceInstUsesWith(IE, VecOp);
12549
12550 // We could theoretically do this for ANY input. However, doing so could
12551 // turn chains of insertelement instructions into a chain of shufflevector
12552 // instructions, and right now we do not merge shufflevectors. As such,
12553 // only do this in a situation where it is clear that there is benefit.
12554 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12555 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12556 // the values of VecOp, except then one read from EIOp0.
12557 // Build a new shuffle mask.
12558 std::vector<Constant*> Mask;
12559 if (isa<UndefValue>(VecOp))
12560 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12561 else {
12562 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12563 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12564 NumVectorElts));
12565 }
12566 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12567 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12568 ConstantVector::get(Mask));
12569 }
12570
12571 // If this insertelement isn't used by some other insertelement, turn it
12572 // (and any insertelements it points to), into one big shuffle.
12573 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12574 std::vector<Constant*> Mask;
12575 Value *RHS = 0;
12576 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12577 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12578 // We now have a shuffle of LHS, RHS, Mask.
12579 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12580 }
12581 }
12582 }
12583
Eli Friedmanbefee262009-06-06 20:08:03 +000012584 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12585 APInt UndefElts(VWidth, 0);
12586 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12587 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12588 return &IE;
12589
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012590 return 0;
12591}
12592
12593
12594Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12595 Value *LHS = SVI.getOperand(0);
12596 Value *RHS = SVI.getOperand(1);
12597 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12598
12599 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012600
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012601 // Undefined shuffle mask -> undefined value.
12602 if (isa<UndefValue>(SVI.getOperand(2)))
12603 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012604
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012605 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012606
12607 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12608 return 0;
12609
Evan Cheng63295ab2009-02-03 10:05:09 +000012610 APInt UndefElts(VWidth, 0);
12611 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12612 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012613 LHS = SVI.getOperand(0);
12614 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012615 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012616 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012617
12618 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12619 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12620 if (LHS == RHS || isa<UndefValue>(LHS)) {
12621 if (isa<UndefValue>(LHS) && LHS == RHS) {
12622 // shuffle(undef,undef,mask) -> undef.
12623 return ReplaceInstUsesWith(SVI, LHS);
12624 }
12625
12626 // Remap any references to RHS to use LHS.
12627 std::vector<Constant*> Elts;
12628 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12629 if (Mask[i] >= 2*e)
12630 Elts.push_back(UndefValue::get(Type::Int32Ty));
12631 else {
12632 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012633 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012634 Mask[i] = 2*e; // Turn into undef.
Dan Gohmanbba96b92008-08-06 18:17:32 +000012635 Elts.push_back(UndefValue::get(Type::Int32Ty));
12636 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012637 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohmanbba96b92008-08-06 18:17:32 +000012638 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12639 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012640 }
12641 }
12642 SVI.setOperand(0, SVI.getOperand(1));
12643 SVI.setOperand(1, UndefValue::get(RHS->getType()));
12644 SVI.setOperand(2, ConstantVector::get(Elts));
12645 LHS = SVI.getOperand(0);
12646 RHS = SVI.getOperand(1);
12647 MadeChange = true;
12648 }
12649
12650 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12651 bool isLHSID = true, isRHSID = true;
12652
12653 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12654 if (Mask[i] >= e*2) continue; // Ignore undef values.
12655 // Is this an identity shuffle of the LHS value?
12656 isLHSID &= (Mask[i] == i);
12657
12658 // Is this an identity shuffle of the RHS value?
12659 isRHSID &= (Mask[i]-e == i);
12660 }
12661
12662 // Eliminate identity shuffles.
12663 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12664 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12665
12666 // If the LHS is a shufflevector itself, see if we can combine it with this
12667 // one without producing an unusual shuffle. Here we are really conservative:
12668 // we are absolutely afraid of producing a shuffle mask not in the input
12669 // program, because the code gen may not be smart enough to turn a merged
12670 // shuffle into two specific shuffles: it may produce worse code. As such,
12671 // we only merge two shuffles if the result is one of the two input shuffle
12672 // masks. In this case, merging the shuffles just removes one instruction,
12673 // which we know is safe. This is good for things like turning:
12674 // (splat(splat)) -> splat.
12675 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12676 if (isa<UndefValue>(RHS)) {
12677 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12678
12679 std::vector<unsigned> NewMask;
12680 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12681 if (Mask[i] >= 2*e)
12682 NewMask.push_back(2*e);
12683 else
12684 NewMask.push_back(LHSMask[Mask[i]]);
12685
12686 // If the result mask is equal to the src shuffle or this shuffle mask, do
12687 // the replacement.
12688 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000012689 unsigned LHSInNElts =
12690 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012691 std::vector<Constant*> Elts;
12692 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000012693 if (NewMask[i] >= LHSInNElts*2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012694 Elts.push_back(UndefValue::get(Type::Int32Ty));
12695 } else {
12696 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12697 }
12698 }
12699 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12700 LHSSVI->getOperand(1),
12701 ConstantVector::get(Elts));
12702 }
12703 }
12704 }
12705
12706 return MadeChange ? &SVI : 0;
12707}
12708
12709
12710
12711
12712/// TryToSinkInstruction - Try to move the specified instruction from its
12713/// current block into the beginning of DestBlock, which can only happen if it's
12714/// safe to move the instruction past all of the instructions between it and the
12715/// end of its block.
12716static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12717 assert(I->hasOneUse() && "Invariants didn't hold!");
12718
12719 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000012720 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012721 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012722
12723 // Do not sink alloca instructions out of the entry block.
12724 if (isa<AllocaInst>(I) && I->getParent() ==
12725 &DestBlock->getParent()->getEntryBlock())
12726 return false;
12727
12728 // We can only sink load instructions if there is nothing between the load and
12729 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012730 if (I->mayReadFromMemory()) {
12731 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012732 Scan != E; ++Scan)
12733 if (Scan->mayWriteToMemory())
12734 return false;
12735 }
12736
Dan Gohman514277c2008-05-23 21:05:58 +000012737 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012738
Dale Johannesen24339f12009-03-03 01:09:07 +000012739 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012740 I->moveBefore(InsertPos);
12741 ++NumSunkInst;
12742 return true;
12743}
12744
12745
12746/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12747/// all reachable code to the worklist.
12748///
12749/// This has a couple of tricks to make the code faster and more powerful. In
12750/// particular, we constant fold and DCE instructions as we go, to avoid adding
12751/// them to the worklist (this significantly speeds up instcombine on code where
12752/// many instructions are dead or constant). Additionally, if we find a branch
12753/// whose condition is a known constant, we only visit the reachable successors.
12754///
12755static void AddReachableCodeToWorklist(BasicBlock *BB,
12756 SmallPtrSet<BasicBlock*, 64> &Visited,
12757 InstCombiner &IC,
12758 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000012759 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012760 Worklist.push_back(BB);
12761
12762 while (!Worklist.empty()) {
12763 BB = Worklist.back();
12764 Worklist.pop_back();
12765
12766 // We have now visited this block! If we've already been here, ignore it.
12767 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012768
12769 DbgInfoIntrinsic *DBI_Prev = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012770 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12771 Instruction *Inst = BBI++;
12772
12773 // DCE instruction if trivially dead.
12774 if (isInstructionTriviallyDead(Inst)) {
12775 ++NumDeadInst;
12776 DOUT << "IC: DCE: " << *Inst;
12777 Inst->eraseFromParent();
12778 continue;
12779 }
12780
12781 // ConstantProp instruction if trivially constant.
12782 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12783 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12784 Inst->replaceAllUsesWith(C);
12785 ++NumConstProp;
12786 Inst->eraseFromParent();
12787 continue;
12788 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000012789
Devang Patel794140c2008-11-19 18:56:50 +000012790 // If there are two consecutive llvm.dbg.stoppoint calls then
12791 // it is likely that the optimizer deleted code in between these
12792 // two intrinsics.
12793 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12794 if (DBI_Next) {
12795 if (DBI_Prev
12796 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12797 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12798 IC.RemoveFromWorkList(DBI_Prev);
12799 DBI_Prev->eraseFromParent();
12800 }
12801 DBI_Prev = DBI_Next;
Zhou Sheng77e03b92009-02-23 10:14:11 +000012802 } else {
12803 DBI_Prev = 0;
Devang Patel794140c2008-11-19 18:56:50 +000012804 }
12805
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012806 IC.AddToWorkList(Inst);
12807 }
12808
12809 // Recursively visit successors. If this is a branch or switch on a
12810 // constant, only visit the reachable successor.
12811 TerminatorInst *TI = BB->getTerminator();
12812 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12813 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12814 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012815 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012816 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012817 continue;
12818 }
12819 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12820 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12821 // See if this is an explicit destination.
12822 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12823 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012824 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012825 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012826 continue;
12827 }
12828
12829 // Otherwise it is the default destination.
12830 Worklist.push_back(SI->getSuccessor(0));
12831 continue;
12832 }
12833 }
12834
12835 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12836 Worklist.push_back(TI->getSuccessor(i));
12837 }
12838}
12839
12840bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12841 bool Changed = false;
12842 TD = &getAnalysis<TargetData>();
12843
12844 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12845 << F.getNameStr() << "\n");
12846
12847 {
12848 // Do a depth-first traversal of the function, populate the worklist with
12849 // the reachable instructions. Ignore blocks that are not reachable. Keep
12850 // track of which blocks we visit.
12851 SmallPtrSet<BasicBlock*, 64> Visited;
12852 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12853
12854 // Do a quick scan over the function. If we find any blocks that are
12855 // unreachable, remove any instructions inside of them. This prevents
12856 // the instcombine code from having to deal with some bad special cases.
12857 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12858 if (!Visited.count(BB)) {
12859 Instruction *Term = BB->getTerminator();
12860 while (Term != BB->begin()) { // Remove instrs bottom-up
12861 BasicBlock::iterator I = Term; --I;
12862
12863 DOUT << "IC: DCE: " << *I;
Dale Johannesendf356c62009-03-10 21:19:49 +000012864 // A debug intrinsic shouldn't force another iteration if we weren't
12865 // going to do one without it.
12866 if (!isa<DbgInfoIntrinsic>(I)) {
12867 ++NumDeadInst;
12868 Changed = true;
12869 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012870 if (!I->use_empty())
12871 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12872 I->eraseFromParent();
12873 }
12874 }
12875 }
12876
12877 while (!Worklist.empty()) {
12878 Instruction *I = RemoveOneFromWorkList();
12879 if (I == 0) continue; // skip null values.
12880
12881 // Check to see if we can DCE the instruction.
12882 if (isInstructionTriviallyDead(I)) {
12883 // Add operands to the worklist.
12884 if (I->getNumOperands() < 4)
12885 AddUsesToWorkList(*I);
12886 ++NumDeadInst;
12887
12888 DOUT << "IC: DCE: " << *I;
12889
12890 I->eraseFromParent();
12891 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000012892 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012893 continue;
12894 }
12895
12896 // Instruction isn't dead, see if we can constant propagate it.
12897 if (Constant *C = ConstantFoldInstruction(I, TD)) {
12898 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12899
12900 // Add operands to the worklist.
12901 AddUsesToWorkList(*I);
12902 ReplaceInstUsesWith(*I, C);
12903
12904 ++NumConstProp;
12905 I->eraseFromParent();
12906 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000012907 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012908 continue;
12909 }
12910
Dan Gohman95b95de2009-05-07 19:43:39 +000012911 if (TD &&
12912 (I->getType()->getTypeID() == Type::VoidTyID ||
12913 I->isTrapping())) {
Nick Lewyckyadb67922008-05-25 20:56:15 +000012914 // See if we can constant fold its operands.
Chris Lattnerf6d58862009-01-31 07:04:22 +000012915 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12916 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewyckyadb67922008-05-25 20:56:15 +000012917 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattnerf6d58862009-01-31 07:04:22 +000012918 if (NewC != CE) {
12919 i->set(NewC);
12920 Changed = true;
12921 }
Nick Lewyckyadb67922008-05-25 20:56:15 +000012922 }
12923
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012924 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000012925 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012926 BasicBlock *BB = I->getParent();
12927 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12928 if (UserParent != BB) {
12929 bool UserIsSuccessor = false;
12930 // See if the user is one of our successors.
12931 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12932 if (*SI == UserParent) {
12933 UserIsSuccessor = true;
12934 break;
12935 }
12936
12937 // If the user is one of our immediate successors, and if that successor
12938 // only has us as a predecessors (we'd have to split the critical edge
12939 // otherwise), we can keep going.
12940 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12941 next(pred_begin(UserParent)) == pred_end(UserParent))
12942 // Okay, the CFG is simple enough, try to sink this instruction.
12943 Changed |= TryToSinkInstruction(I, UserParent);
12944 }
12945 }
12946
12947 // Now that we have an instruction, try combining it to simplify it...
12948#ifndef NDEBUG
12949 std::string OrigI;
12950#endif
12951 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12952 if (Instruction *Result = visit(*I)) {
12953 ++NumCombined;
12954 // Should we replace the old instruction with a new one?
12955 if (Result != I) {
12956 DOUT << "IC: Old = " << *I
12957 << " New = " << *Result;
12958
12959 // Everything uses the new instruction now.
12960 I->replaceAllUsesWith(Result);
12961
12962 // Push the new instruction and any users onto the worklist.
12963 AddToWorkList(Result);
12964 AddUsersToWorkList(*Result);
12965
12966 // Move the name to the new instruction first.
12967 Result->takeName(I);
12968
12969 // Insert the new instruction into the basic block...
12970 BasicBlock *InstParent = I->getParent();
12971 BasicBlock::iterator InsertPos = I;
12972
12973 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12974 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12975 ++InsertPos;
12976
12977 InstParent->getInstList().insert(InsertPos, Result);
12978
12979 // Make sure that we reprocess all operands now that we reduced their
12980 // use counts.
12981 AddUsesToWorkList(*I);
12982
12983 // Instructions can end up on the worklist more than once. Make sure
12984 // we do not process an instruction that has been deleted.
12985 RemoveFromWorkList(I);
12986
12987 // Erase the old instruction.
12988 InstParent->getInstList().erase(I);
12989 } else {
12990#ifndef NDEBUG
12991 DOUT << "IC: Mod = " << OrigI
12992 << " New = " << *I;
12993#endif
12994
12995 // If the instruction was modified, it's possible that it is now dead.
12996 // if so, remove it.
12997 if (isInstructionTriviallyDead(I)) {
12998 // Make sure we process all operands now that we are reducing their
12999 // use counts.
13000 AddUsesToWorkList(*I);
13001
13002 // Instructions may end up in the worklist more than once. Erase all
13003 // occurrences of this instruction.
13004 RemoveFromWorkList(I);
13005 I->eraseFromParent();
13006 } else {
13007 AddToWorkList(I);
13008 AddUsersToWorkList(*I);
13009 }
13010 }
13011 Changed = true;
13012 }
13013 }
13014
13015 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000013016
13017 // Do an explicit clear, this shrinks the map if needed.
13018 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013019 return Changed;
13020}
13021
13022
13023bool InstCombiner::runOnFunction(Function &F) {
13024 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13025
13026 bool EverMadeChange = false;
13027
13028 // Iterate while there is work to do.
13029 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000013030 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013031 EverMadeChange = true;
13032 return EverMadeChange;
13033}
13034
13035FunctionPass *llvm::createInstructionCombiningPass() {
13036 return new InstCombiner();
13037}