blob: e208d69f7c65c116542f657b412fe1c94edaa381 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman089efff2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14// This pass combines things like:
15// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
17// into:
18// %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
25// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
27// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
29// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
32// ... etc.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Scalar.h"
38#include "llvm/IntrinsicInst.h"
Owen Anderson24be4c12009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/Pass.h"
41#include "llvm/DerivedTypes.h"
42#include "llvm/GlobalVariable.h"
Dan Gohman9545fb02009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnera9333562009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandez28f4d2f2009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattnera432bc72008-06-02 01:18:21 +000047#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048#include "llvm/Target/TargetData.h"
49#include "llvm/Transforms/Utils/BasicBlockUtils.h"
50#include "llvm/Transforms/Utils/Local.h"
51#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000052#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000054#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055#include "llvm/Support/GetElementPtrTypeIterator.h"
56#include "llvm/Support/InstVisitor.h"
Chris Lattnerc7694852009-08-30 07:44:24 +000057#include "llvm/Support/IRBuilder.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000058#include "llvm/Support/MathExtras.h"
59#include "llvm/Support/PatternMatch.h"
Chris Lattneree5839b2009-10-15 04:13:44 +000060#include "llvm/Support/TargetFolder.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000061#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062#include "llvm/ADT/DenseMap.h"
63#include "llvm/ADT/SmallVector.h"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/ADT/Statistic.h"
66#include "llvm/ADT/STLExtras.h"
67#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000068#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069using namespace llvm;
70using namespace llvm::PatternMatch;
71
72STATISTIC(NumCombined , "Number of insts combined");
73STATISTIC(NumConstProp, "Number of constant folds");
74STATISTIC(NumDeadInst , "Number of dead inst eliminated");
75STATISTIC(NumDeadStore, "Number of dead stores eliminated");
76STATISTIC(NumSunkInst , "Number of instructions sunk");
77
Chris Lattner78500cb2009-12-21 06:03:05 +000078/// SelectPatternFlavor - We can match a variety of different patterns for
79/// select operations.
80enum SelectPatternFlavor {
81 SPF_UNKNOWN = 0,
82 SPF_SMIN, SPF_UMIN,
83 SPF_SMAX, SPF_UMAX
84 //SPF_ABS - TODO.
85};
86
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087namespace {
Chris Lattner5119c702009-08-30 05:55:36 +000088 /// InstCombineWorklist - This is the worklist management logic for
89 /// InstCombine.
90 class InstCombineWorklist {
91 SmallVector<Instruction*, 256> Worklist;
92 DenseMap<Instruction*, unsigned> WorklistMap;
93
94 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
95 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
96 public:
97 InstCombineWorklist() {}
98
99 bool isEmpty() const { return Worklist.empty(); }
100
101 /// Add - Add the specified instruction to the worklist if it isn't already
102 /// in it.
103 void Add(Instruction *I) {
Jeffrey Yasskin17091f02009-10-08 00:12:24 +0000104 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
105 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner5119c702009-08-30 05:55:36 +0000106 Worklist.push_back(I);
Jeffrey Yasskin17091f02009-10-08 00:12:24 +0000107 }
Chris Lattner5119c702009-08-30 05:55:36 +0000108 }
109
Chris Lattnerc5ad98f2009-08-30 06:27:41 +0000110 void AddValue(Value *V) {
111 if (Instruction *I = dyn_cast<Instruction>(V))
112 Add(I);
113 }
114
Chris Lattnerb5663c72009-10-12 03:58:40 +0000115 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
116 /// which should only be done when the worklist is empty and when the group
117 /// has no duplicates.
118 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
119 assert(Worklist.empty() && "Worklist must be empty to add initial group");
120 Worklist.reserve(NumEntries+16);
121 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
122 for (; NumEntries; --NumEntries) {
123 Instruction *I = List[NumEntries-1];
124 WorklistMap.insert(std::make_pair(I, Worklist.size()));
125 Worklist.push_back(I);
126 }
127 }
128
Chris Lattner3183fb62009-08-30 06:13:40 +0000129 // Remove - remove I from the worklist if it exists.
Chris Lattner5119c702009-08-30 05:55:36 +0000130 void Remove(Instruction *I) {
131 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
132 if (It == WorklistMap.end()) return; // Not in worklist.
133
134 // Don't bother moving everything down, just null out the slot.
135 Worklist[It->second] = 0;
136
137 WorklistMap.erase(It);
138 }
139
140 Instruction *RemoveOne() {
141 Instruction *I = Worklist.back();
142 Worklist.pop_back();
143 WorklistMap.erase(I);
144 return I;
145 }
146
Chris Lattner4796b622009-08-30 06:22:51 +0000147 /// AddUsersToWorkList - When an instruction is simplified, add all users of
148 /// the instruction to the work lists because they might get more simplified
149 /// now.
150 ///
151 void AddUsersToWorkList(Instruction &I) {
152 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
153 UI != UE; ++UI)
154 Add(cast<Instruction>(*UI));
155 }
156
Chris Lattner5119c702009-08-30 05:55:36 +0000157
158 /// Zap - check that the worklist is empty and nuke the backing store for
159 /// the map if it is large.
160 void Zap() {
161 assert(WorklistMap.empty() && "Worklist empty, but map not?");
162
163 // Do an explicit clear, this shrinks the map if needed.
164 WorklistMap.clear();
165 }
166 };
167} // end anonymous namespace.
168
169
170namespace {
Chris Lattnerc7694852009-08-30 07:44:24 +0000171 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
172 /// just like the normal insertion helper, but also adds any new instructions
173 /// to the instcombine worklist.
174 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
175 InstCombineWorklist &Worklist;
176 public:
177 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
178
179 void InsertHelper(Instruction *I, const Twine &Name,
180 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
181 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
182 Worklist.Add(I);
183 }
184 };
185} // end anonymous namespace
186
187
188namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000189 class InstCombiner : public FunctionPass,
190 public InstVisitor<InstCombiner, Instruction*> {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 TargetData *TD;
192 bool MustPreserveLCSSA;
Chris Lattner21d79e22009-08-31 06:57:37 +0000193 bool MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194 public:
Chris Lattner36ec3b42009-08-30 17:53:59 +0000195 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner3183fb62009-08-30 06:13:40 +0000196 InstCombineWorklist Worklist;
197
Chris Lattnerc7694852009-08-30 07:44:24 +0000198 /// Builder - This is an IRBuilder that automatically inserts new
199 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +0000200 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerad7516a2009-08-30 18:50:58 +0000201 BuilderTy *Builder;
Chris Lattnerc7694852009-08-30 07:44:24 +0000202
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 static char ID; // Pass identification, replacement for typeid
Chris Lattnerc7694852009-08-30 07:44:24 +0000204 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205
Owen Anderson175b6542009-07-22 00:24:57 +0000206 LLVMContext *Context;
207 LLVMContext *getContext() const { return Context; }
Owen Anderson24be4c12009-07-03 00:17:18 +0000208
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000209 public:
210 virtual bool runOnFunction(Function &F);
211
212 bool DoOneIteration(Function &F, unsigned ItNum);
213
214 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 AU.addPreservedID(LCSSAID);
216 AU.setPreservesCFG();
217 }
218
Dan Gohmana80e2712009-07-21 23:21:54 +0000219 TargetData *getTargetData() const { return TD; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220
221 // Visitation implementation - Implement instruction combining for different
222 // instruction types. The semantics are as follows:
223 // Return Value:
224 // null - No change was made
225 // I - Change was made, I is still valid, I may be dead though
226 // otherwise - Change was made, replace I with returned instruction
227 //
228 Instruction *visitAdd(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000229 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner93e6ff92009-11-04 08:05:20 +0000230 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000232 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000234 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235 Instruction *visitURem(BinaryOperator &I);
236 Instruction *visitSRem(BinaryOperator &I);
237 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000238 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 Instruction *commonRemTransforms(BinaryOperator &I);
240 Instruction *commonIRemTransforms(BinaryOperator &I);
241 Instruction *commonDivTransforms(BinaryOperator &I);
242 Instruction *commonIDivTransforms(BinaryOperator &I);
243 Instruction *visitUDiv(BinaryOperator &I);
244 Instruction *visitSDiv(BinaryOperator &I);
245 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000246 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +0000247 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000249 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner57e66fa2009-07-23 05:46:22 +0000250 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000251 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000252 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 Instruction *visitOr (BinaryOperator &I);
254 Instruction *visitXor(BinaryOperator &I);
255 Instruction *visitShl(BinaryOperator &I);
256 Instruction *visitAShr(BinaryOperator &I);
257 Instruction *visitLShr(BinaryOperator &I);
258 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000259 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
260 Constant *RHSC);
Chris Lattner78264d82010-01-02 08:12:04 +0000261 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
262 GlobalVariable *GV, CmpInst &ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263 Instruction *visitFCmpInst(FCmpInst &I);
264 Instruction *visitICmpInst(ICmpInst &I);
265 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
266 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
267 Instruction *LHS,
268 ConstantInt *RHS);
269 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
270 ConstantInt *DivRHS);
Chris Lattner258a2ffb2009-12-21 03:19:28 +0000271 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
Chris Lattnera54b96b2009-12-21 04:04:05 +0000272 ICmpInst::Predicate Pred, Value *TheAdd);
Dan Gohman17f46f72009-07-28 01:40:03 +0000273 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274 ICmpInst::Predicate Cond, Instruction &I);
275 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
276 BinaryOperator &I);
277 Instruction *commonCastTransforms(CastInst &CI);
278 Instruction *commonIntCastTransforms(CastInst &CI);
279 Instruction *commonPointerCastTransforms(CastInst &CI);
280 Instruction *visitTrunc(TruncInst &CI);
281 Instruction *visitZExt(ZExtInst &CI);
282 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000283 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000285 Instruction *visitFPToUI(FPToUIInst &FI);
286 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287 Instruction *visitUIToFP(CastInst &CI);
288 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000289 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000290 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291 Instruction *visitBitCast(BitCastInst &CI);
292 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
293 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000294 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Chris Lattner78500cb2009-12-21 06:03:05 +0000295 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
296 Value *A, Value *B, Instruction &Outer,
297 SelectPatternFlavor SPF2, Value *C);
Dan Gohman58c09632008-09-16 18:46:06 +0000298 Instruction *visitSelectInst(SelectInst &SI);
299 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300 Instruction *visitCallInst(CallInst &CI);
301 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner1cd526b2009-11-08 19:23:30 +0000302
303 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304 Instruction *visitPHINode(PHINode &PN);
305 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandezb1687302009-10-23 21:09:37 +0000306 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez93946082009-10-24 04:23:03 +0000307 Instruction *visitFree(Instruction &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 Instruction *visitLoadInst(LoadInst &LI);
309 Instruction *visitStoreInst(StoreInst &SI);
310 Instruction *visitBranchInst(BranchInst &BI);
311 Instruction *visitSwitchInst(SwitchInst &SI);
312 Instruction *visitInsertElementInst(InsertElementInst &IE);
313 Instruction *visitExtractElementInst(ExtractElementInst &EI);
314 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000315 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316
317 // visitInstruction - Specify what to return for unhandled instructions...
318 Instruction *visitInstruction(Instruction &I) { return 0; }
319
320 private:
321 Instruction *visitCallSite(CallSite CS);
322 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000323 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000324 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
325 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000326 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000327 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
328
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329
330 public:
331 // InsertNewInstBefore - insert an instruction New before instruction Old
332 // in the program. Add the new instruction to the worklist.
333 //
334 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
335 assert(New && New->getParent() == 0 &&
336 "New instruction already inserted into a basic block!");
337 BasicBlock *BB = Old.getParent();
338 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner3183fb62009-08-30 06:13:40 +0000339 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340 return New;
341 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000342
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343 // ReplaceInstUsesWith - This method is to be used when an instruction is
344 // found to be dead, replacable with another preexisting expression. Here
345 // we add all uses of I to the worklist, replace all uses of I with the new
346 // value, then return I, so that the inst combiner will know that I was
347 // modified.
348 //
349 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner4796b622009-08-30 06:22:51 +0000350 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +0000351
352 // If we are replacing the instruction with itself, this must be in a
353 // segment of unreachable code, so just clobber the instruction.
354 if (&I == V)
355 V = UndefValue::get(I.getType());
356
357 I.replaceAllUsesWith(V);
358 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359 }
360
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361 // EraseInstFromFunction - When dealing with an instruction that has side
362 // effects or produces a void value, we can't rely on DCE to delete the
363 // instruction. Instead, visit methods should return the value returned by
364 // this function.
365 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez48c3c542009-09-18 22:35:49 +0000366 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner26b7f942009-08-31 05:17:58 +0000367
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000368 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner3183fb62009-08-30 06:13:40 +0000369 // Make sure that we reprocess all operands now that we reduced their
370 // use counts.
Chris Lattnerc5ad98f2009-08-30 06:27:41 +0000371 if (I.getNumOperands() < 8) {
372 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
373 if (Instruction *Op = dyn_cast<Instruction>(*i))
374 Worklist.Add(Op);
375 }
Chris Lattner3183fb62009-08-30 06:13:40 +0000376 Worklist.Remove(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 I.eraseFromParent();
Chris Lattner21d79e22009-08-31 06:57:37 +0000378 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000379 return 0; // Don't do anything with FI
380 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000381
382 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
383 APInt &KnownOne, unsigned Depth = 0) const {
384 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
385 }
386
387 bool MaskedValueIsZero(Value *V, const APInt &Mask,
388 unsigned Depth = 0) const {
389 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
390 }
391 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
392 return llvm::ComputeNumSignBits(Op, TD, Depth);
393 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000394
395 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396
397 /// SimplifyCommutative - This performs a few simplifications for
398 /// commutative operators.
399 bool SimplifyCommutative(BinaryOperator &I);
400
Chris Lattner676c78e2009-01-31 08:15:18 +0000401 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
402 /// based on the demanded bits.
403 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
404 APInt& KnownZero, APInt& KnownOne,
405 unsigned Depth);
406 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000407 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000408 unsigned Depth=0);
409
410 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
411 /// SimplifyDemandedBits knows about. See if the instruction has any
412 /// properties that allow us to simplify its operands.
413 bool SimplifyDemandedInstructionBits(Instruction &Inst);
414
Evan Cheng63295ab2009-02-03 10:05:09 +0000415 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
416 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000417
Chris Lattnerf7843b72009-09-27 19:57:57 +0000418 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
419 // which has a PHI node as operand #0, see if we can fold the instruction
420 // into the PHI (which is only possible if all operands to the PHI are
421 // constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +0000422 //
423 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
424 // that would normally be unprofitable because they strongly encourage jump
425 // threading.
426 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000427
428 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
429 // operator and they all are only used by the PHI, PHI together their
430 // inputs, and do the operation once, to the result of the PHI.
431 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
432 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000433 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner38751f82009-11-01 20:04:24 +0000434 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000435
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000436
437 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
438 ConstantInt *AndRHS, BinaryOperator &TheAnd);
439
440 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
441 bool isSub, Instruction &I);
442 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
443 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandezb1687302009-10-23 21:09:37 +0000444 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000445 Instruction *MatchBSwap(BinaryOperator &I);
446 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000447 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000448 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000449
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000450
451 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000452
Dan Gohman8fd520a2009-06-15 22:12:54 +0000453 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000454 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000455 unsigned GetOrEnforceKnownAlignment(Value *V,
456 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000457
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000458 };
Chris Lattner5119c702009-08-30 05:55:36 +0000459} // end anonymous namespace
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460
Dan Gohman089efff2008-05-13 00:00:25 +0000461char InstCombiner::ID = 0;
462static RegisterPass<InstCombiner>
463X("instcombine", "Combine redundant instructions");
464
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000465// getComplexity: Assign a complexity or rank value to LLVM Values...
466// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman5d138f92009-08-29 23:39:38 +0000467static unsigned getComplexity(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000468 if (isa<Instruction>(V)) {
Owen Anderson76f49252009-07-13 22:18:28 +0000469 if (BinaryOperator::isNeg(V) ||
470 BinaryOperator::isFNeg(V) ||
Dan Gohman7ce405e2009-06-04 22:49:04 +0000471 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000472 return 3;
473 return 4;
474 }
475 if (isa<Argument>(V)) return 3;
476 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
477}
478
479// isOnlyUse - Return true if this instruction will be deleted if we stop using
480// it.
481static bool isOnlyUse(Value *V) {
482 return V->hasOneUse() || isa<Constant>(V);
483}
484
485// getPromotedType - Return the specified type promoted as it would be to pass
486// though a va_arg area...
487static const Type *getPromotedType(const Type *Ty) {
488 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
489 if (ITy->getBitWidth() < 32)
Owen Anderson35b47072009-08-13 21:58:54 +0000490 return Type::getInt32Ty(Ty->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000491 }
492 return Ty;
493}
494
Chris Lattnerd0011092009-11-10 07:23:37 +0000495/// ShouldChangeType - Return true if it is desirable to convert a computation
496/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
497/// type for example, or from a smaller to a larger illegal type.
498static bool ShouldChangeType(const Type *From, const Type *To,
499 const TargetData *TD) {
500 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
501
502 // If we don't have TD, we don't know if the source/dest are legal.
503 if (!TD) return false;
504
505 unsigned FromWidth = From->getPrimitiveSizeInBits();
506 unsigned ToWidth = To->getPrimitiveSizeInBits();
507 bool FromLegal = TD->isLegalInteger(FromWidth);
508 bool ToLegal = TD->isLegalInteger(ToWidth);
509
510 // If this is a legal integer from type, and the result would be an illegal
511 // type, don't do the transformation.
512 if (FromLegal && !ToLegal)
513 return false;
514
515 // Otherwise, if both are illegal, do not increase the size of the result. We
516 // do allow things like i160 -> i64, but not i64 -> i160.
517 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
518 return false;
519
520 return true;
521}
522
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000523/// getBitCastOperand - If the specified operand is a CastInst, a constant
524/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
525/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000526static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000527 if (Operator *O = dyn_cast<Operator>(V)) {
528 if (O->getOpcode() == Instruction::BitCast)
529 return O->getOperand(0);
530 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
531 if (GEP->hasAllZeroIndices())
532 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000533 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534 return 0;
535}
536
537/// This function is a wrapper around CastInst::isEliminableCastPair. It
538/// simply extracts arguments and returns what that function returns.
539static Instruction::CastOps
540isEliminableCastPair(
541 const CastInst *CI, ///< The first cast instruction
542 unsigned opcode, ///< The opcode of the second cast instruction
543 const Type *DstTy, ///< The target type for the second cast instruction
544 TargetData *TD ///< The target data for pointer size
545) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000546
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
548 const Type *MidTy = CI->getType(); // B from above
549
550 // Get the opcodes of the two Cast instructions
551 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
552 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
553
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000554 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmana80e2712009-07-21 23:21:54 +0000555 DstTy,
Owen Anderson35b47072009-08-13 21:58:54 +0000556 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000557
558 // We don't want to form an inttoptr or ptrtoint that converts to an integer
559 // type that differs from the pointer size.
Owen Anderson35b47072009-08-13 21:58:54 +0000560 if ((Res == Instruction::IntToPtr &&
Dan Gohman033445f2009-08-19 23:38:22 +0000561 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson35b47072009-08-13 21:58:54 +0000562 (Res == Instruction::PtrToInt &&
Dan Gohman033445f2009-08-19 23:38:22 +0000563 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000564 Res = 0;
565
566 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000567}
568
569/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
570/// in any code being generated. It does not require codegen if V is simple
571/// enough or if the cast can be folded into other casts.
572static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
573 const Type *Ty, TargetData *TD) {
574 if (V->getType() == Ty || isa<Constant>(V)) return false;
575
576 // If this is another cast that can be eliminated, it isn't codegen either.
577 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000578 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 return false;
580 return true;
581}
582
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583// SimplifyCommutative - This performs a few simplifications for commutative
584// operators:
585//
586// 1. Order operands such that they are listed from right (least complex) to
587// left (most complex). This puts constants before unary operators before
588// binary operators.
589//
590// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
591// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
592//
593bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
594 bool Changed = false;
Dan Gohman5d138f92009-08-29 23:39:38 +0000595 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596 Changed = !I.swapOperands();
597
598 if (!I.isAssociative()) return Changed;
599 Instruction::BinaryOps Opcode = I.getOpcode();
600 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
601 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
602 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000603 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000604 cast<Constant>(I.getOperand(1)),
605 cast<Constant>(Op->getOperand(1)));
606 I.setOperand(0, Op->getOperand(0));
607 I.setOperand(1, Folded);
608 return true;
609 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
610 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
611 isOnlyUse(Op) && isOnlyUse(Op1)) {
612 Constant *C1 = cast<Constant>(Op->getOperand(1));
613 Constant *C2 = cast<Constant>(Op1->getOperand(1));
614
615 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000616 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000617 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618 Op1->getOperand(0),
619 Op1->getName(), &I);
Chris Lattner3183fb62009-08-30 06:13:40 +0000620 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000621 I.setOperand(0, New);
622 I.setOperand(1, Folded);
623 return true;
624 }
625 }
626 return Changed;
627}
628
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
630// if the LHS is a constant zero (which is the 'negate' form).
631//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000632static inline Value *dyn_castNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000633 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634 return BinaryOperator::getNegArgument(V);
635
636 // Constants can be considered to be negated values if they can be folded.
637 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000638 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000639
640 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
641 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000642 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000643
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644 return 0;
645}
646
Dan Gohman7ce405e2009-06-04 22:49:04 +0000647// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
648// instruction if the LHS is a constant negative zero (which is the 'negate'
649// form).
650//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000651static inline Value *dyn_castFNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000652 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000653 return BinaryOperator::getFNegArgument(V);
654
655 // Constants can be considered to be negated values if they can be folded.
656 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000657 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000658
659 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
660 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000661 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000662
663 return 0;
664}
665
Chris Lattner78500cb2009-12-21 06:03:05 +0000666/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
667/// returning the kind and providing the out parameter results if we
668/// successfully match.
669static SelectPatternFlavor
670MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
671 SelectInst *SI = dyn_cast<SelectInst>(V);
672 if (SI == 0) return SPF_UNKNOWN;
673
674 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
675 if (ICI == 0) return SPF_UNKNOWN;
676
677 LHS = ICI->getOperand(0);
678 RHS = ICI->getOperand(1);
679
680 // (icmp X, Y) ? X : Y
681 if (SI->getTrueValue() == ICI->getOperand(0) &&
682 SI->getFalseValue() == ICI->getOperand(1)) {
683 switch (ICI->getPredicate()) {
684 default: return SPF_UNKNOWN; // Equality.
685 case ICmpInst::ICMP_UGT:
686 case ICmpInst::ICMP_UGE: return SPF_UMAX;
687 case ICmpInst::ICMP_SGT:
688 case ICmpInst::ICMP_SGE: return SPF_SMAX;
689 case ICmpInst::ICMP_ULT:
690 case ICmpInst::ICMP_ULE: return SPF_UMIN;
691 case ICmpInst::ICMP_SLT:
692 case ICmpInst::ICMP_SLE: return SPF_SMIN;
693 }
694 }
695
696 // (icmp X, Y) ? Y : X
697 if (SI->getTrueValue() == ICI->getOperand(1) &&
698 SI->getFalseValue() == ICI->getOperand(0)) {
699 switch (ICI->getPredicate()) {
700 default: return SPF_UNKNOWN; // Equality.
701 case ICmpInst::ICMP_UGT:
702 case ICmpInst::ICMP_UGE: return SPF_UMIN;
703 case ICmpInst::ICMP_SGT:
704 case ICmpInst::ICMP_SGE: return SPF_SMIN;
705 case ICmpInst::ICMP_ULT:
706 case ICmpInst::ICMP_ULE: return SPF_UMAX;
707 case ICmpInst::ICMP_SLT:
708 case ICmpInst::ICMP_SLE: return SPF_SMAX;
709 }
710 }
711
712 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
713
714 return SPF_UNKNOWN;
715}
716
Chris Lattner6e060db2009-10-26 15:40:07 +0000717/// isFreeToInvert - Return true if the specified value is free to invert (apply
718/// ~ to). This happens in cases where the ~ can be eliminated.
719static inline bool isFreeToInvert(Value *V) {
720 // ~(~(X)) -> X.
Evan Cheng5d4a07e2009-10-26 03:51:32 +0000721 if (BinaryOperator::isNot(V))
Chris Lattner6e060db2009-10-26 15:40:07 +0000722 return true;
723
724 // Constants can be considered to be not'ed values.
725 if (isa<ConstantInt>(V))
726 return true;
727
728 // Compares can be inverted if they have a single use.
729 if (CmpInst *CI = dyn_cast<CmpInst>(V))
730 return CI->hasOneUse();
731
732 return false;
733}
734
735static inline Value *dyn_castNotVal(Value *V) {
736 // If this is not(not(x)) don't return that this is a not: we want the two
737 // not's to be folded first.
738 if (BinaryOperator::isNot(V)) {
739 Value *Operand = BinaryOperator::getNotArgument(V);
740 if (!isFreeToInvert(Operand))
741 return Operand;
742 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000743
744 // Constants can be considered to be not'ed values...
745 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000746 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 return 0;
748}
749
Chris Lattner6e060db2009-10-26 15:40:07 +0000750
751
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752// dyn_castFoldableMul - If this value is a multiply that can be folded into
753// other computations (because it has a constant operand), return the
754// non-constant operand of the multiply, and set CST to point to the multiplier.
755// Otherwise, return null.
756//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000757static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758 if (V->hasOneUse() && V->getType()->isInteger())
759 if (Instruction *I = dyn_cast<Instruction>(V)) {
760 if (I->getOpcode() == Instruction::Mul)
761 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
762 return I->getOperand(0);
763 if (I->getOpcode() == Instruction::Shl)
764 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
765 // The multiplier is really 1 << CST.
766 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
767 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000768 CST = ConstantInt::get(V->getType()->getContext(),
769 APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770 return I->getOperand(0);
771 }
772 }
773 return 0;
774}
775
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000776/// AddOne - Add one to a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000777static Constant *AddOne(Constant *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000778 return ConstantExpr::getAdd(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000779 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780}
781/// SubOne - Subtract one from a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000782static Constant *SubOne(ConstantInt *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000783 return ConstantExpr::getSub(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000784 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000786/// MultiplyOverflows - True if the multiply can not be expressed in an int
787/// this size.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000788static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000789 uint32_t W = C1->getBitWidth();
790 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
791 if (sign) {
792 LHSExt.sext(W * 2);
793 RHSExt.sext(W * 2);
794 } else {
795 LHSExt.zext(W * 2);
796 RHSExt.zext(W * 2);
797 }
798
799 APInt MulExt = LHSExt * RHSExt;
800
Chris Lattner78500cb2009-12-21 06:03:05 +0000801 if (!sign)
Nick Lewycky9d798f92008-02-18 22:48:05 +0000802 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattner78500cb2009-12-21 06:03:05 +0000803
804 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
805 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
806 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewycky9d798f92008-02-18 22:48:05 +0000807}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809
810/// ShrinkDemandedConstant - Check to see if the specified operand of the
811/// specified instruction is a constant integer. If so, check to see if there
812/// are any bits set in the constant that are not demanded. If so, shrink the
813/// constant and return true.
814static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000815 APInt Demanded) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000816 assert(I && "No instruction?");
817 assert(OpNo < I->getNumOperands() && "Operand index too large");
818
819 // If the operand is not a constant integer, nothing to do.
820 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
821 if (!OpC) return false;
822
823 // If there are no bits set that aren't demanded, nothing to do.
824 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
825 if ((~Demanded & OpC->getValue()) == 0)
826 return false;
827
828 // This instruction is producing bits that are not demanded. Shrink the RHS.
829 Demanded &= OpC->getValue();
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000830 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000831 return true;
832}
833
834// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
835// set of known zero and one bits, compute the maximum and minimum values that
836// could have the specified known zero and known one bits, returning them in
837// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000838static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839 const APInt& KnownOne,
840 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000841 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
842 KnownZero.getBitWidth() == Min.getBitWidth() &&
843 KnownZero.getBitWidth() == Max.getBitWidth() &&
844 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000845 APInt UnknownBits = ~(KnownZero|KnownOne);
846
847 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
848 // bit if it is unknown.
849 Min = KnownOne;
850 Max = KnownOne|UnknownBits;
851
Dan Gohman7934d592009-04-25 17:12:48 +0000852 if (UnknownBits.isNegative()) { // Sign bit is unknown
853 Min.set(Min.getBitWidth()-1);
854 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000855 }
856}
857
858// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
859// a set of known zero and one bits, compute the maximum and minimum values that
860// could have the specified known zero and known one bits, returning them in
861// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000862static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000863 const APInt &KnownOne,
864 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000865 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
866 KnownZero.getBitWidth() == Min.getBitWidth() &&
867 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
869 APInt UnknownBits = ~(KnownZero|KnownOne);
870
871 // The minimum value is when the unknown bits are all zeros.
872 Min = KnownOne;
873 // The maximum value is when the unknown bits are all ones.
874 Max = KnownOne|UnknownBits;
875}
876
Chris Lattner676c78e2009-01-31 08:15:18 +0000877/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
878/// SimplifyDemandedBits knows about. See if the instruction has any
879/// properties that allow us to simplify its operands.
880bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000881 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000882 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
883 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
884
885 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
886 KnownZero, KnownOne, 0);
887 if (V == 0) return false;
888 if (V == &Inst) return true;
889 ReplaceInstUsesWith(Inst, V);
890 return true;
891}
892
893/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
894/// specified instruction operand if possible, updating it in place. It returns
895/// true if it made any change and false otherwise.
896bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
897 APInt &KnownZero, APInt &KnownOne,
898 unsigned Depth) {
899 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
900 KnownZero, KnownOne, Depth);
901 if (NewVal == 0) return false;
Dan Gohman3af2d412009-10-05 16:31:55 +0000902 U = NewVal;
Chris Lattner676c78e2009-01-31 08:15:18 +0000903 return true;
904}
905
906
907/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
908/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000909/// that only the bits set in DemandedMask of the result of V are ever used
910/// downstream. Consequently, depending on the mask and V, it may be possible
911/// to replace V with a constant or one of its operands. In such cases, this
912/// function does the replacement and returns true. In all other cases, it
913/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000914/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000915/// to be zero in the expression. These are provided to potentially allow the
916/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
917/// the expression. KnownOne and KnownZero always follow the invariant that
918/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
919/// the bits in KnownOne and KnownZero may only be accurate for those bits set
920/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
921/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000922///
923/// This returns null if it did not change anything and it permits no
924/// simplification. This returns V itself if it did some simplification of V's
925/// operands based on the information about what bits are demanded. This returns
926/// some other non-null value if it found out that V is equal to another value
927/// in the context where the specified bits are demanded, but not for all users.
928Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
929 APInt &KnownZero, APInt &KnownOne,
930 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000931 assert(V != 0 && "Null pointer of Value???");
932 assert(Depth <= 6 && "Limit Search Depth");
933 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000934 const Type *VTy = V->getType();
935 assert((TD || !isa<PointerType>(VTy)) &&
936 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000937 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
938 (!VTy->isIntOrIntVector() ||
939 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000940 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000941 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000942 "Value *V, DemandedMask, KnownZero and KnownOne "
943 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000944 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
945 // We know all of the bits for a constant!
946 KnownOne = CI->getValue() & DemandedMask;
947 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000948 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949 }
Dan Gohman7934d592009-04-25 17:12:48 +0000950 if (isa<ConstantPointerNull>(V)) {
951 // We know all of the bits for a constant!
952 KnownOne.clear();
953 KnownZero = DemandedMask;
954 return 0;
955 }
956
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000957 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000958 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000959 if (DemandedMask == 0) { // Not demanding any bits from V.
960 if (isa<UndefValue>(V))
961 return 0;
Owen Andersonb99ecca2009-07-30 23:03:37 +0000962 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000963 }
964
Chris Lattner08817332009-01-31 08:24:16 +0000965 if (Depth == 6) // Limit search depth.
966 return 0;
967
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000968 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
969 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
970
Dan Gohman7934d592009-04-25 17:12:48 +0000971 Instruction *I = dyn_cast<Instruction>(V);
972 if (!I) {
973 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
974 return 0; // Only analyze instructions.
975 }
976
Chris Lattner08817332009-01-31 08:24:16 +0000977 // If there are multiple uses of this value and we aren't at the root, then
978 // we can't do any simplifications of the operands, because DemandedMask
979 // only reflects the bits demanded by *one* of the users.
980 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000981 // Despite the fact that we can't simplify this instruction in all User's
982 // context, we can at least compute the knownzero/knownone bits, and we can
983 // do simplifications that apply to *just* the one user if we know that
984 // this instruction has a simpler value in that context.
985 if (I->getOpcode() == Instruction::And) {
986 // If either the LHS or the RHS are Zero, the result is zero.
987 ComputeMaskedBits(I->getOperand(1), DemandedMask,
988 RHSKnownZero, RHSKnownOne, Depth+1);
989 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
990 LHSKnownZero, LHSKnownOne, Depth+1);
991
992 // If all of the demanded bits are known 1 on one side, return the other.
993 // These bits cannot contribute to the result of the 'and' in this
994 // context.
995 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
996 (DemandedMask & ~LHSKnownZero))
997 return I->getOperand(0);
998 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
999 (DemandedMask & ~RHSKnownZero))
1000 return I->getOperand(1);
1001
1002 // If all of the demanded bits in the inputs are known zeros, return zero.
1003 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +00001004 return Constant::getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +00001005
1006 } else if (I->getOpcode() == Instruction::Or) {
1007 // We can simplify (X|Y) -> X or Y in the user's context if we know that
1008 // only bits from X or Y are demanded.
1009
1010 // If either the LHS or the RHS are One, the result is One.
1011 ComputeMaskedBits(I->getOperand(1), DemandedMask,
1012 RHSKnownZero, RHSKnownOne, Depth+1);
1013 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1014 LHSKnownZero, LHSKnownOne, Depth+1);
1015
1016 // If all of the demanded bits are known zero on one side, return the
1017 // other. These bits cannot contribute to the result of the 'or' in this
1018 // context.
1019 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1020 (DemandedMask & ~LHSKnownOne))
1021 return I->getOperand(0);
1022 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1023 (DemandedMask & ~RHSKnownOne))
1024 return I->getOperand(1);
1025
1026 // If all of the potentially set bits on one side are known to be set on
1027 // the other side, just use the 'other' side.
1028 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1029 (DemandedMask & (~RHSKnownZero)))
1030 return I->getOperand(0);
1031 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1032 (DemandedMask & (~LHSKnownZero)))
1033 return I->getOperand(1);
1034 }
1035
Chris Lattner08817332009-01-31 08:24:16 +00001036 // Compute the KnownZero/KnownOne bits to simplify things downstream.
1037 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
1038 return 0;
1039 }
1040
1041 // If this is the root being simplified, allow it to have multiple uses,
1042 // just set the DemandedMask to all bits so that we can try to simplify the
1043 // operands. This allows visitTruncInst (for example) to simplify the
1044 // operand of a trunc without duplicating all the logic below.
1045 if (Depth == 0 && !V->hasOneUse())
1046 DemandedMask = APInt::getAllOnesValue(BitWidth);
1047
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +00001049 default:
Chris Lattner676c78e2009-01-31 08:15:18 +00001050 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +00001051 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001052 case Instruction::And:
1053 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +00001054 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1055 RHSKnownZero, RHSKnownOne, Depth+1) ||
1056 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001058 return I;
1059 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1060 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001061
1062 // If all of the demanded bits are known 1 on one side, return the other.
1063 // These bits cannot contribute to the result of the 'and'.
1064 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1065 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +00001066 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001067 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1068 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +00001069 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070
1071 // If all of the demanded bits in the inputs are known zeros, return zero.
1072 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +00001073 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001074
1075 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001076 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +00001077 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078
1079 // Output known-1 bits are only known if set in both the LHS & RHS.
1080 RHSKnownOne &= LHSKnownOne;
1081 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1082 RHSKnownZero |= LHSKnownZero;
1083 break;
1084 case Instruction::Or:
1085 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +00001086 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1087 RHSKnownZero, RHSKnownOne, Depth+1) ||
1088 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001089 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001090 return I;
1091 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1092 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001093
1094 // If all of the demanded bits are known zero on one side, return the other.
1095 // These bits cannot contribute to the result of the 'or'.
1096 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1097 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +00001098 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001099 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1100 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +00001101 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001102
1103 // If all of the potentially set bits on one side are known to be set on
1104 // the other side, just use the 'other' side.
1105 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1106 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +00001107 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1109 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +00001110 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001111
1112 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001113 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001114 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001115
1116 // Output known-0 bits are only known if clear in both the LHS & RHS.
1117 RHSKnownZero &= LHSKnownZero;
1118 // Output known-1 are known to be set if set in either the LHS | RHS.
1119 RHSKnownOne |= LHSKnownOne;
1120 break;
1121 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +00001122 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1123 RHSKnownZero, RHSKnownOne, Depth+1) ||
1124 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001125 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001126 return I;
1127 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1128 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001129
1130 // If all of the demanded bits are known zero on one side, return the other.
1131 // These bits cannot contribute to the result of the 'xor'.
1132 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001133 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001134 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001135 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001136
1137 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1138 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1139 (RHSKnownOne & LHSKnownOne);
1140 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1141 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1142 (RHSKnownOne & LHSKnownZero);
1143
1144 // If all of the demanded bits are known to be zero on one side or the
1145 // other, turn this into an *inclusive* or.
1146 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneradba7ea2009-08-31 04:36:22 +00001147 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1148 Instruction *Or =
1149 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1150 I->getName());
1151 return InsertNewInstBefore(Or, *I);
1152 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001153
1154 // If all of the demanded bits on one side are known, and all of the set
1155 // bits on that side are also known to be set on the other side, turn this
1156 // into an AND, as we know the bits will be cleared.
1157 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1158 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1159 // all known
1160 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohmancf2c9982009-08-03 22:07:33 +00001161 Constant *AndC = Constant::getIntegerValue(VTy,
1162 ~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001164 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001165 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001166 }
1167 }
1168
1169 // If the RHS is a constant, see if we can simplify it.
1170 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001171 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001172 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001173
Chris Lattnereefa89c2009-10-11 22:22:13 +00001174 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1175 // are flipping are known to be set, then the xor is just resetting those
1176 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1177 // simplifying both of them.
1178 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1179 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1180 isa<ConstantInt>(I->getOperand(1)) &&
1181 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1182 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1183 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1184 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1185 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1186
1187 Constant *AndC =
1188 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1189 Instruction *NewAnd =
1190 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1191 InsertNewInstBefore(NewAnd, *I);
1192
1193 Constant *XorC =
1194 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1195 Instruction *NewXor =
1196 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1197 return InsertNewInstBefore(NewXor, *I);
1198 }
1199
1200
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201 RHSKnownZero = KnownZeroOut;
1202 RHSKnownOne = KnownOneOut;
1203 break;
1204 }
1205 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001206 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1207 RHSKnownZero, RHSKnownOne, Depth+1) ||
1208 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001209 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001210 return I;
1211 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1212 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001213
1214 // If the operands are constants, see if we can simplify them.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001215 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1216 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001217 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001218
1219 // Only known if known in both the LHS and RHS.
1220 RHSKnownOne &= LHSKnownOne;
1221 RHSKnownZero &= LHSKnownZero;
1222 break;
1223 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001224 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001225 DemandedMask.zext(truncBf);
1226 RHSKnownZero.zext(truncBf);
1227 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001228 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001229 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001230 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001231 DemandedMask.trunc(BitWidth);
1232 RHSKnownZero.trunc(BitWidth);
1233 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001234 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001235 break;
1236 }
1237 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001238 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001239 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001240
1241 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1242 if (const VectorType *SrcVTy =
1243 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1244 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1245 // Don't touch a bitcast between vectors of different element counts.
1246 return false;
1247 } else
1248 // Don't touch a scalar-to-vector bitcast.
1249 return false;
1250 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1251 // Don't touch a vector-to-scalar bitcast.
1252 return false;
1253
Chris Lattner676c78e2009-01-31 08:15:18 +00001254 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001255 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001256 return I;
1257 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258 break;
1259 case Instruction::ZExt: {
1260 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001261 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001262
1263 DemandedMask.trunc(SrcBitWidth);
1264 RHSKnownZero.trunc(SrcBitWidth);
1265 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001266 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001268 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269 DemandedMask.zext(BitWidth);
1270 RHSKnownZero.zext(BitWidth);
1271 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001272 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 // The top bits are known to be zero.
1274 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1275 break;
1276 }
1277 case Instruction::SExt: {
1278 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001279 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001280
1281 APInt InputDemandedBits = DemandedMask &
1282 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1283
1284 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1285 // If any of the sign extended bits are demanded, we know that the sign
1286 // bit is demanded.
1287 if ((NewBits & DemandedMask) != 0)
1288 InputDemandedBits.set(SrcBitWidth-1);
1289
1290 InputDemandedBits.trunc(SrcBitWidth);
1291 RHSKnownZero.trunc(SrcBitWidth);
1292 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001293 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001295 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001296 InputDemandedBits.zext(BitWidth);
1297 RHSKnownZero.zext(BitWidth);
1298 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001299 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001300
1301 // If the sign bit of the input is known set or clear, then we know the
1302 // top bits of the result.
1303
1304 // If the input sign bit is known zero, or if the NewBits are not demanded
1305 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001306 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001308 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1309 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001310 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1311 RHSKnownOne |= NewBits;
1312 }
1313 break;
1314 }
1315 case Instruction::Add: {
1316 // Figure out what the input bits are. If the top bits of the and result
1317 // are not demanded, then the add doesn't demand them from its input
1318 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001319 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001320
1321 // If there is a constant on the RHS, there are a variety of xformations
1322 // we can do.
1323 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1324 // If null, this should be simplified elsewhere. Some of the xforms here
1325 // won't work if the RHS is zero.
1326 if (RHS->isZero())
1327 break;
1328
1329 // If the top bit of the output is demanded, demand everything from the
1330 // input. Otherwise, we demand all the input bits except NLZ top bits.
1331 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1332
1333 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001334 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001336 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001337
1338 // If the RHS of the add has bits set that can't affect the input, reduce
1339 // the constant.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001340 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001341 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342
1343 // Avoid excess work.
1344 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1345 break;
1346
1347 // Turn it into OR if input bits are zero.
1348 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1349 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001350 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001351 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001352 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001353 }
1354
1355 // We can say something about the output known-zero and known-one bits,
1356 // depending on potential carries from the input constant and the
1357 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1358 // bits set and the RHS constant is 0x01001, then we know we have a known
1359 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1360
1361 // To compute this, we first compute the potential carry bits. These are
1362 // the bits which may be modified. I'm not aware of a better way to do
1363 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001364 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001365 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1366
1367 // Now that we know which bits have carries, compute the known-1/0 sets.
1368
1369 // Bits are known one if they are known zero in one operand and one in the
1370 // other, and there is no input carry.
1371 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1372 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1373
1374 // Bits are known zero if they are known zero in both operands and there
1375 // is no input carry.
1376 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1377 } else {
1378 // If the high-bits of this ADD are not demanded, then it does not demand
1379 // the high bits of its LHS or RHS.
1380 if (DemandedMask[BitWidth-1] == 0) {
1381 // Right fill the mask of bits for this ADD to demand the most
1382 // significant bit and all those below it.
1383 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001384 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1385 LHSKnownZero, LHSKnownOne, Depth+1) ||
1386 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001387 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001388 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001389 }
1390 }
1391 break;
1392 }
1393 case Instruction::Sub:
1394 // If the high-bits of this SUB are not demanded, then it does not demand
1395 // the high bits of its LHS or RHS.
1396 if (DemandedMask[BitWidth-1] == 0) {
1397 // Right fill the mask of bits for this SUB to demand the most
1398 // significant bit and all those below it.
1399 uint32_t NLZ = DemandedMask.countLeadingZeros();
1400 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001401 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1402 LHSKnownZero, LHSKnownOne, Depth+1) ||
1403 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001404 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001405 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001406 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001407 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1408 // the known zeros and ones.
1409 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001410 break;
1411 case Instruction::Shl:
1412 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1413 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1414 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001415 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001416 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001417 return I;
1418 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001419 RHSKnownZero <<= ShiftAmt;
1420 RHSKnownOne <<= ShiftAmt;
1421 // low bits known zero.
1422 if (ShiftAmt)
1423 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1424 }
1425 break;
1426 case Instruction::LShr:
1427 // For a logical shift right
1428 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1429 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1430
1431 // Unsigned shift right.
1432 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001433 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001434 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001435 return I;
1436 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001437 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1438 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1439 if (ShiftAmt) {
1440 // Compute the new bits that are at the top now.
1441 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1442 RHSKnownZero |= HighBits; // high bits known zero.
1443 }
1444 }
1445 break;
1446 case Instruction::AShr:
1447 // If this is an arithmetic shift right and only the low-bit is set, we can
1448 // always convert this into a logical shr, even if the shift amount is
1449 // variable. The low bit of the shift cannot be an input sign bit unless
1450 // the shift amount is >= the size of the datatype, which is undefined.
1451 if (DemandedMask == 1) {
1452 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001453 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001454 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001455 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001456 }
1457
1458 // If the sign bit is the only bit demanded by this ashr, then there is no
1459 // need to do it, the shift doesn't change the high bit.
1460 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001461 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001462
1463 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1464 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1465
1466 // Signed shift right.
1467 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1468 // If any of the "high bits" are demanded, we should set the sign bit as
1469 // demanded.
1470 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1471 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001472 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001473 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001474 return I;
1475 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001476 // Compute the new bits that are at the top now.
1477 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1478 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1479 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1480
1481 // Handle the sign bits.
1482 APInt SignBit(APInt::getSignBit(BitWidth));
1483 // Adjust to where it is now in the mask.
1484 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1485
1486 // If the input sign bit is known to be zero, or if none of the top bits
1487 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001488 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001489 (HighBits & ~DemandedMask) == HighBits) {
1490 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001491 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001492 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001493 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001494 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1495 RHSKnownOne |= HighBits;
1496 }
1497 }
1498 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001499 case Instruction::SRem:
1500 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001501 APInt RA = Rem->getValue().abs();
1502 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001503 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001504 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001505
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001506 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001507 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001508 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001509 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001510 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001511
1512 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1513 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001514
1515 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001516
Chris Lattner676c78e2009-01-31 08:15:18 +00001517 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001518 }
1519 }
1520 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001521 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001522 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1523 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001524 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1525 KnownZero2, KnownOne2, Depth+1) ||
1526 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001527 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001528 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001529
Chris Lattneree5417c2009-01-21 18:09:24 +00001530 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001531 Leaders = std::max(Leaders,
1532 KnownZero2.countLeadingOnes());
1533 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001534 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001535 }
Chris Lattner989ba312008-06-18 04:33:20 +00001536 case Instruction::Call:
1537 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1538 switch (II->getIntrinsicID()) {
1539 default: break;
1540 case Intrinsic::bswap: {
1541 // If the only bits demanded come from one byte of the bswap result,
1542 // just shift the input byte into position to eliminate the bswap.
1543 unsigned NLZ = DemandedMask.countLeadingZeros();
1544 unsigned NTZ = DemandedMask.countTrailingZeros();
1545
1546 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1547 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1548 // have 14 leading zeros, round to 8.
1549 NLZ &= ~7;
1550 NTZ &= ~7;
1551 // If we need exactly one byte, we can do this transformation.
1552 if (BitWidth-NLZ-NTZ == 8) {
1553 unsigned ResultBit = NTZ;
1554 unsigned InputBit = BitWidth-NTZ-8;
1555
1556 // Replace this with either a left or right shift to get the byte into
1557 // the right place.
1558 Instruction *NewVal;
1559 if (InputBit > ResultBit)
1560 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001561 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001562 else
1563 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001564 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001565 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001566 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001567 }
1568
1569 // TODO: Could compute known zero/one bits based on the input.
1570 break;
1571 }
1572 }
1573 }
Chris Lattner4946e222008-06-18 18:11:55 +00001574 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001575 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001576 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001577
1578 // If the client is only demanding bits that we know, return the known
1579 // constant.
Dan Gohmancf2c9982009-08-03 22:07:33 +00001580 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1581 return Constant::getIntegerValue(VTy, RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001582 return false;
1583}
1584
1585
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001586/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001587/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001588/// actually used by the caller. This method analyzes which elements of the
1589/// operand are undef and returns that information in UndefElts.
1590///
1591/// If the information about demanded elements can be used to simplify the
1592/// operation, the operation is simplified, then the resultant value is
1593/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001594Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1595 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001596 unsigned Depth) {
1597 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001598 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001599 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001600
1601 if (isa<UndefValue>(V)) {
1602 // If the entire vector is undefined, just return this info.
1603 UndefElts = EltMask;
1604 return 0;
1605 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1606 UndefElts = EltMask;
Owen Andersonb99ecca2009-07-30 23:03:37 +00001607 return UndefValue::get(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001608 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001609
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001610 UndefElts = 0;
1611 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1612 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb99ecca2009-07-30 23:03:37 +00001613 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001614
1615 std::vector<Constant*> Elts;
1616 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001617 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001618 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001619 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001620 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1621 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001622 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001623 } else { // Otherwise, defined.
1624 Elts.push_back(CP->getOperand(i));
1625 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001626
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001627 // If we changed the constant, return it.
Owen Anderson2f422e02009-07-28 21:19:26 +00001628 Constant *NewCP = ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001629 return NewCP != CP ? NewCP : 0;
1630 } else if (isa<ConstantAggregateZero>(V)) {
1631 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1632 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001633
1634 // Check if this is identity. If so, return 0 since we are not simplifying
1635 // anything.
1636 if (DemandedElts == ((1ULL << VWidth) -1))
1637 return 0;
1638
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001639 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonaac28372009-07-31 20:28:14 +00001640 Constant *Zero = Constant::getNullValue(EltTy);
Owen Andersonb99ecca2009-07-30 23:03:37 +00001641 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001643 for (unsigned i = 0; i != VWidth; ++i) {
1644 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1645 Elts.push_back(Elt);
1646 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001647 UndefElts = DemandedElts ^ EltMask;
Owen Anderson2f422e02009-07-28 21:19:26 +00001648 return ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001649 }
1650
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001651 // Limit search depth.
1652 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001653 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001654
1655 // If multiple users are using the root value, procede with
1656 // simplification conservatively assuming that all elements
1657 // are needed.
1658 if (!V->hasOneUse()) {
1659 // Quit if we find multiple users of a non-root value though.
1660 // They'll be handled when it's their turn to be visited by
1661 // the main instcombine process.
1662 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001663 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001664 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001665
1666 // Conservatively assume that all elements are needed.
1667 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001668 }
1669
1670 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001671 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001672
1673 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001674 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001675 Value *TmpV;
1676 switch (I->getOpcode()) {
1677 default: break;
1678
1679 case Instruction::InsertElement: {
1680 // If this is a variable index, we don't know which element it overwrites.
1681 // demand exactly the same input as we produce.
1682 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1683 if (Idx == 0) {
1684 // Note that we can't propagate undef elt info, because we don't know
1685 // which elt is getting updated.
1686 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1687 UndefElts2, Depth+1);
1688 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1689 break;
1690 }
1691
1692 // If this is inserting an element that isn't demanded, remove this
1693 // insertelement.
1694 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner059cfc72009-08-30 06:20:05 +00001695 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1696 Worklist.Add(I);
1697 return I->getOperand(0);
1698 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001699
1700 // Otherwise, the element inserted overwrites whatever was there, so the
1701 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001702 APInt DemandedElts2 = DemandedElts;
1703 DemandedElts2.clear(IdxNo);
1704 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001705 UndefElts, Depth+1);
1706 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1707
1708 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001709 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001710 break;
1711 }
1712 case Instruction::ShuffleVector: {
1713 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001714 uint64_t LHSVWidth =
1715 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001716 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001717 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001718 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001719 unsigned MaskVal = Shuffle->getMaskValue(i);
1720 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001721 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001722 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001723 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001724 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001725 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001726 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001727 }
1728 }
1729 }
1730
Nate Begemanb4d176f2009-02-11 22:36:25 +00001731 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001732 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001733 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001734 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1735
Nate Begemanb4d176f2009-02-11 22:36:25 +00001736 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001737 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1738 UndefElts3, Depth+1);
1739 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1740
1741 bool NewUndefElts = false;
1742 for (unsigned i = 0; i < VWidth; i++) {
1743 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001744 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001745 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001746 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001747 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001748 NewUndefElts = true;
1749 UndefElts.set(i);
1750 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001751 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001752 if (UndefElts3[MaskVal - LHSVWidth]) {
1753 NewUndefElts = true;
1754 UndefElts.set(i);
1755 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001756 }
1757 }
1758
1759 if (NewUndefElts) {
1760 // Add additional discovered undefs.
1761 std::vector<Constant*> Elts;
1762 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001763 if (UndefElts[i])
Owen Anderson35b47072009-08-13 21:58:54 +00001764 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001765 else
Owen Anderson35b47072009-08-13 21:58:54 +00001766 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001767 Shuffle->getMaskValue(i)));
1768 }
Owen Anderson2f422e02009-07-28 21:19:26 +00001769 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001770 MadeChange = true;
1771 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001772 break;
1773 }
1774 case Instruction::BitCast: {
1775 // Vector->vector casts only.
1776 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1777 if (!VTy) break;
1778 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001779 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001780 unsigned Ratio;
1781
1782 if (VWidth == InVWidth) {
1783 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1784 // elements as are demanded of us.
1785 Ratio = 1;
1786 InputDemandedElts = DemandedElts;
1787 } else if (VWidth > InVWidth) {
1788 // Untested so far.
1789 break;
1790
1791 // If there are more elements in the result than there are in the source,
1792 // then an input element is live if any of the corresponding output
1793 // elements are live.
1794 Ratio = VWidth/InVWidth;
1795 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001796 if (DemandedElts[OutIdx])
1797 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001798 }
1799 } else {
1800 // Untested so far.
1801 break;
1802
1803 // If there are more elements in the source than there are in the result,
1804 // then an input element is live if the corresponding output element is
1805 // live.
1806 Ratio = InVWidth/VWidth;
1807 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001808 if (DemandedElts[InIdx/Ratio])
1809 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001810 }
1811
1812 // div/rem demand all inputs, because they don't want divide by zero.
1813 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1814 UndefElts2, Depth+1);
1815 if (TmpV) {
1816 I->setOperand(0, TmpV);
1817 MadeChange = true;
1818 }
1819
1820 UndefElts = UndefElts2;
1821 if (VWidth > InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001822 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001823 // If there are more elements in the result than there are in the source,
1824 // then an output element is undef if the corresponding input element is
1825 // undef.
1826 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001827 if (UndefElts2[OutIdx/Ratio])
1828 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001829 } else if (VWidth < InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001830 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001831 // If there are more elements in the source than there are in the result,
1832 // then a result element is undef if all of the corresponding input
1833 // elements are undef.
1834 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1835 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001836 if (!UndefElts2[InIdx]) // Not undef?
1837 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001838 }
1839 break;
1840 }
1841 case Instruction::And:
1842 case Instruction::Or:
1843 case Instruction::Xor:
1844 case Instruction::Add:
1845 case Instruction::Sub:
1846 case Instruction::Mul:
1847 // div/rem demand all inputs, because they don't want divide by zero.
1848 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1849 UndefElts, Depth+1);
1850 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1851 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1852 UndefElts2, Depth+1);
1853 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1854
1855 // Output elements are undefined if both are undefined. Consider things
1856 // like undef&0. The result is known zero, not undef.
1857 UndefElts &= UndefElts2;
1858 break;
1859
1860 case Instruction::Call: {
1861 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1862 if (!II) break;
1863 switch (II->getIntrinsicID()) {
1864 default: break;
1865
1866 // Binary vector operations that work column-wise. A dest element is a
1867 // function of the corresponding input elements from the two inputs.
1868 case Intrinsic::x86_sse_sub_ss:
1869 case Intrinsic::x86_sse_mul_ss:
1870 case Intrinsic::x86_sse_min_ss:
1871 case Intrinsic::x86_sse_max_ss:
1872 case Intrinsic::x86_sse2_sub_sd:
1873 case Intrinsic::x86_sse2_mul_sd:
1874 case Intrinsic::x86_sse2_min_sd:
1875 case Intrinsic::x86_sse2_max_sd:
1876 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1877 UndefElts, Depth+1);
1878 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1879 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1880 UndefElts2, Depth+1);
1881 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1882
1883 // If only the low elt is demanded and this is a scalarizable intrinsic,
1884 // scalarize it now.
1885 if (DemandedElts == 1) {
1886 switch (II->getIntrinsicID()) {
1887 default: break;
1888 case Intrinsic::x86_sse_sub_ss:
1889 case Intrinsic::x86_sse_mul_ss:
1890 case Intrinsic::x86_sse2_sub_sd:
1891 case Intrinsic::x86_sse2_mul_sd:
1892 // TODO: Lower MIN/MAX/ABS/etc
1893 Value *LHS = II->getOperand(1);
1894 Value *RHS = II->getOperand(2);
1895 // Extract the element as scalars.
Eric Christopher1ba36872009-07-25 02:28:41 +00001896 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001897 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christopher1ba36872009-07-25 02:28:41 +00001898 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001899 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001900
1901 switch (II->getIntrinsicID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001902 default: llvm_unreachable("Case stmts out of sync!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001903 case Intrinsic::x86_sse_sub_ss:
1904 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001905 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001906 II->getName()), *II);
1907 break;
1908 case Intrinsic::x86_sse_mul_ss:
1909 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001910 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001911 II->getName()), *II);
1912 break;
1913 }
1914
1915 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001916 InsertElementInst::Create(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001917 UndefValue::get(II->getType()), TmpV,
Owen Anderson35b47072009-08-13 21:58:54 +00001918 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001919 InsertNewInstBefore(New, *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001920 return New;
1921 }
1922 }
1923
1924 // Output elements are undefined if both are undefined. Consider things
1925 // like undef&0. The result is known zero, not undef.
1926 UndefElts &= UndefElts2;
1927 break;
1928 }
1929 break;
1930 }
1931 }
1932 return MadeChange ? I : 0;
1933}
1934
Dan Gohman5d56fd42008-05-19 22:14:15 +00001935
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001936/// AssociativeOpt - Perform an optimization on an associative operator. This
1937/// function is designed to check a chain of associative operators for a
1938/// potential to apply a certain optimization. Since the optimization may be
1939/// applicable if the expression was reassociated, this checks the chain, then
1940/// reassociates the expression as necessary to expose the optimization
1941/// opportunity. This makes use of a special Functor, which must define
1942/// 'shouldApply' and 'apply' methods.
1943///
1944template<typename Functor>
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001945static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001946 unsigned Opcode = Root.getOpcode();
1947 Value *LHS = Root.getOperand(0);
1948
1949 // Quick check, see if the immediate LHS matches...
1950 if (F.shouldApply(LHS))
1951 return F.apply(Root);
1952
1953 // Otherwise, if the LHS is not of the same opcode as the root, return.
1954 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1955 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1956 // Should we apply this transform to the RHS?
1957 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1958
1959 // If not to the RHS, check to see if we should apply to the LHS...
1960 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1961 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1962 ShouldApply = true;
1963 }
1964
1965 // If the functor wants to apply the optimization to the RHS of LHSI,
1966 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1967 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001968 // Now all of the instructions are in the current basic block, go ahead
1969 // and perform the reassociation.
1970 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1971
1972 // First move the selected RHS to the LHS of the root...
1973 Root.setOperand(0, LHSI->getOperand(1));
1974
1975 // Make what used to be the LHS of the root be the user of the root...
1976 Value *ExtraOperand = TmpLHSI->getOperand(1);
1977 if (&Root == TmpLHSI) {
Owen Andersonaac28372009-07-31 20:28:14 +00001978 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001979 return 0;
1980 }
1981 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1982 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001983 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001984 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001985 ARI = Root;
1986
1987 // Now propagate the ExtraOperand down the chain of instructions until we
1988 // get to LHSI.
1989 while (TmpLHSI != LHSI) {
1990 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1991 // Move the instruction to immediately before the chain we are
1992 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001993 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001994 ARI = NextLHSI;
1995
1996 Value *NextOp = NextLHSI->getOperand(1);
1997 NextLHSI->setOperand(1, ExtraOperand);
1998 TmpLHSI = NextLHSI;
1999 ExtraOperand = NextOp;
2000 }
2001
2002 // Now that the instructions are reassociated, have the functor perform
2003 // the transformation...
2004 return F.apply(Root);
2005 }
2006
2007 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2008 }
2009 return 0;
2010}
2011
Dan Gohman089efff2008-05-13 00:00:25 +00002012namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002013
Nick Lewycky27f6c132008-05-23 04:34:58 +00002014// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002015struct AddRHS {
2016 Value *RHS;
Dan Gohmancdff2122009-08-12 16:23:25 +00002017 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002018 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2019 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00002020 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00002021 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002022 }
2023};
2024
2025// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2026// iff C1&C2 == 0
2027struct AddMaskingAnd {
2028 Constant *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00002029 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002030 bool shouldApply(Value *LHS) const {
2031 ConstantInt *C1;
Dan Gohmancdff2122009-08-12 16:23:25 +00002032 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002033 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002034 }
2035 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00002036 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002037 }
2038};
2039
Dan Gohman089efff2008-05-13 00:00:25 +00002040}
2041
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002042static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2043 InstCombiner *IC) {
Chris Lattner78628292009-08-30 19:47:22 +00002044 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattnerd6164c22009-08-30 20:01:10 +00002045 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002046
2047 // Figure out if the constant is the left or the right argument.
2048 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2049 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2050
2051 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2052 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +00002053 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2054 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002055 }
2056
2057 Value *Op0 = SO, *Op1 = ConstOperand;
2058 if (!ConstIsRHS)
2059 std::swap(Op0, Op1);
Chris Lattnerc7694852009-08-30 07:44:24 +00002060
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002061 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattnerc7694852009-08-30 07:44:24 +00002062 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
2063 SO->getName()+".op");
2064 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
2065 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2066 SO->getName()+".cmp");
2067 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2068 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2069 SO->getName()+".cmp");
2070 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002071}
2072
2073// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2074// constant as the other operand, try to fold the binary operator into the
2075// select arguments. This also works for Cast instructions, which obviously do
2076// not have a second operand.
2077static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2078 InstCombiner *IC) {
2079 // Don't modify shared select instructions
2080 if (!SI->hasOneUse()) return 0;
2081 Value *TV = SI->getOperand(1);
2082 Value *FV = SI->getOperand(2);
2083
2084 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2085 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson35b47072009-08-13 21:58:54 +00002086 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002087
2088 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2089 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2090
Gabor Greifd6da1d02008-04-06 20:25:17 +00002091 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2092 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002093 }
2094 return 0;
2095}
2096
2097
Chris Lattnerf7843b72009-09-27 19:57:57 +00002098/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2099/// has a PHI node as operand #0, see if we can fold the instruction into the
2100/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +00002101///
2102/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2103/// that would normally be unprofitable because they strongly encourage jump
2104/// threading.
2105Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2106 bool AllowAggressive) {
2107 AllowAggressive = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002108 PHINode *PN = cast<PHINode>(I.getOperand(0));
2109 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner9b61abd2009-09-27 20:46:36 +00002110 if (NumPHIValues == 0 ||
2111 // We normally only transform phis with a single use, unless we're trying
2112 // hard to make jump threading happen.
2113 (!PN->hasOneUse() && !AllowAggressive))
2114 return 0;
2115
2116
Chris Lattnerf7843b72009-09-27 19:57:57 +00002117 // Check to see if all of the operands of the PHI are simple constants
2118 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002119 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2120 // bail out. We don't do arbitrary constant expressions here because moving
2121 // their computation can be expensive without a cost model.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002122 BasicBlock *NonConstBB = 0;
2123 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattnerf7843b72009-09-27 19:57:57 +00002124 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2125 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002126 if (NonConstBB) return 0; // More than one non-const value.
2127 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2128 NonConstBB = PN->getIncomingBlock(i);
2129
2130 // If the incoming non-constant value is in I's block, we have an infinite
2131 // loop.
2132 if (NonConstBB == I.getParent())
2133 return 0;
2134 }
2135
2136 // If there is exactly one non-constant value, we can insert a copy of the
2137 // operation in that block. However, if this is a critical edge, we would be
2138 // inserting the computation one some other paths (e.g. inside a loop). Only
2139 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9b61abd2009-09-27 20:46:36 +00002140 if (NonConstBB != 0 && !AllowAggressive) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002141 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2142 if (!BI || !BI->isUnconditional()) return 0;
2143 }
2144
2145 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002146 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002147 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner3980f9b2009-10-21 23:41:58 +00002148 InsertNewInstBefore(NewPN, *PN);
2149 NewPN->takeName(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002150
2151 // Next, add all of the operands to the PHI.
Chris Lattnerf7843b72009-09-27 19:57:57 +00002152 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2153 // We only currently try to fold the condition of a select when it is a phi,
2154 // not the true/false values.
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002155 Value *TrueV = SI->getTrueValue();
2156 Value *FalseV = SI->getFalseValue();
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002157 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerf7843b72009-09-27 19:57:57 +00002158 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002159 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002160 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2161 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002162 Value *InV = 0;
2163 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002164 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerf7843b72009-09-27 19:57:57 +00002165 } else {
2166 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002167 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2168 FalseVInPred,
Chris Lattnerf7843b72009-09-27 19:57:57 +00002169 "phitmp", NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +00002170 Worklist.Add(cast<Instruction>(InV));
Chris Lattnerf7843b72009-09-27 19:57:57 +00002171 }
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002172 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002173 }
2174 } else if (I.getNumOperands() == 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002175 Constant *C = cast<Constant>(I.getOperand(1));
2176 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002177 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002178 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2179 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +00002180 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002181 else
Owen Anderson02b48c32009-07-29 18:55:55 +00002182 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002183 } else {
2184 assert(PN->getIncomingBlock(i) == NonConstBB);
2185 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002186 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002187 PN->getIncomingValue(i), C, "phitmp",
2188 NonConstBB->getTerminator());
2189 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +00002190 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002191 CI->getPredicate(),
2192 PN->getIncomingValue(i), C, "phitmp",
2193 NonConstBB->getTerminator());
2194 else
Edwin Törökbd448e32009-07-14 16:55:14 +00002195 llvm_unreachable("Unknown binop!");
Chris Lattner3980f9b2009-10-21 23:41:58 +00002196
2197 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002198 }
2199 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2200 }
2201 } else {
2202 CastInst *CI = cast<CastInst>(&I);
2203 const Type *RetTy = CI->getType();
2204 for (unsigned i = 0; i != NumPHIValues; ++i) {
2205 Value *InV;
2206 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002207 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002208 } else {
2209 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002210 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002211 I.getType(), "phitmp",
2212 NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +00002213 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002214 }
2215 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2216 }
2217 }
2218 return ReplaceInstUsesWith(I, NewPN);
2219}
2220
Chris Lattner55476162008-01-29 06:52:45 +00002221
Chris Lattner3554f972008-05-20 05:46:13 +00002222/// WillNotOverflowSignedAdd - Return true if we can prove that:
2223/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2224/// This basically requires proving that the add in the original type would not
2225/// overflow to change the sign bit or have a carry out.
2226bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2227 // There are different heuristics we can use for this. Here are some simple
2228 // ones.
2229
2230 // Add has the property that adding any two 2's complement numbers can only
2231 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner96076f72009-11-27 17:42:22 +00002232 // have at least two sign bits, we know that the addition of the two values
2233 // will sign extend fine.
Chris Lattner3554f972008-05-20 05:46:13 +00002234 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2235 return true;
2236
2237
2238 // If one of the operands only has one non-zero bit, and if the other operand
2239 // has a known-zero bit in a more significant place than it (not including the
2240 // sign bit) the ripple may go up to and fill the zero, but won't change the
2241 // sign. For example, (X & ~4) + 1.
2242
2243 // TODO: Implement.
2244
2245 return false;
2246}
2247
Chris Lattner55476162008-01-29 06:52:45 +00002248
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002249Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2250 bool Changed = SimplifyCommutative(I);
2251 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2252
Chris Lattner96076f72009-11-27 17:42:22 +00002253 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2254 I.hasNoUnsignedWrap(), TD))
2255 return ReplaceInstUsesWith(I, V);
2256
2257
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002258 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002259 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2260 // X + (signbit) --> X ^ signbit
2261 const APInt& Val = CI->getValue();
2262 uint32_t BitWidth = Val.getBitWidth();
2263 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002264 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002265
2266 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2267 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002268 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002269 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002270
Eli Friedmana21526d2009-07-13 22:27:52 +00002271 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +00002272 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson35b47072009-08-13 21:58:54 +00002273 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002274 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002275 }
2276
2277 if (isa<PHINode>(LHS))
2278 if (Instruction *NV = FoldOpIntoPhi(I))
2279 return NV;
2280
2281 ConstantInt *XorRHS = 0;
2282 Value *XorLHS = 0;
2283 if (isa<ConstantInt>(RHSC) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002284 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002285 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002286 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2287
2288 uint32_t Size = TySizeBits / 2;
2289 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2290 APInt CFF80Val(-C0080Val);
2291 do {
2292 if (TySizeBits > Size) {
2293 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2294 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2295 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2296 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2297 // This is a sign extend if the top bits are known zero.
2298 if (!MaskedValueIsZero(XorLHS,
2299 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2300 Size = 0; // Not a sign ext, but can't be any others either.
2301 break;
2302 }
2303 }
2304 Size >>= 1;
2305 C0080Val = APIntOps::lshr(C0080Val, Size);
2306 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2307 } while (Size >= 1);
2308
2309 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002310 // with funny bit widths then this switch statement should be removed. It
2311 // is just here to get the size of the "middle" type back up to something
2312 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002313 const Type *MiddleType = 0;
2314 switch (Size) {
2315 default: break;
Owen Anderson35b47072009-08-13 21:58:54 +00002316 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2317 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2318 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002319 }
2320 if (MiddleType) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002321 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002322 return new SExtInst(NewTrunc, I.getType(), I.getName());
2323 }
2324 }
2325 }
2326
Owen Anderson35b47072009-08-13 21:58:54 +00002327 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002328 return BinaryOperator::CreateXor(LHS, RHS);
2329
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002330 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002331 if (I.getType()->isInteger()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00002332 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Anderson24be4c12009-07-03 00:17:18 +00002333 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002334
2335 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2336 if (RHSI->getOpcode() == Instruction::Sub)
2337 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2338 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2339 }
2340 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2341 if (LHSI->getOpcode() == Instruction::Sub)
2342 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2343 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2344 }
2345 }
2346
2347 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002348 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002349 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002350 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002351 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002352 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohmancdff2122009-08-12 16:23:25 +00002353 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002354 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002355 }
2356
Gabor Greifa645dd32008-05-16 19:29:10 +00002357 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002358 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002359
2360 // A + -B --> A - B
2361 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002362 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002363 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002364
2365
2366 ConstantInt *C2;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002367 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002368 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002369 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002370
2371 // X*C1 + X*C2 --> X * (C1+C2)
2372 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002373 if (X == dyn_castFoldableMul(RHS, C1))
Owen Anderson02b48c32009-07-29 18:55:55 +00002374 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002375 }
2376
2377 // X + X*C --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002378 if (dyn_castFoldableMul(RHS, C2) == LHS)
2379 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002380
2381 // X + ~X --> -1 since ~X = -X-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002382 if (dyn_castNotVal(LHS) == RHS ||
2383 dyn_castNotVal(RHS) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +00002384 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002385
2386
2387 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00002388 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2389 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002390 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002391
2392 // A+B --> A|B iff A and B have no bits set in common.
2393 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2394 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2395 APInt LHSKnownOne(IT->getBitWidth(), 0);
2396 APInt LHSKnownZero(IT->getBitWidth(), 0);
2397 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2398 if (LHSKnownZero != 0) {
2399 APInt RHSKnownOne(IT->getBitWidth(), 0);
2400 APInt RHSKnownZero(IT->getBitWidth(), 0);
2401 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2402
2403 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002404 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002405 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002406 }
2407 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002408
Nick Lewycky83598a72008-02-03 07:42:09 +00002409 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002410 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002411 Value *W, *X, *Y, *Z;
Dan Gohmancdff2122009-08-12 16:23:25 +00002412 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2413 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002414 if (W != Y) {
2415 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002416 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002417 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002418 std::swap(W, X);
2419 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002420 std::swap(Y, Z);
2421 std::swap(W, X);
2422 }
2423 }
2424
2425 if (W == Y) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002426 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002427 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002428 }
2429 }
2430 }
2431
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002432 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2433 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002434 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002435 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002436
2437 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002438 if (LHS->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002439 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002440 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002441 if (Anded == CRHS) {
2442 // See if all bits from the first bit set in the Add RHS up are included
2443 // in the mask. First, get the rightmost bit.
2444 const APInt& AddRHSV = CRHS->getValue();
2445
2446 // Form a mask of all bits from the lowest bit added through the top.
2447 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2448
2449 // See if the and mask includes all of these bits.
2450 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2451
2452 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2453 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattnerc7694852009-08-30 07:44:24 +00002454 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002455 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002456 }
2457 }
2458 }
2459
2460 // Try to fold constant add into select arguments.
2461 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2462 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2463 return R;
2464 }
2465
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002466 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002467 {
2468 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002469 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002470 if (!SI) {
2471 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002472 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002473 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002474 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002475 Value *TV = SI->getTrueValue();
2476 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002477 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002478
2479 // Can we fold the add into the argument of the select?
2480 // We check both true and false select arguments for a matching subtract.
Dan Gohmancdff2122009-08-12 16:23:25 +00002481 if (match(FV, m_Zero()) &&
2482 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002483 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002484 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohmancdff2122009-08-12 16:23:25 +00002485 if (match(TV, m_Zero()) &&
2486 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002487 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002488 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002489 }
2490 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002491
Chris Lattner3554f972008-05-20 05:46:13 +00002492 // Check for (add (sext x), y), see if we can merge this into an
2493 // integer add followed by a sext.
2494 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2495 // (add (sext x), cst) --> (sext (add x, cst'))
2496 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2497 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002498 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002499 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002500 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002501 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2502 // Insert the new, smaller add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002503 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2504 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002505 return new SExtInst(NewAdd, I.getType());
2506 }
2507 }
2508
2509 // (add (sext x), (sext y)) --> (sext (add int x, y))
2510 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2511 // Only do this if x/y have the same type, if at last one of them has a
2512 // single use (so we don't increase the number of sexts), and if the
2513 // integer add will not overflow.
2514 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2515 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2516 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2517 RHSConv->getOperand(0))) {
2518 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002519 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2520 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002521 return new SExtInst(NewAdd, I.getType());
2522 }
2523 }
2524 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002525
2526 return Changed ? &I : 0;
2527}
2528
2529Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2530 bool Changed = SimplifyCommutative(I);
2531 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2532
2533 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2534 // X + 0 --> X
2535 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +00002536 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002537 (I.getType())->getValueAPF()))
2538 return ReplaceInstUsesWith(I, LHS);
2539 }
2540
2541 if (isa<PHINode>(LHS))
2542 if (Instruction *NV = FoldOpIntoPhi(I))
2543 return NV;
2544 }
2545
2546 // -A + B --> B - A
2547 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002548 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002549 return BinaryOperator::CreateFSub(RHS, LHSV);
2550
2551 // A + -B --> A - B
2552 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002553 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002554 return BinaryOperator::CreateFSub(LHS, V);
2555
2556 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2557 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2558 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2559 return ReplaceInstUsesWith(I, LHS);
2560
Chris Lattner3554f972008-05-20 05:46:13 +00002561 // Check for (add double (sitofp x), y), see if we can merge this into an
2562 // integer add followed by a promotion.
2563 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2564 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2565 // ... if the constant fits in the integer value. This is useful for things
2566 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2567 // requires a constant pool load, and generally allows the add to be better
2568 // instcombined.
2569 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2570 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002571 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002572 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002573 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002574 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2575 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002576 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2577 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002578 return new SIToFPInst(NewAdd, I.getType());
2579 }
2580 }
2581
2582 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2583 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2584 // Only do this if x/y have the same type, if at last one of them has a
2585 // single use (so we don't increase the number of int->fp conversions),
2586 // and if the integer add will not overflow.
2587 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2588 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2589 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2590 RHSConv->getOperand(0))) {
2591 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002592 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner93e6ff92009-11-04 08:05:20 +00002593 RHSConv->getOperand(0),"addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002594 return new SIToFPInst(NewAdd, I.getType());
2595 }
2596 }
2597 }
2598
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002599 return Changed ? &I : 0;
2600}
2601
Chris Lattner93e6ff92009-11-04 08:05:20 +00002602
2603/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2604/// code necessary to compute the offset from the base pointer (without adding
2605/// in the base pointer). Return the result as a signed integer of intptr size.
2606static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2607 TargetData &TD = *IC.getTargetData();
2608 gep_type_iterator GTI = gep_type_begin(GEP);
2609 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2610 Value *Result = Constant::getNullValue(IntPtrTy);
2611
2612 // Build a mask for high order bits.
2613 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2614 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2615
2616 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2617 ++i, ++GTI) {
2618 Value *Op = *i;
2619 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2620 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2621 if (OpC->isZero()) continue;
2622
2623 // Handle a struct index, which adds its field offset to the pointer.
2624 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2625 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2626
2627 Result = IC.Builder->CreateAdd(Result,
2628 ConstantInt::get(IntPtrTy, Size),
2629 GEP->getName()+".offs");
2630 continue;
2631 }
2632
2633 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2634 Constant *OC =
2635 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2636 Scale = ConstantExpr::getMul(OC, Scale);
2637 // Emit an add instruction.
2638 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2639 continue;
2640 }
2641 // Convert to correct type.
2642 if (Op->getType() != IntPtrTy)
2643 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2644 if (Size != 1) {
2645 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2646 // We'll let instcombine(mul) convert this to a shl if possible.
2647 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2648 }
2649
2650 // Emit an add instruction.
2651 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2652 }
2653 return Result;
2654}
2655
2656
2657/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2658/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2659/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2660/// be complex, and scales are involved. The above expression would also be
2661/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2662/// This later form is less amenable to optimization though, and we are allowed
2663/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2664///
2665/// If we can't emit an optimized form for this expression, this returns null.
2666///
2667static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2668 InstCombiner &IC) {
2669 TargetData &TD = *IC.getTargetData();
2670 gep_type_iterator GTI = gep_type_begin(GEP);
2671
2672 // Check to see if this gep only has a single variable index. If so, and if
2673 // any constant indices are a multiple of its scale, then we can compute this
2674 // in terms of the scale of the variable index. For example, if the GEP
2675 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2676 // because the expression will cross zero at the same point.
2677 unsigned i, e = GEP->getNumOperands();
2678 int64_t Offset = 0;
2679 for (i = 1; i != e; ++i, ++GTI) {
2680 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2681 // Compute the aggregate offset of constant indices.
2682 if (CI->isZero()) continue;
2683
2684 // Handle a struct index, which adds its field offset to the pointer.
2685 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2686 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2687 } else {
2688 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2689 Offset += Size*CI->getSExtValue();
2690 }
2691 } else {
2692 // Found our variable index.
2693 break;
2694 }
2695 }
2696
2697 // If there are no variable indices, we must have a constant offset, just
2698 // evaluate it the general way.
2699 if (i == e) return 0;
2700
2701 Value *VariableIdx = GEP->getOperand(i);
2702 // Determine the scale factor of the variable element. For example, this is
2703 // 4 if the variable index is into an array of i32.
2704 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2705
2706 // Verify that there are no other variable indices. If so, emit the hard way.
2707 for (++i, ++GTI; i != e; ++i, ++GTI) {
2708 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2709 if (!CI) return 0;
2710
2711 // Compute the aggregate offset of constant indices.
2712 if (CI->isZero()) continue;
2713
2714 // Handle a struct index, which adds its field offset to the pointer.
2715 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2716 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2717 } else {
2718 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2719 Offset += Size*CI->getSExtValue();
2720 }
2721 }
2722
2723 // Okay, we know we have a single variable index, which must be a
2724 // pointer/array/vector index. If there is no offset, life is simple, return
2725 // the index.
2726 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2727 if (Offset == 0) {
2728 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2729 // we don't need to bother extending: the extension won't affect where the
2730 // computation crosses zero.
2731 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2732 VariableIdx = new TruncInst(VariableIdx,
2733 TD.getIntPtrType(VariableIdx->getContext()),
2734 VariableIdx->getName(), &I);
2735 return VariableIdx;
2736 }
2737
2738 // Otherwise, there is an index. The computation we will do will be modulo
2739 // the pointer size, so get it.
2740 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2741
2742 Offset &= PtrSizeMask;
2743 VariableScale &= PtrSizeMask;
2744
2745 // To do this transformation, any constant index must be a multiple of the
2746 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2747 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2748 // multiple of the variable scale.
2749 int64_t NewOffs = Offset / (int64_t)VariableScale;
2750 if (Offset != NewOffs*(int64_t)VariableScale)
2751 return 0;
2752
2753 // Okay, we can do this evaluation. Start by converting the index to intptr.
2754 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2755 if (VariableIdx->getType() != IntPtrTy)
2756 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2757 true /*SExt*/,
2758 VariableIdx->getName(), &I);
2759 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2760 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2761}
2762
2763
2764/// Optimize pointer differences into the same array into a size. Consider:
2765/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2766/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2767///
2768Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2769 const Type *Ty) {
2770 assert(TD && "Must have target data info for this");
2771
2772 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2773 // this.
2774 bool Swapped;
Chris Lattner08be8ff2010-01-01 22:42:29 +00002775 GetElementPtrInst *GEP = 0;
2776 ConstantExpr *CstGEP = 0;
Chris Lattner93e6ff92009-11-04 08:05:20 +00002777
Chris Lattner08be8ff2010-01-01 22:42:29 +00002778 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
2779 // For now we require one side to be the base pointer "A" or a constant
2780 // expression derived from it.
2781 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
2782 // (gep X, ...) - X
2783 if (LHSGEP->getOperand(0) == RHS) {
2784 GEP = LHSGEP;
2785 Swapped = false;
2786 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
2787 // (gep X, ...) - (ce_gep X, ...)
2788 if (CE->getOpcode() == Instruction::GetElementPtr &&
2789 LHSGEP->getOperand(0) == CE->getOperand(0)) {
2790 CstGEP = CE;
2791 GEP = LHSGEP;
2792 Swapped = false;
2793 }
2794 }
2795 }
2796
2797 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
2798 // X - (gep X, ...)
2799 if (RHSGEP->getOperand(0) == LHS) {
2800 GEP = RHSGEP;
2801 Swapped = true;
2802 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
2803 // (ce_gep X, ...) - (gep X, ...)
2804 if (CE->getOpcode() == Instruction::GetElementPtr &&
2805 RHSGEP->getOperand(0) == CE->getOperand(0)) {
2806 CstGEP = CE;
2807 GEP = RHSGEP;
2808 Swapped = true;
2809 }
2810 }
2811 }
2812
2813 if (GEP == 0)
Chris Lattner93e6ff92009-11-04 08:05:20 +00002814 return 0;
2815
Chris Lattner93e6ff92009-11-04 08:05:20 +00002816 // Emit the offset of the GEP and an intptr_t.
2817 Value *Result = EmitGEPOffset(GEP, *this);
Chris Lattner08be8ff2010-01-01 22:42:29 +00002818
2819 // If we had a constant expression GEP on the other side offsetting the
2820 // pointer, subtract it from the offset we have.
2821 if (CstGEP) {
2822 Value *CstOffset = EmitGEPOffset(CstGEP, *this);
2823 Result = Builder->CreateSub(Result, CstOffset);
2824 }
2825
Chris Lattner93e6ff92009-11-04 08:05:20 +00002826
2827 // If we have p - gep(p, ...) then we have to negate the result.
2828 if (Swapped)
2829 Result = Builder->CreateNeg(Result, "diff.neg");
2830
2831 return Builder->CreateIntCast(Result, Ty, true);
2832}
2833
2834
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002835Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2836 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2837
Dan Gohman7ce405e2009-06-04 22:49:04 +00002838 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002839 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002840
Chris Lattnera54b96b2009-12-21 04:04:05 +00002841 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
2842 if (Value *V = dyn_castNegVal(Op1)) {
2843 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2844 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
2845 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
2846 return Res;
2847 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002848
2849 if (isa<UndefValue>(Op0))
2850 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2851 if (isa<UndefValue>(Op1))
2852 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner93e6ff92009-11-04 08:05:20 +00002853 if (I.getType() == Type::getInt1Ty(*Context))
2854 return BinaryOperator::CreateXor(Op0, Op1);
2855
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002856 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner93e6ff92009-11-04 08:05:20 +00002857 // Replace (-1 - A) with (~A).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002858 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00002859 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002860
2861 // C - ~X == X + (1+C)
2862 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002863 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002864 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002865
2866 // -(X >>u 31) -> (X >>s 31)
2867 // -(X >>s 31) -> (X >>u 31)
2868 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002869 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002870 if (SI->getOpcode() == Instruction::LShr) {
2871 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2872 // Check to see if we are shifting out everything but the sign bit.
2873 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2874 SI->getType()->getPrimitiveSizeInBits()-1) {
2875 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002876 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002877 SI->getOperand(0), CU, SI->getName());
2878 }
2879 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00002880 } else if (SI->getOpcode() == Instruction::AShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002881 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2882 // Check to see if we are shifting out everything but the sign bit.
2883 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2884 SI->getType()->getPrimitiveSizeInBits()-1) {
2885 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002886 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002887 SI->getOperand(0), CU, SI->getName());
2888 }
2889 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002890 }
2891 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002892 }
2893
2894 // Try to fold constant sub into select arguments.
2895 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2896 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2897 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002898
2899 // C - zext(bool) -> bool ? C - 1 : C
2900 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson35b47072009-08-13 21:58:54 +00002901 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002902 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002903 }
2904
2905 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002906 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002907 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002908 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002909 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002910 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002911 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002912 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002913 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2914 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2915 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002916 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002917 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002918 }
2919 }
2920
2921 if (Op1I->hasOneUse()) {
2922 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2923 // is not used by anyone else...
2924 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002925 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002926 // Swap the two operands of the subexpr...
2927 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2928 Op1I->setOperand(0, IIOp1);
2929 Op1I->setOperand(1, IIOp0);
2930
2931 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002932 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002933 }
2934
2935 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2936 //
2937 if (Op1I->getOpcode() == Instruction::And &&
2938 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2939 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2940
Chris Lattnerc7694852009-08-30 07:44:24 +00002941 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greifa645dd32008-05-16 19:29:10 +00002942 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002943 }
2944
2945 // 0 - (X sdiv C) -> (X sdiv -C)
2946 if (Op1I->getOpcode() == Instruction::SDiv)
2947 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2948 if (CSI->isZero())
2949 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002950 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002951 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002952
2953 // X - X*C --> X * (1-C)
2954 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002955 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002956 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00002957 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002958 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002959 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002960 }
2961 }
2962 }
2963
Dan Gohman7ce405e2009-06-04 22:49:04 +00002964 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2965 if (Op0I->getOpcode() == Instruction::Add) {
2966 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2967 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2968 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2969 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2970 } else if (Op0I->getOpcode() == Instruction::Sub) {
2971 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002972 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002973 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002974 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002975 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002976
2977 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002978 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002979 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002980 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002981
2982 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002983 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00002984 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002985 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00002986
2987 // Optimize pointer differences into the same array into a size. Consider:
2988 // &A[10] - &A[0]: we should compile this to "10".
2989 if (TD) {
Chris Lattnerc49d68a2010-01-01 22:12:03 +00002990 Value *LHSOp, *RHSOp;
Chris Lattnerc93843f2010-01-01 22:29:12 +00002991 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
2992 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattnerc49d68a2010-01-01 22:12:03 +00002993 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2994 return ReplaceInstUsesWith(I, Res);
Chris Lattner93e6ff92009-11-04 08:05:20 +00002995
2996 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerc93843f2010-01-01 22:29:12 +00002997 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
2998 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
2999 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
3000 return ReplaceInstUsesWith(I, Res);
Chris Lattner93e6ff92009-11-04 08:05:20 +00003001 }
3002
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003003 return 0;
3004}
3005
Dan Gohman7ce405e2009-06-04 22:49:04 +00003006Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
3007 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3008
3009 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003010 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00003011 return BinaryOperator::CreateFAdd(Op0, V);
3012
3013 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
3014 if (Op1I->getOpcode() == Instruction::FAdd) {
3015 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00003016 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00003017 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00003018 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00003019 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00003020 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00003021 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00003022 }
3023
3024 return 0;
3025}
3026
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003027/// isSignBitCheck - Given an exploded icmp instruction, return true if the
3028/// comparison only checks the sign bit. If it only checks the sign bit, set
3029/// TrueIfSigned if the result of the comparison is true when the input value is
3030/// signed.
3031static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3032 bool &TrueIfSigned) {
3033 switch (pred) {
3034 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3035 TrueIfSigned = true;
3036 return RHS->isZero();
3037 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3038 TrueIfSigned = true;
3039 return RHS->isAllOnesValue();
3040 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3041 TrueIfSigned = false;
3042 return RHS->isAllOnesValue();
3043 case ICmpInst::ICMP_UGT:
3044 // True if LHS u> RHS and RHS == high-bit-mask - 1
3045 TrueIfSigned = true;
3046 return RHS->getValue() ==
3047 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3048 case ICmpInst::ICMP_UGE:
3049 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3050 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00003051 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003052 default:
3053 return false;
3054 }
3055}
3056
3057Instruction *InstCombiner::visitMul(BinaryOperator &I) {
3058 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00003059 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003060
Chris Lattner3508c5c2009-10-11 21:36:10 +00003061 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00003062 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003063
Chris Lattner6438c582009-10-11 07:53:15 +00003064 // Simplify mul instructions with a constant RHS.
Chris Lattner3508c5c2009-10-11 21:36:10 +00003065 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3066 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003067
3068 // ((X << C1)*C2) == (X * (C2 << C1))
3069 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
3070 if (SI->getOpcode() == Instruction::Shl)
3071 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00003072 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00003073 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003074
3075 if (CI->isZero())
Chris Lattner3508c5c2009-10-11 21:36:10 +00003076 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003077 if (CI->equalsInt(1)) // X * 1 == X
3078 return ReplaceInstUsesWith(I, Op0);
3079 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00003080 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003081
3082 const APInt& Val = cast<ConstantInt>(CI)->getValue();
3083 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00003084 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003085 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003086 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00003087 } else if (isa<VectorType>(Op1C->getType())) {
3088 if (Op1C->isNullValue())
3089 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky94418732008-11-27 20:21:08 +00003090
Chris Lattner3508c5c2009-10-11 21:36:10 +00003091 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky94418732008-11-27 20:21:08 +00003092 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00003093 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00003094
3095 // As above, vector X*splat(1.0) -> X in all defined cases.
3096 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00003097 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
3098 if (CI->equalsInt(1))
3099 return ReplaceInstUsesWith(I, Op0);
3100 }
3101 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003102 }
3103
3104 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3105 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00003106 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003107 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner3508c5c2009-10-11 21:36:10 +00003108 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3109 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greifa645dd32008-05-16 19:29:10 +00003110 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003111
3112 }
3113
3114 // Try to fold constant mul into select arguments.
3115 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3116 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3117 return R;
3118
3119 if (isa<PHINode>(Op0))
3120 if (Instruction *NV = FoldOpIntoPhi(I))
3121 return NV;
3122 }
3123
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003124 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00003125 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00003126 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003127
Nick Lewycky1c246402008-11-21 07:33:58 +00003128 // (X / Y) * Y = X - (X % Y)
3129 // (X / Y) * -Y = (X % Y) - X
3130 {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003131 Value *Op1C = Op1;
Nick Lewycky1c246402008-11-21 07:33:58 +00003132 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3133 if (!BO ||
3134 (BO->getOpcode() != Instruction::UDiv &&
3135 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003136 Op1C = Op0;
3137 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00003138 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00003139 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky1c246402008-11-21 07:33:58 +00003140 if (BO && BO->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00003141 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky1c246402008-11-21 07:33:58 +00003142 (BO->getOpcode() == Instruction::UDiv ||
3143 BO->getOpcode() == Instruction::SDiv)) {
3144 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3145
Dan Gohman07878902009-08-12 16:33:09 +00003146 // If the division is exact, X % Y is zero.
3147 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3148 if (SDiv->isExact()) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003149 if (Op1BO == Op1C)
Dan Gohman07878902009-08-12 16:33:09 +00003150 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattner3508c5c2009-10-11 21:36:10 +00003151 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohman07878902009-08-12 16:33:09 +00003152 }
3153
Chris Lattnerc7694852009-08-30 07:44:24 +00003154 Value *Rem;
Nick Lewycky1c246402008-11-21 07:33:58 +00003155 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattnerc7694852009-08-30 07:44:24 +00003156 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003157 else
Chris Lattnerc7694852009-08-30 07:44:24 +00003158 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003159 Rem->takeName(BO);
3160
Chris Lattner3508c5c2009-10-11 21:36:10 +00003161 if (Op1BO == Op1C)
Nick Lewycky1c246402008-11-21 07:33:58 +00003162 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattnerc7694852009-08-30 07:44:24 +00003163 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003164 }
3165 }
3166
Chris Lattner6438c582009-10-11 07:53:15 +00003167 /// i1 mul -> i1 and.
Owen Anderson35b47072009-08-13 21:58:54 +00003168 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003169 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003170
Chris Lattner6438c582009-10-11 07:53:15 +00003171 // X*(1 << Y) --> X << Y
3172 // (1 << Y)*X --> X << Y
3173 {
3174 Value *Y;
3175 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003176 return BinaryOperator::CreateShl(Op1, Y);
3177 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner6438c582009-10-11 07:53:15 +00003178 return BinaryOperator::CreateShl(Op0, Y);
3179 }
3180
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003181 // If one of the operands of the multiply is a cast from a boolean value, then
3182 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattner4ca76f72009-10-11 21:29:45 +00003183 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3184 if (!isa<VectorType>(I.getType())) {
3185 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenb5887062009-10-12 18:45:32 +00003186 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner291872e2009-10-11 21:22:21 +00003187
Chris Lattner4ca76f72009-10-11 21:29:45 +00003188 Value *BoolCast = 0, *OtherOp = 0;
3189 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003190 BoolCast = Op0, OtherOp = Op1;
3191 else if (MaskedValueIsZero(Op1, Negative2))
3192 BoolCast = Op1, OtherOp = Op0;
Chris Lattner4ca76f72009-10-11 21:29:45 +00003193
Chris Lattner291872e2009-10-11 21:22:21 +00003194 if (BoolCast) {
Chris Lattner291872e2009-10-11 21:22:21 +00003195 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3196 BoolCast, "tmp");
3197 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003198 }
3199 }
3200
3201 return Changed ? &I : 0;
3202}
3203
Dan Gohman7ce405e2009-06-04 22:49:04 +00003204Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3205 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00003206 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohman7ce405e2009-06-04 22:49:04 +00003207
3208 // Simplify mul instructions with a constant RHS...
Chris Lattner3508c5c2009-10-11 21:36:10 +00003209 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3210 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00003211 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3212 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3213 if (Op1F->isExactlyValue(1.0))
3214 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattner3508c5c2009-10-11 21:36:10 +00003215 } else if (isa<VectorType>(Op1C->getType())) {
3216 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00003217 // As above, vector X*splat(1.0) -> X in all defined cases.
3218 if (Constant *Splat = Op1V->getSplatValue()) {
3219 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3220 if (F->isExactlyValue(1.0))
3221 return ReplaceInstUsesWith(I, Op0);
3222 }
3223 }
3224 }
3225
3226 // Try to fold constant mul into select arguments.
3227 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3228 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3229 return R;
3230
3231 if (isa<PHINode>(Op0))
3232 if (Instruction *NV = FoldOpIntoPhi(I))
3233 return NV;
3234 }
3235
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003236 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00003237 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00003238 return BinaryOperator::CreateFMul(Op0v, Op1v);
3239
3240 return Changed ? &I : 0;
3241}
3242
Chris Lattner76972db2008-07-14 00:15:52 +00003243/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3244/// instruction.
3245bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3246 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3247
3248 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3249 int NonNullOperand = -1;
3250 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3251 if (ST->isNullValue())
3252 NonNullOperand = 2;
3253 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3254 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3255 if (ST->isNullValue())
3256 NonNullOperand = 1;
3257
3258 if (NonNullOperand == -1)
3259 return false;
3260
3261 Value *SelectCond = SI->getOperand(0);
3262
3263 // Change the div/rem to use 'Y' instead of the select.
3264 I.setOperand(1, SI->getOperand(NonNullOperand));
3265
3266 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3267 // problem. However, the select, or the condition of the select may have
3268 // multiple uses. Based on our knowledge that the operand must be non-zero,
3269 // propagate the known value for the select into other uses of it, and
3270 // propagate a known value of the condition into its other users.
3271
3272 // If the select and condition only have a single use, don't bother with this,
3273 // early exit.
3274 if (SI->use_empty() && SelectCond->hasOneUse())
3275 return true;
3276
3277 // Scan the current block backward, looking for other uses of SI.
3278 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3279
3280 while (BBI != BBFront) {
3281 --BBI;
3282 // If we found a call to a function, we can't assume it will return, so
3283 // information from below it cannot be propagated above it.
3284 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3285 break;
3286
3287 // Replace uses of the select or its condition with the known values.
3288 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3289 I != E; ++I) {
3290 if (*I == SI) {
3291 *I = SI->getOperand(NonNullOperand);
Chris Lattner3183fb62009-08-30 06:13:40 +00003292 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00003293 } else if (*I == SelectCond) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00003294 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3295 ConstantInt::getFalse(*Context);
Chris Lattner3183fb62009-08-30 06:13:40 +00003296 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00003297 }
3298 }
3299
3300 // If we past the instruction, quit looking for it.
3301 if (&*BBI == SI)
3302 SI = 0;
3303 if (&*BBI == SelectCond)
3304 SelectCond = 0;
3305
3306 // If we ran out of things to eliminate, break out of the loop.
3307 if (SelectCond == 0 && SI == 0)
3308 break;
3309
3310 }
3311 return true;
3312}
3313
3314
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003315/// This function implements the transforms on div instructions that work
3316/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3317/// used by the visitors to those instructions.
3318/// @brief Transforms common to all three div instructions
3319Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3320 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3321
Chris Lattner653ef3c2008-02-19 06:12:18 +00003322 // undef / X -> 0 for integer.
3323 // undef / X -> undef for FP (the undef could be a snan).
3324 if (isa<UndefValue>(Op0)) {
3325 if (Op0->getType()->isFPOrFPVector())
3326 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00003327 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003328 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003329
3330 // X / undef -> undef
3331 if (isa<UndefValue>(Op1))
3332 return ReplaceInstUsesWith(I, Op1);
3333
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003334 return 0;
3335}
3336
3337/// This function implements the transforms common to both integer division
3338/// instructions (udiv and sdiv). It is called by the visitors to those integer
3339/// division instructions.
3340/// @brief Common integer divide transforms
3341Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3342 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3343
Chris Lattnercefb36c2008-05-16 02:59:42 +00003344 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00003345 if (Op0 == Op1) {
3346 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00003347 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00003348 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00003349 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00003350 }
3351
Owen Andersoneacb44d2009-07-24 23:12:02 +00003352 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00003353 return ReplaceInstUsesWith(I, CI);
3354 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00003355
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003356 if (Instruction *Common = commonDivTransforms(I))
3357 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00003358
3359 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3360 // This does not apply for fdiv.
3361 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3362 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003363
3364 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3365 // div X, 1 == X
3366 if (RHS->equalsInt(1))
3367 return ReplaceInstUsesWith(I, Op0);
3368
3369 // (X / C1) / C2 -> X / (C1*C2)
3370 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3371 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3372 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00003373 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003374 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00003375 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00003376 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003377 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00003378 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003379 }
3380
3381 if (!RHS->isZero()) { // avoid X udiv 0
3382 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3383 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3384 return R;
3385 if (isa<PHINode>(Op0))
3386 if (Instruction *NV = FoldOpIntoPhi(I))
3387 return NV;
3388 }
3389 }
3390
3391 // 0 / X == 0, we don't need to preserve faults!
3392 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3393 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00003394 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003395
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003396 // It can't be division by zero, hence it must be division by one.
Owen Anderson35b47072009-08-13 21:58:54 +00003397 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003398 return ReplaceInstUsesWith(I, Op0);
3399
Nick Lewycky94418732008-11-27 20:21:08 +00003400 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3401 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3402 // div X, 1 == X
3403 if (X->isOne())
3404 return ReplaceInstUsesWith(I, Op0);
3405 }
3406
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003407 return 0;
3408}
3409
3410Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3411 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3412
3413 // Handle the integer div common cases
3414 if (Instruction *Common = commonIDivTransforms(I))
3415 return Common;
3416
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003417 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00003418 // X udiv C^2 -> X >> C
3419 // Check to see if this is an unsigned division with an exact power of 2,
3420 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003421 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003422 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003423 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003424
3425 // X udiv C, where C >= signbit
3426 if (C->getValue().isNegative()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003427 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersonaac28372009-07-31 20:28:14 +00003428 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003429 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003430 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003431 }
3432
3433 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3434 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3435 if (RHSI->getOpcode() == Instruction::Shl &&
3436 isa<ConstantInt>(RHSI->getOperand(0))) {
3437 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3438 if (C1.isPowerOf2()) {
3439 Value *N = RHSI->getOperand(1);
3440 const Type *NTy = N->getType();
Chris Lattnerc7694852009-08-30 07:44:24 +00003441 if (uint32_t C2 = C1.logBase2())
3442 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003443 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003444 }
3445 }
3446 }
3447
3448 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3449 // where C1&C2 are powers of two.
3450 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3451 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3452 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3453 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3454 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3455 // Compute the shift amounts
3456 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3457 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003458 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003459 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003460
3461 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003462 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003463 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003464
3465 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003466 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003467 }
3468 }
3469 return 0;
3470}
3471
3472Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3473 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3474
3475 // Handle the integer div common cases
3476 if (Instruction *Common = commonIDivTransforms(I))
3477 return Common;
3478
3479 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3480 // sdiv X, -1 == -X
3481 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00003482 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00003483
Dan Gohman07878902009-08-12 16:33:09 +00003484 // sdiv X, C --> ashr X, log2(C)
Dan Gohman31b6b132009-08-11 20:47:47 +00003485 if (cast<SDivOperator>(&I)->isExact() &&
3486 RHS->getValue().isNonNegative() &&
3487 RHS->getValue().isPowerOf2()) {
3488 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3489 RHS->getValue().exactLogBase2());
3490 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3491 }
Dan Gohman5ce93b32009-08-12 16:37:02 +00003492
3493 // -X/C --> X/-C provided the negation doesn't overflow.
3494 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3495 if (isa<Constant>(Sub->getOperand(0)) &&
3496 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohmanb5ed4492009-08-20 17:11:38 +00003497 Sub->hasNoSignedWrap())
Dan Gohman5ce93b32009-08-12 16:37:02 +00003498 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3499 ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003500 }
3501
3502 // If the sign bits of both operands are zero (i.e. we can prove they are
3503 // unsigned inputs), turn this into a udiv.
3504 if (I.getType()->isInteger()) {
3505 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003506 if (MaskedValueIsZero(Op0, Mask)) {
3507 if (MaskedValueIsZero(Op1, Mask)) {
3508 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3509 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3510 }
3511 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00003512 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00003513 ShiftedInt->getValue().isPowerOf2()) {
3514 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3515 // Safe because the only negative value (1 << Y) can take on is
3516 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3517 // the sign bit set.
3518 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3519 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003520 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003521 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003522
3523 return 0;
3524}
3525
3526Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3527 return commonDivTransforms(I);
3528}
3529
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003530/// This function implements the transforms on rem instructions that work
3531/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3532/// is used by the visitors to those instructions.
3533/// @brief Transforms common to all three rem instructions
3534Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3535 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3536
Chris Lattner653ef3c2008-02-19 06:12:18 +00003537 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3538 if (I.getType()->isFPOrFPVector())
3539 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00003540 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003541 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003542 if (isa<UndefValue>(Op1))
3543 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3544
3545 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003546 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3547 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003548
3549 return 0;
3550}
3551
3552/// This function implements the transforms common to both integer remainder
3553/// instructions (urem and srem). It is called by the visitors to those integer
3554/// remainder instructions.
3555/// @brief Common integer remainder transforms
3556Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3557 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3558
3559 if (Instruction *common = commonRemTransforms(I))
3560 return common;
3561
Dale Johannesena51f7372009-01-21 00:35:19 +00003562 // 0 % X == 0 for integer, we don't need to preserve faults!
3563 if (Constant *LHS = dyn_cast<Constant>(Op0))
3564 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00003565 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003566
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003567 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3568 // X % 0 == undef, we don't need to preserve faults!
3569 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003570 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003571
3572 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003573 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003574
3575 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3576 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3577 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3578 return R;
3579 } else if (isa<PHINode>(Op0I)) {
3580 if (Instruction *NV = FoldOpIntoPhi(I))
3581 return NV;
3582 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003583
3584 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003585 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003586 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003587 }
3588 }
3589
3590 return 0;
3591}
3592
3593Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3594 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3595
3596 if (Instruction *common = commonIRemTransforms(I))
3597 return common;
3598
3599 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3600 // X urem C^2 -> X and C
3601 // Check to see if this is an unsigned remainder with an exact power of 2,
3602 // if so, convert to a bitwise and.
3603 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3604 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003605 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003606 }
3607
3608 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3609 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3610 if (RHSI->getOpcode() == Instruction::Shl &&
3611 isa<ConstantInt>(RHSI->getOperand(0))) {
3612 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00003613 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00003614 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003615 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003616 }
3617 }
3618 }
3619
3620 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3621 // where C1&C2 are powers of two.
3622 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3623 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3624 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3625 // STO == 0 and SFO == 0 handled above.
3626 if ((STO->getValue().isPowerOf2()) &&
3627 (SFO->getValue().isPowerOf2())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003628 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3629 SI->getName()+".t");
3630 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3631 SI->getName()+".f");
Gabor Greifd6da1d02008-04-06 20:25:17 +00003632 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003633 }
3634 }
3635 }
3636
3637 return 0;
3638}
3639
3640Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3641 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3642
Dan Gohmandb3dd962007-11-05 23:16:33 +00003643 // Handle the integer rem common cases
Chris Lattner4796b622009-08-30 06:22:51 +00003644 if (Instruction *Common = commonIRemTransforms(I))
3645 return Common;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003646
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003647 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003648 if (!isa<Constant>(RHSNeg) ||
3649 (isa<ConstantInt>(RHSNeg) &&
3650 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003651 // X % -Y -> X % Y
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003652 Worklist.AddValue(I.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003653 I.setOperand(1, RHSNeg);
3654 return &I;
3655 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003656
Dan Gohmandb3dd962007-11-05 23:16:33 +00003657 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003658 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003659 if (I.getType()->isInteger()) {
3660 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3661 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3662 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003663 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003664 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003665 }
3666
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003667 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003668 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3669 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003670
Nick Lewyckyfd746832008-12-20 16:48:00 +00003671 bool hasNegative = false;
3672 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3673 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3674 if (RHS->getValue().isNegative())
3675 hasNegative = true;
3676
3677 if (hasNegative) {
3678 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003679 for (unsigned i = 0; i != VWidth; ++i) {
3680 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3681 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00003682 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003683 else
3684 Elts[i] = RHS;
3685 }
3686 }
3687
Owen Anderson2f422e02009-07-28 21:19:26 +00003688 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003689 if (NewRHSV != RHSV) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003690 Worklist.AddValue(I.getOperand(1));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003691 I.setOperand(1, NewRHSV);
3692 return &I;
3693 }
3694 }
3695 }
3696
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003697 return 0;
3698}
3699
3700Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3701 return commonRemTransforms(I);
3702}
3703
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003704// isOneBitSet - Return true if there is exactly one bit set in the specified
3705// constant.
3706static bool isOneBitSet(const ConstantInt *CI) {
3707 return CI->getValue().isPowerOf2();
3708}
3709
3710// isHighOnes - Return true if the constant is of the form 1+0+.
3711// This is the same as lowones(~X).
3712static bool isHighOnes(const ConstantInt *CI) {
3713 return (~CI->getValue() + 1).isPowerOf2();
3714}
3715
3716/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3717/// are carefully arranged to allow folding of expressions such as:
3718///
3719/// (A < B) | (A > B) --> (A != B)
3720///
3721/// Note that this is only valid if the first and second predicates have the
3722/// same sign. Is illegal to do: (A u< B) | (A s> B)
3723///
3724/// Three bits are used to represent the condition, as follows:
3725/// 0 A > B
3726/// 1 A == B
3727/// 2 A < B
3728///
3729/// <=> Value Definition
3730/// 000 0 Always false
3731/// 001 1 A > B
3732/// 010 2 A == B
3733/// 011 3 A >= B
3734/// 100 4 A < B
3735/// 101 5 A != B
3736/// 110 6 A <= B
3737/// 111 7 Always true
3738///
3739static unsigned getICmpCode(const ICmpInst *ICI) {
3740 switch (ICI->getPredicate()) {
3741 // False -> 0
3742 case ICmpInst::ICMP_UGT: return 1; // 001
3743 case ICmpInst::ICMP_SGT: return 1; // 001
3744 case ICmpInst::ICMP_EQ: return 2; // 010
3745 case ICmpInst::ICMP_UGE: return 3; // 011
3746 case ICmpInst::ICMP_SGE: return 3; // 011
3747 case ICmpInst::ICMP_ULT: return 4; // 100
3748 case ICmpInst::ICMP_SLT: return 4; // 100
3749 case ICmpInst::ICMP_NE: return 5; // 101
3750 case ICmpInst::ICMP_ULE: return 6; // 110
3751 case ICmpInst::ICMP_SLE: return 6; // 110
3752 // True -> 7
3753 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003754 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003755 return 0;
3756 }
3757}
3758
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003759/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3760/// predicate into a three bit mask. It also returns whether it is an ordered
3761/// predicate by reference.
3762static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3763 isOrdered = false;
3764 switch (CC) {
3765 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3766 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003767 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3768 case FCmpInst::FCMP_UGT: return 1; // 001
3769 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3770 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003771 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3772 case FCmpInst::FCMP_UGE: return 3; // 011
3773 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3774 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003775 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3776 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003777 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3778 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003779 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003780 default:
3781 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003782 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003783 return 0;
3784 }
3785}
3786
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003787/// getICmpValue - This is the complement of getICmpCode, which turns an
3788/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003789/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003790/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003791static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003792 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003793 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003794 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson4f720fa2009-07-31 17:39:07 +00003795 case 0: return ConstantInt::getFalse(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003796 case 1:
3797 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003798 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003799 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003800 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3801 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003802 case 3:
3803 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003804 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003805 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003806 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003807 case 4:
3808 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003809 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003810 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003811 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3812 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003813 case 6:
3814 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003815 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003816 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003817 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003818 case 7: return ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003819 }
3820}
3821
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003822/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3823/// opcode and two operands into either a FCmp instruction. isordered is passed
3824/// in to determine which kind of predicate to use in the new fcmp instruction.
3825static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003826 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003827 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003828 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003829 case 0:
3830 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003831 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003832 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003833 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003834 case 1:
3835 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003836 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003837 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003838 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003839 case 2:
3840 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003841 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003842 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003843 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003844 case 3:
3845 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003846 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003847 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003848 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003849 case 4:
3850 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003851 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003852 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003853 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003854 case 5:
3855 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003856 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003857 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003858 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003859 case 6:
3860 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003861 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003862 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003863 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003864 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003865 }
3866}
3867
Chris Lattner2972b822008-11-16 04:55:20 +00003868/// PredicatesFoldable - Return true if both predicates match sign or if at
3869/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003870static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003871 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3872 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3873 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003874}
3875
3876namespace {
3877// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3878struct FoldICmpLogical {
3879 InstCombiner &IC;
3880 Value *LHS, *RHS;
3881 ICmpInst::Predicate pred;
3882 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3883 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3884 pred(ICI->getPredicate()) {}
3885 bool shouldApply(Value *V) const {
3886 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3887 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003888 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3889 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003890 return false;
3891 }
3892 Instruction *apply(Instruction &Log) const {
3893 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3894 if (ICI->getOperand(0) != LHS) {
3895 assert(ICI->getOperand(1) == LHS);
3896 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3897 }
3898
3899 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3900 unsigned LHSCode = getICmpCode(ICI);
3901 unsigned RHSCode = getICmpCode(RHSICI);
3902 unsigned Code;
3903 switch (Log.getOpcode()) {
3904 case Instruction::And: Code = LHSCode & RHSCode; break;
3905 case Instruction::Or: Code = LHSCode | RHSCode; break;
3906 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003907 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003908 }
3909
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003910 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Anderson24be4c12009-07-03 00:17:18 +00003911 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003912 if (Instruction *I = dyn_cast<Instruction>(RV))
3913 return I;
3914 // Otherwise, it's a constant boolean value...
3915 return IC.ReplaceInstUsesWith(Log, RV);
3916 }
3917};
3918} // end anonymous namespace
3919
3920// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3921// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3922// guaranteed to be a binary operator.
3923Instruction *InstCombiner::OptAndOp(Instruction *Op,
3924 ConstantInt *OpRHS,
3925 ConstantInt *AndRHS,
3926 BinaryOperator &TheAnd) {
3927 Value *X = Op->getOperand(0);
3928 Constant *Together = 0;
3929 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00003930 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003931
3932 switch (Op->getOpcode()) {
3933 case Instruction::Xor:
3934 if (Op->hasOneUse()) {
3935 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattnerc7694852009-08-30 07:44:24 +00003936 Value *And = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003937 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003938 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003939 }
3940 break;
3941 case Instruction::Or:
3942 if (Together == AndRHS) // (X | C) & C --> C
3943 return ReplaceInstUsesWith(TheAnd, AndRHS);
3944
3945 if (Op->hasOneUse() && Together != OpRHS) {
3946 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattnerc7694852009-08-30 07:44:24 +00003947 Value *Or = Builder->CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003948 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003949 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003950 }
3951 break;
3952 case Instruction::Add:
3953 if (Op->hasOneUse()) {
3954 // Adding a one to a single bit bit-field should be turned into an XOR
3955 // of the bit. First thing to check is to see if this AND is with a
3956 // single bit constant.
3957 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3958
3959 // If there is only one bit set...
3960 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3961 // Ok, at this point, we know that we are masking the result of the
3962 // ADD down to exactly one bit. If the constant we are adding has
3963 // no bits set below this bit, then we can eliminate the ADD.
3964 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3965
3966 // Check to see if any bits below the one bit set in AndRHSV are set.
3967 if ((AddRHS & (AndRHSV-1)) == 0) {
3968 // If not, the only thing that can effect the output of the AND is
3969 // the bit specified by AndRHSV. If that bit is set, the effect of
3970 // the XOR is to toggle the bit. If it is clear, then the ADD has
3971 // no effect.
3972 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3973 TheAnd.setOperand(0, X);
3974 return &TheAnd;
3975 } else {
3976 // Pull the XOR out of the AND.
Chris Lattnerc7694852009-08-30 07:44:24 +00003977 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003978 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003979 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003980 }
3981 }
3982 }
3983 }
3984 break;
3985
3986 case Instruction::Shl: {
3987 // We know that the AND will not produce any of the bits shifted in, so if
3988 // the anded constant includes them, clear them now!
3989 //
3990 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3991 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3992 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003993 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003994
3995 if (CI->getValue() == ShlMask) {
3996 // Masking out bits that the shift already masks
3997 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3998 } else if (CI != AndRHS) { // Reducing bits set in and.
3999 TheAnd.setOperand(1, CI);
4000 return &TheAnd;
4001 }
4002 break;
4003 }
4004 case Instruction::LShr:
4005 {
4006 // We know that the AND will not produce any of the bits shifted in, so if
4007 // the anded constant includes them, clear them now! This only applies to
4008 // unsigned shifts, because a signed shr may bring in set bits!
4009 //
4010 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
4011 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
4012 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00004013 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004014
4015 if (CI->getValue() == ShrMask) {
4016 // Masking out bits that the shift already masks.
4017 return ReplaceInstUsesWith(TheAnd, Op);
4018 } else if (CI != AndRHS) {
4019 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
4020 return &TheAnd;
4021 }
4022 break;
4023 }
4024 case Instruction::AShr:
4025 // Signed shr.
4026 // See if this is shifting in some sign extension, then masking it out
4027 // with an and.
4028 if (Op->hasOneUse()) {
4029 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
4030 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
4031 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00004032 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004033 if (C == AndRHS) { // Masking out bits shifted in.
4034 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
4035 // Make the argument unsigned.
4036 Value *ShVal = Op->getOperand(0);
Chris Lattnerc7694852009-08-30 07:44:24 +00004037 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004038 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004039 }
4040 }
4041 break;
4042 }
4043 return 0;
4044}
4045
4046
4047/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
4048/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
4049/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
4050/// whether to treat the V, Lo and HI as signed or not. IB is the location to
4051/// insert new instructions.
4052Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
4053 bool isSigned, bool Inside,
4054 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00004055 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004056 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
4057 "Lo is not <= Hi in range emission code!");
4058
4059 if (Inside) {
4060 if (Lo == Hi) // Trivially false.
Dan Gohmane6803b82009-08-25 23:17:54 +00004061 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004062
4063 // V >= Min && V < Hi --> V < Hi
4064 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
4065 ICmpInst::Predicate pred = (isSigned ?
4066 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohmane6803b82009-08-25 23:17:54 +00004067 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004068 }
4069
4070 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00004071 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattnerc7694852009-08-30 07:44:24 +00004072 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00004073 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00004074 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004075 }
4076
4077 if (Lo == Hi) // Trivially true.
Dan Gohmane6803b82009-08-25 23:17:54 +00004078 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004079
4080 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004081 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004082 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
4083 ICmpInst::Predicate pred = (isSigned ?
4084 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohmane6803b82009-08-25 23:17:54 +00004085 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004086 }
4087
4088 // Emit V-Lo >u Hi-1-Lo
4089 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00004090 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattnerc7694852009-08-30 07:44:24 +00004091 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00004092 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00004093 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004094}
4095
4096// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
4097// any number of 0s on either side. The 1s are allowed to wrap from LSB to
4098// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
4099// not, since all 1s are not contiguous.
4100static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
4101 const APInt& V = Val->getValue();
4102 uint32_t BitWidth = Val->getType()->getBitWidth();
4103 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
4104
4105 // look for the first zero bit after the run of ones
4106 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
4107 // look for the first non-zero bit
4108 ME = V.getActiveBits();
4109 return true;
4110}
4111
4112/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4113/// where isSub determines whether the operator is a sub. If we can fold one of
4114/// the following xforms:
4115///
4116/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4117/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4118/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4119///
4120/// return (A +/- B).
4121///
4122Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
4123 ConstantInt *Mask, bool isSub,
4124 Instruction &I) {
4125 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4126 if (!LHSI || LHSI->getNumOperands() != 2 ||
4127 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4128
4129 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4130
4131 switch (LHSI->getOpcode()) {
4132 default: return 0;
4133 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00004134 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004135 // If the AndRHS is a power of two minus one (0+1+), this is simple.
4136 if ((Mask->getValue().countLeadingZeros() +
4137 Mask->getValue().countPopulation()) ==
4138 Mask->getValue().getBitWidth())
4139 break;
4140
4141 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4142 // part, we don't need any explicit masks to take them out of A. If that
4143 // is all N is, ignore it.
4144 uint32_t MB = 0, ME = 0;
4145 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
4146 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4147 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4148 if (MaskedValueIsZero(RHS, Mask))
4149 break;
4150 }
4151 }
4152 return 0;
4153 case Instruction::Or:
4154 case Instruction::Xor:
4155 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4156 if ((Mask->getValue().countLeadingZeros() +
4157 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00004158 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004159 break;
4160 return 0;
4161 }
4162
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004163 if (isSub)
Chris Lattnerc7694852009-08-30 07:44:24 +00004164 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4165 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004166}
4167
Chris Lattner0631ea72008-11-16 05:06:21 +00004168/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4169Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4170 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00004171 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00004172 ConstantInt *LHSCst, *RHSCst;
4173 ICmpInst::Predicate LHSCC, RHSCC;
4174
Chris Lattnerf3803482008-11-16 05:10:52 +00004175 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004176 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004177 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004178 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004179 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00004180 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00004181
Chris Lattner163e6ab2009-11-29 00:51:17 +00004182 if (LHSCst == RHSCst && LHSCC == RHSCC) {
4183 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4184 // where C is a power of 2
4185 if (LHSCC == ICmpInst::ICMP_ULT &&
4186 LHSCst->getValue().isPowerOf2()) {
4187 Value *NewOr = Builder->CreateOr(Val, Val2);
4188 return new ICmpInst(LHSCC, NewOr, LHSCst);
4189 }
4190
4191 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4192 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4193 Value *NewOr = Builder->CreateOr(Val, Val2);
4194 return new ICmpInst(LHSCC, NewOr, LHSCst);
4195 }
Chris Lattnerf3803482008-11-16 05:10:52 +00004196 }
4197
4198 // From here on, we only handle:
4199 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4200 if (Val != Val2) return 0;
4201
Chris Lattner0631ea72008-11-16 05:06:21 +00004202 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4203 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4204 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4205 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4206 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4207 return 0;
4208
4209 // We can't fold (ugt x, C) & (sgt x, C2).
4210 if (!PredicatesFoldable(LHSCC, RHSCC))
4211 return 0;
4212
4213 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00004214 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004215 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0631ea72008-11-16 05:06:21 +00004216 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004217 CmpInst::isSigned(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00004218 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00004219 else
Chris Lattner665298f2008-11-16 05:14:43 +00004220 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4221
4222 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00004223 std::swap(LHS, RHS);
4224 std::swap(LHSCst, RHSCst);
4225 std::swap(LHSCC, RHSCC);
4226 }
4227
4228 // At this point, we know we have have two icmp instructions
4229 // comparing a value against two constants and and'ing the result
4230 // together. Because of the above check, we know that we only have
4231 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4232 // (from the FoldICmpLogical check above), that the two constants
4233 // are not equal and that the larger constant is on the RHS
4234 assert(LHSCst != RHSCst && "Compares not folded above?");
4235
4236 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004237 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004238 case ICmpInst::ICMP_EQ:
4239 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004240 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004241 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4242 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4243 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004244 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004245 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4246 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4247 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4248 return ReplaceInstUsesWith(I, LHS);
4249 }
4250 case ICmpInst::ICMP_NE:
4251 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004252 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004253 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004254 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00004255 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004256 break; // (X != 13 & X u< 15) -> no change
4257 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004258 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00004259 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004260 break; // (X != 13 & X s< 15) -> no change
4261 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4262 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4263 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4264 return ReplaceInstUsesWith(I, RHS);
4265 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004266 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00004267 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004268 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmane6803b82009-08-25 23:17:54 +00004269 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004270 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00004271 }
4272 break; // (X != 13 & X != 15) -> no change
4273 }
4274 break;
4275 case ICmpInst::ICMP_ULT:
4276 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004277 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004278 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4279 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004280 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004281 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4282 break;
4283 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4284 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4285 return ReplaceInstUsesWith(I, LHS);
4286 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4287 break;
4288 }
4289 break;
4290 case ICmpInst::ICMP_SLT:
4291 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004292 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004293 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4294 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004295 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004296 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4297 break;
4298 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4299 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4300 return ReplaceInstUsesWith(I, LHS);
4301 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4302 break;
4303 }
4304 break;
4305 case ICmpInst::ICMP_UGT:
4306 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004307 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004308 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4309 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4310 return ReplaceInstUsesWith(I, RHS);
4311 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4312 break;
4313 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004314 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00004315 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004316 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00004317 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004318 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004319 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00004320 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4321 break;
4322 }
4323 break;
4324 case ICmpInst::ICMP_SGT:
4325 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004326 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004327 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4328 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4329 return ReplaceInstUsesWith(I, RHS);
4330 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4331 break;
4332 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004333 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00004334 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004335 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00004336 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004337 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004338 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00004339 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4340 break;
4341 }
4342 break;
4343 }
Chris Lattner0631ea72008-11-16 05:06:21 +00004344
4345 return 0;
4346}
4347
Chris Lattner93a359a2009-07-23 05:14:02 +00004348Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4349 FCmpInst *RHS) {
4350
4351 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4352 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4353 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4354 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4355 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4356 // If either of the constants are nans, then the whole thing returns
4357 // false.
4358 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004359 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00004360 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner93a359a2009-07-23 05:14:02 +00004361 LHS->getOperand(0), RHS->getOperand(0));
4362 }
Chris Lattnercf373552009-07-23 05:32:17 +00004363
4364 // Handle vector zeros. This occurs because the canonical form of
4365 // "fcmp ord x,x" is "fcmp ord x, 0".
4366 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4367 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004368 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnercf373552009-07-23 05:32:17 +00004369 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00004370 return 0;
4371 }
4372
4373 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4374 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4375 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4376
4377
4378 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4379 // Swap RHS operands to match LHS.
4380 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4381 std::swap(Op1LHS, Op1RHS);
4382 }
4383
4384 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4385 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4386 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004387 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +00004388
4389 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004390 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004391 if (Op0CC == FCmpInst::FCMP_TRUE)
4392 return ReplaceInstUsesWith(I, RHS);
4393 if (Op1CC == FCmpInst::FCMP_TRUE)
4394 return ReplaceInstUsesWith(I, LHS);
4395
4396 bool Op0Ordered;
4397 bool Op1Ordered;
4398 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4399 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4400 if (Op1Pred == 0) {
4401 std::swap(LHS, RHS);
4402 std::swap(Op0Pred, Op1Pred);
4403 std::swap(Op0Ordered, Op1Ordered);
4404 }
4405 if (Op0Pred == 0) {
4406 // uno && ueq -> uno && (uno || eq) -> ueq
4407 // ord && olt -> ord && (ord && lt) -> olt
4408 if (Op0Ordered == Op1Ordered)
4409 return ReplaceInstUsesWith(I, RHS);
4410
4411 // uno && oeq -> uno && (ord && eq) -> false
4412 // uno && ord -> false
4413 if (!Op0Ordered)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004414 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004415 // ord && ueq -> ord && (uno || eq) -> oeq
4416 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4417 Op0LHS, Op0RHS, Context));
4418 }
4419 }
4420
4421 return 0;
4422}
4423
Chris Lattner0631ea72008-11-16 05:06:21 +00004424
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004425Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4426 bool Changed = SimplifyCommutative(I);
4427 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4428
Chris Lattnera3e46f62009-11-10 00:55:12 +00004429 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4430 return ReplaceInstUsesWith(I, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004431
4432 // See if we can simplify any instructions used by the instruction whose sole
4433 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004434 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky72c812c2010-01-02 15:25:44 +00004435 return &I;
Dan Gohman8fd520a2009-06-15 22:12:54 +00004436
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004437 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00004438 const APInt &AndRHSMask = AndRHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004439 APInt NotAndRHS(~AndRHSMask);
4440
4441 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner4580d452009-10-11 22:00:32 +00004442 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004443 Value *Op0LHS = Op0I->getOperand(0);
4444 Value *Op0RHS = Op0I->getOperand(1);
4445 switch (Op0I->getOpcode()) {
Chris Lattner4580d452009-10-11 22:00:32 +00004446 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004447 case Instruction::Xor:
4448 case Instruction::Or:
4449 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner4580d452009-10-11 22:00:32 +00004450 if (!Op0I->hasOneUse()) break;
4451
4452 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4453 // Not masking anything out for the LHS, move to RHS.
4454 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4455 Op0RHS->getName()+".masked");
4456 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4457 }
4458 if (!isa<Constant>(Op0RHS) &&
4459 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4460 // Not masking anything out for the RHS, move to LHS.
4461 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4462 Op0LHS->getName()+".masked");
4463 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004464 }
4465
4466 break;
4467 case Instruction::Add:
4468 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4469 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4470 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4471 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004472 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004473 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004474 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004475 break;
4476
4477 case Instruction::Sub:
4478 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4479 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4480 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4481 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004482 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004483
Nick Lewyckya349ba42008-07-10 05:51:40 +00004484 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4485 // has 1's for all bits that the subtraction with A might affect.
4486 if (Op0I->hasOneUse()) {
4487 uint32_t BitWidth = AndRHSMask.getBitWidth();
4488 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4489 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4490
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004491 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004492 if (!(A && A->isZero()) && // avoid infinite recursion.
4493 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004494 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004495 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4496 }
4497 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004498 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004499
4500 case Instruction::Shl:
4501 case Instruction::LShr:
4502 // (1 << x) & 1 --> zext(x == 0)
4503 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004504 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004505 Value *NewICmp =
4506 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004507 return new ZExtInst(NewICmp, I.getType());
4508 }
4509 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004510 }
4511
4512 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4513 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4514 return Res;
4515 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4516 // If this is an integer truncation or change from signed-to-unsigned, and
4517 // if the source is an and/or with immediate, transform it. This
4518 // frequently occurs for bitfield accesses.
4519 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4520 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4521 CastOp->getNumOperands() == 2)
Chris Lattner6e060db2009-10-26 15:40:07 +00004522 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004523 if (CastOp->getOpcode() == Instruction::And) {
4524 // Change: and (cast (and X, C1) to T), C2
4525 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4526 // This will fold the two constants together, which may allow
4527 // other simplifications.
Chris Lattnerc7694852009-08-30 07:44:24 +00004528 Value *NewCast = Builder->CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004529 CastOp->getOperand(0), I.getType(),
4530 CastOp->getName()+".shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004531 // trunc_or_bitcast(C1)&C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004532 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004533 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004534 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004535 } else if (CastOp->getOpcode() == Instruction::Or) {
4536 // Change: and (cast (or X, C1) to T), C2
4537 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004538 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004539 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00004540 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004541 return ReplaceInstUsesWith(I, AndRHS);
4542 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004543 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004544 }
4545 }
4546
4547 // Try to fold constant and into select arguments.
4548 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4549 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4550 return R;
4551 if (isa<PHINode>(Op0))
4552 if (Instruction *NV = FoldOpIntoPhi(I))
4553 return NV;
4554 }
4555
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004556
4557 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnera3e46f62009-11-10 00:55:12 +00004558 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4559 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4560 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4561 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4562 I.getName()+".demorgan");
4563 return BinaryOperator::CreateNot(Or);
4564 }
4565
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004566 {
4567 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnera3e46f62009-11-10 00:55:12 +00004568 // (A|B) & ~(A&B) -> A^B
4569 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4570 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4571 ((A == C && B == D) || (A == D && B == C)))
4572 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004573
Chris Lattnera3e46f62009-11-10 00:55:12 +00004574 // ~(A&B) & (A|B) -> A^B
4575 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4576 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4577 ((A == C && B == D) || (A == D && B == C)))
4578 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004579
4580 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004581 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004582 if (A == Op1) { // (A^B)&A -> A&(A^B)
4583 I.swapOperands(); // Simplify below
4584 std::swap(Op0, Op1);
4585 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4586 cast<BinaryOperator>(Op0)->swapOperands();
4587 I.swapOperands(); // Simplify below
4588 std::swap(Op0, Op1);
4589 }
4590 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004591
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004592 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004593 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004594 if (B == Op0) { // B&(A^B) -> B&(B^A)
4595 cast<BinaryOperator>(Op1)->swapOperands();
4596 std::swap(A, B);
4597 }
Chris Lattnerc7694852009-08-30 07:44:24 +00004598 if (A == Op0) // A&(A^B) -> A & ~B
4599 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004600 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004601
4602 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00004603 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4604 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004605 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004606 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4607 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004608 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004609 }
4610
4611 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4612 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004613 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004614 return R;
4615
Chris Lattner0631ea72008-11-16 05:06:21 +00004616 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4617 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4618 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004619 }
4620
4621 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4622 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4623 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4624 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4625 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004626 if (SrcTy == Op1C->getOperand(0)->getType() &&
4627 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004628 // Only do this if the casts both really cause code to be generated.
4629 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4630 I.getType(), TD) &&
4631 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4632 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004633 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4634 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004635 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004636 }
4637 }
4638
4639 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4640 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4641 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4642 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4643 SI0->getOperand(1) == SI1->getOperand(1) &&
4644 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004645 Value *NewOp =
4646 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4647 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004648 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004649 SI1->getOperand(1));
4650 }
4651 }
4652
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004653 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004654 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004655 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4656 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4657 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004658 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004659
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004660 return Changed ? &I : 0;
4661}
4662
Chris Lattner567f5112008-10-05 02:13:19 +00004663/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4664/// capable of providing pieces of a bswap. The subexpression provides pieces
4665/// of a bswap if it is proven that each of the non-zero bytes in the output of
4666/// the expression came from the corresponding "byte swapped" byte in some other
4667/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4668/// we know that the expression deposits the low byte of %X into the high byte
4669/// of the bswap result and that all other bytes are zero. This expression is
4670/// accepted, the high byte of ByteValues is set to X to indicate a correct
4671/// match.
4672///
4673/// This function returns true if the match was unsuccessful and false if so.
4674/// On entry to the function the "OverallLeftShift" is a signed integer value
4675/// indicating the number of bytes that the subexpression is later shifted. For
4676/// example, if the expression is later right shifted by 16 bits, the
4677/// OverallLeftShift value would be -2 on entry. This is used to specify which
4678/// byte of ByteValues is actually being set.
4679///
4680/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4681/// byte is masked to zero by a user. For example, in (X & 255), X will be
4682/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4683/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4684/// always in the local (OverallLeftShift) coordinate space.
4685///
4686static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4687 SmallVector<Value*, 8> &ByteValues) {
4688 if (Instruction *I = dyn_cast<Instruction>(V)) {
4689 // If this is an or instruction, it may be an inner node of the bswap.
4690 if (I->getOpcode() == Instruction::Or) {
4691 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4692 ByteValues) ||
4693 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4694 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004695 }
Chris Lattner567f5112008-10-05 02:13:19 +00004696
4697 // If this is a logical shift by a constant multiple of 8, recurse with
4698 // OverallLeftShift and ByteMask adjusted.
4699 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4700 unsigned ShAmt =
4701 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4702 // Ensure the shift amount is defined and of a byte value.
4703 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4704 return true;
4705
4706 unsigned ByteShift = ShAmt >> 3;
4707 if (I->getOpcode() == Instruction::Shl) {
4708 // X << 2 -> collect(X, +2)
4709 OverallLeftShift += ByteShift;
4710 ByteMask >>= ByteShift;
4711 } else {
4712 // X >>u 2 -> collect(X, -2)
4713 OverallLeftShift -= ByteShift;
4714 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004715 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004716 }
4717
4718 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4719 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4720
4721 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4722 ByteValues);
4723 }
4724
4725 // If this is a logical 'and' with a mask that clears bytes, clear the
4726 // corresponding bytes in ByteMask.
4727 if (I->getOpcode() == Instruction::And &&
4728 isa<ConstantInt>(I->getOperand(1))) {
4729 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4730 unsigned NumBytes = ByteValues.size();
4731 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4732 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4733
4734 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4735 // If this byte is masked out by a later operation, we don't care what
4736 // the and mask is.
4737 if ((ByteMask & (1 << i)) == 0)
4738 continue;
4739
4740 // If the AndMask is all zeros for this byte, clear the bit.
4741 APInt MaskB = AndMask & Byte;
4742 if (MaskB == 0) {
4743 ByteMask &= ~(1U << i);
4744 continue;
4745 }
4746
4747 // If the AndMask is not all ones for this byte, it's not a bytezap.
4748 if (MaskB != Byte)
4749 return true;
4750
4751 // Otherwise, this byte is kept.
4752 }
4753
4754 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4755 ByteValues);
4756 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004757 }
4758
Chris Lattner567f5112008-10-05 02:13:19 +00004759 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4760 // the input value to the bswap. Some observations: 1) if more than one byte
4761 // is demanded from this input, then it could not be successfully assembled
4762 // into a byteswap. At least one of the two bytes would not be aligned with
4763 // their ultimate destination.
4764 if (!isPowerOf2_32(ByteMask)) return true;
4765 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004766
Chris Lattner567f5112008-10-05 02:13:19 +00004767 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4768 // is demanded, it needs to go into byte 0 of the result. This means that the
4769 // byte needs to be shifted until it lands in the right byte bucket. The
4770 // shift amount depends on the position: if the byte is coming from the high
4771 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4772 // low part, it must be shifted left.
4773 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4774 if (InputByteNo < ByteValues.size()/2) {
4775 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4776 return true;
4777 } else {
4778 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4779 return true;
4780 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004781
4782 // If the destination byte value is already defined, the values are or'd
4783 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004784 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004785 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004786 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004787 return false;
4788}
4789
4790/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4791/// If so, insert the new bswap intrinsic and return it.
4792Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4793 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004794 if (!ITy || ITy->getBitWidth() % 16 ||
4795 // ByteMask only allows up to 32-byte values.
4796 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004797 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4798
4799 /// ByteValues - For each byte of the result, we keep track of which value
4800 /// defines each byte.
4801 SmallVector<Value*, 8> ByteValues;
4802 ByteValues.resize(ITy->getBitWidth()/8);
4803
4804 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004805 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4806 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004807 return 0;
4808
4809 // Check to see if all of the bytes come from the same value.
4810 Value *V = ByteValues[0];
4811 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4812
4813 // Check to make sure that all of the bytes come from the same value.
4814 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4815 if (ByteValues[i] != V)
4816 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004817 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004818 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004819 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004820 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004821}
4822
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004823/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4824/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4825/// we can simplify this expression to "cond ? C : D or B".
4826static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004827 Value *C, Value *D,
4828 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004829 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004830 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004831 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004832 return 0;
4833
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004834 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00004835 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004836 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00004837 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004838 return SelectInst::Create(Cond, C, B);
4839 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00004840 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004841 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00004842 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004843 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004844 return 0;
4845}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004846
Chris Lattner0c678e52008-11-16 05:20:07 +00004847/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4848Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4849 ICmpInst *LHS, ICmpInst *RHS) {
4850 Value *Val, *Val2;
4851 ConstantInt *LHSCst, *RHSCst;
4852 ICmpInst::Predicate LHSCC, RHSCC;
4853
4854 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner163e6ab2009-11-29 00:51:17 +00004855 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4856 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00004857 return 0;
Chris Lattner163e6ab2009-11-29 00:51:17 +00004858
4859
4860 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4861 if (LHSCst == RHSCst && LHSCC == RHSCC &&
4862 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4863 Value *NewOr = Builder->CreateOr(Val, Val2);
4864 return new ICmpInst(LHSCC, NewOr, LHSCst);
4865 }
Chris Lattner0c678e52008-11-16 05:20:07 +00004866
4867 // From here on, we only handle:
4868 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4869 if (Val != Val2) return 0;
4870
4871 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4872 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4873 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4874 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4875 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4876 return 0;
4877
4878 // We can't fold (ugt x, C) | (sgt x, C2).
4879 if (!PredicatesFoldable(LHSCC, RHSCC))
4880 return 0;
4881
4882 // Ensure that the larger constant is on the RHS.
4883 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004884 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0c678e52008-11-16 05:20:07 +00004885 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004886 CmpInst::isSigned(RHSCC)))
Chris Lattner0c678e52008-11-16 05:20:07 +00004887 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4888 else
4889 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4890
4891 if (ShouldSwap) {
4892 std::swap(LHS, RHS);
4893 std::swap(LHSCst, RHSCst);
4894 std::swap(LHSCC, RHSCC);
4895 }
4896
4897 // At this point, we know we have have two icmp instructions
4898 // comparing a value against two constants and or'ing the result
4899 // together. Because of the above check, we know that we only have
4900 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4901 // FoldICmpLogical check above), that the two constants are not
4902 // equal.
4903 assert(LHSCst != RHSCst && "Compares not folded above?");
4904
4905 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004906 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004907 case ICmpInst::ICMP_EQ:
4908 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004909 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004910 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004911 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004912 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00004913 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004914 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004915 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohmane6803b82009-08-25 23:17:54 +00004916 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004917 }
4918 break; // (X == 13 | X == 15) -> no change
4919 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4920 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4921 break;
4922 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4923 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4924 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4925 return ReplaceInstUsesWith(I, RHS);
4926 }
4927 break;
4928 case ICmpInst::ICMP_NE:
4929 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004930 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004931 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4932 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4933 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4934 return ReplaceInstUsesWith(I, LHS);
4935 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4936 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4937 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004938 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004939 }
4940 break;
4941 case ICmpInst::ICMP_ULT:
4942 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004943 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004944 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4945 break;
4946 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4947 // If RHSCst is [us]MAXINT, it is always false. Not handling
4948 // this can cause overflow.
4949 if (RHSCst->isMaxValue(false))
4950 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004951 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004952 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004953 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4954 break;
4955 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4956 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4957 return ReplaceInstUsesWith(I, RHS);
4958 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4959 break;
4960 }
4961 break;
4962 case ICmpInst::ICMP_SLT:
4963 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004964 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004965 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4966 break;
4967 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4968 // If RHSCst is [us]MAXINT, it is always false. Not handling
4969 // this can cause overflow.
4970 if (RHSCst->isMaxValue(true))
4971 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004972 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004973 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004974 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4975 break;
4976 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4977 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4978 return ReplaceInstUsesWith(I, RHS);
4979 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4980 break;
4981 }
4982 break;
4983 case ICmpInst::ICMP_UGT:
4984 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004985 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004986 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4987 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4988 return ReplaceInstUsesWith(I, LHS);
4989 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4990 break;
4991 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4992 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004993 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004994 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4995 break;
4996 }
4997 break;
4998 case ICmpInst::ICMP_SGT:
4999 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005000 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00005001 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
5002 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
5003 return ReplaceInstUsesWith(I, LHS);
5004 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
5005 break;
5006 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
5007 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005008 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00005009 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
5010 break;
5011 }
5012 break;
5013 }
5014 return 0;
5015}
5016
Chris Lattner57e66fa2009-07-23 05:46:22 +00005017Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
5018 FCmpInst *RHS) {
5019 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
5020 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
5021 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
5022 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
5023 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
5024 // If either of the constants are nans, then the whole thing returns
5025 // true.
5026 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005027 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00005028
5029 // Otherwise, no need to compare the two constants, compare the
5030 // rest.
Dan Gohmane6803b82009-08-25 23:17:54 +00005031 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00005032 LHS->getOperand(0), RHS->getOperand(0));
5033 }
5034
5035 // Handle vector zeros. This occurs because the canonical form of
5036 // "fcmp uno x,x" is "fcmp uno x, 0".
5037 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
5038 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00005039 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00005040 LHS->getOperand(0), RHS->getOperand(0));
5041
5042 return 0;
5043 }
5044
5045 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
5046 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
5047 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
5048
5049 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
5050 // Swap RHS operands to match LHS.
5051 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
5052 std::swap(Op1LHS, Op1RHS);
5053 }
5054 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
5055 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
5056 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00005057 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner57e66fa2009-07-23 05:46:22 +00005058 Op0LHS, Op0RHS);
5059 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005060 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00005061 if (Op0CC == FCmpInst::FCMP_FALSE)
5062 return ReplaceInstUsesWith(I, RHS);
5063 if (Op1CC == FCmpInst::FCMP_FALSE)
5064 return ReplaceInstUsesWith(I, LHS);
5065 bool Op0Ordered;
5066 bool Op1Ordered;
5067 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
5068 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
5069 if (Op0Ordered == Op1Ordered) {
5070 // If both are ordered or unordered, return a new fcmp with
5071 // or'ed predicates.
5072 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5073 Op0LHS, Op0RHS, Context);
5074 if (Instruction *I = dyn_cast<Instruction>(RV))
5075 return I;
5076 // Otherwise, it's a constant boolean value...
5077 return ReplaceInstUsesWith(I, RV);
5078 }
5079 }
5080 return 0;
5081}
5082
Bill Wendlingdae376a2008-12-01 08:23:25 +00005083/// FoldOrWithConstants - This helper function folds:
5084///
Bill Wendling236a1192008-12-02 05:09:00 +00005085/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00005086///
5087/// into:
5088///
Bill Wendling236a1192008-12-02 05:09:00 +00005089/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00005090///
Bill Wendling236a1192008-12-02 05:09:00 +00005091/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00005092Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00005093 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00005094 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5095 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00005096
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00005097 Value *V1 = 0;
5098 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00005099 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00005100
Bill Wendling86ee3162008-12-02 06:18:11 +00005101 APInt Xor = CI1->getValue() ^ CI2->getValue();
5102 if (!Xor.isAllOnesValue()) return 0;
5103
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00005104 if (V1 == A || V1 == B) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005105 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00005106 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005107 }
5108
5109 return 0;
5110}
5111
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005112Instruction *InstCombiner::visitOr(BinaryOperator &I) {
5113 bool Changed = SimplifyCommutative(I);
5114 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5115
Chris Lattnera3e46f62009-11-10 00:55:12 +00005116 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5117 return ReplaceInstUsesWith(I, V);
5118
5119
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005120 // See if we can simplify any instructions used by the instruction whose sole
5121 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005122 if (SimplifyDemandedInstructionBits(I))
5123 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005124
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005125 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5126 ConstantInt *C1 = 0; Value *X = 0;
5127 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00005128 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005129 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005130 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005131 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005132 return BinaryOperator::CreateAnd(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005133 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005134 }
5135
5136 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00005137 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005138 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005139 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005140 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005141 return BinaryOperator::CreateXor(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005142 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005143 }
5144
5145 // Try to fold constant and into select arguments.
5146 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5147 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5148 return R;
5149 if (isa<PHINode>(Op0))
5150 if (Instruction *NV = FoldOpIntoPhi(I))
5151 return NV;
5152 }
5153
5154 Value *A = 0, *B = 0;
5155 ConstantInt *C1 = 0, *C2 = 0;
5156
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005157 // (A | B) | C and A | (B | C) -> bswap if possible.
5158 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00005159 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5160 match(Op1, m_Or(m_Value(), m_Value())) ||
5161 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5162 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005163 if (Instruction *BSwap = MatchBSwap(I))
5164 return BSwap;
5165 }
5166
5167 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00005168 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005169 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005170 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005171 Value *NOr = Builder->CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005172 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005173 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005174 }
5175
5176 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00005177 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005178 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005179 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005180 Value *NOr = Builder->CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005181 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005182 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005183 }
5184
5185 // (A & C)|(B & D)
5186 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00005187 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5188 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005189 Value *V1 = 0, *V2 = 0, *V3 = 0;
5190 C1 = dyn_cast<ConstantInt>(C);
5191 C2 = dyn_cast<ConstantInt>(D);
5192 if (C1 && C2) { // (A & C1)|(B & C2)
5193 // If we have: ((V + N) & C1) | (V & C2)
5194 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5195 // replace with V+N.
5196 if (C1->getValue() == ~C2->getValue()) {
5197 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohmancdff2122009-08-12 16:23:25 +00005198 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005199 // Add commutes, try both ways.
5200 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5201 return ReplaceInstUsesWith(I, A);
5202 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5203 return ReplaceInstUsesWith(I, A);
5204 }
5205 // Or commutes, try both ways.
5206 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005207 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005208 // Add commutes, try both ways.
5209 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5210 return ReplaceInstUsesWith(I, B);
5211 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5212 return ReplaceInstUsesWith(I, B);
5213 }
5214 }
5215 V1 = 0; V2 = 0; V3 = 0;
5216 }
5217
5218 // Check to see if we have any common things being and'ed. If so, find the
5219 // terms for V1 & (V2|V3).
5220 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5221 if (A == B) // (A & C)|(A & D) == A & (C|D)
5222 V1 = A, V2 = C, V3 = D;
5223 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5224 V1 = A, V2 = B, V3 = C;
5225 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5226 V1 = C, V2 = A, V3 = D;
5227 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5228 V1 = C, V2 = A, V3 = B;
5229
5230 if (V1) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005231 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00005232 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005233 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005234 }
Dan Gohman279952c2008-10-28 22:38:57 +00005235
Dan Gohman35b76162008-10-30 20:40:10 +00005236 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00005237 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005238 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005239 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005240 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005241 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005242 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005243 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005244 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00005245
Bill Wendling22ca8352008-11-30 13:52:49 +00005246 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005247 if ((match(C, m_Not(m_Specific(D))) &&
5248 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005249 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00005250 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005251 if ((match(A, m_Not(m_Specific(D))) &&
5252 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005253 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00005254 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005255 if ((match(C, m_Not(m_Specific(B))) &&
5256 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005257 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00005258 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005259 if ((match(A, m_Not(m_Specific(B))) &&
5260 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005261 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005262 }
5263
5264 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
5265 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5266 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5267 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
5268 SI0->getOperand(1) == SI1->getOperand(1) &&
5269 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005270 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5271 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005272 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005273 SI1->getOperand(1));
5274 }
5275 }
5276
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005277 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00005278 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5279 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00005280 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005281 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005282 }
5283 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00005284 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5285 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00005286 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005287 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005288 }
5289
Chris Lattnera3e46f62009-11-10 00:55:12 +00005290 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5291 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5292 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5293 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5294 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5295 I.getName()+".demorgan");
5296 return BinaryOperator::CreateNot(And);
5297 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005298
5299 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5300 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005301 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005302 return R;
5303
Chris Lattner0c678e52008-11-16 05:20:07 +00005304 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5305 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5306 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005307 }
5308
5309 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005310 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005311 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5312 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00005313 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5314 !isa<ICmpInst>(Op1C->getOperand(0))) {
5315 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00005316 if (SrcTy == Op1C->getOperand(0)->getType() &&
5317 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00005318 // Only do this if the casts both really cause code to be
5319 // generated.
5320 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5321 I.getType(), TD) &&
5322 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5323 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005324 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5325 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005326 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00005327 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005328 }
5329 }
Chris Lattner91882432007-10-24 05:38:08 +00005330 }
5331
5332
5333 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5334 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00005335 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5336 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5337 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00005338 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005339
5340 return Changed ? &I : 0;
5341}
5342
Dan Gohman089efff2008-05-13 00:00:25 +00005343namespace {
5344
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005345// XorSelf - Implements: X ^ X --> 0
5346struct XorSelf {
5347 Value *RHS;
5348 XorSelf(Value *rhs) : RHS(rhs) {}
5349 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5350 Instruction *apply(BinaryOperator &Xor) const {
5351 return &Xor;
5352 }
5353};
5354
Dan Gohman089efff2008-05-13 00:00:25 +00005355}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005356
5357Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5358 bool Changed = SimplifyCommutative(I);
5359 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5360
Evan Chenge5cd8032008-03-25 20:07:13 +00005361 if (isa<UndefValue>(Op1)) {
5362 if (isa<UndefValue>(Op0))
5363 // Handle undef ^ undef -> 0 special case. This is a common
5364 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00005365 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005366 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005367 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005368
5369 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005370 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005371 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00005372 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005373 }
5374
5375 // See if we can simplify any instructions used by the instruction whose sole
5376 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005377 if (SimplifyDemandedInstructionBits(I))
5378 return &I;
5379 if (isa<VectorType>(I.getType()))
5380 if (isa<ConstantAggregateZero>(Op1))
5381 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005382
5383 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005384 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005385 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5386 if (Op0I->getOpcode() == Instruction::And ||
5387 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner6e060db2009-10-26 15:40:07 +00005388 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5389 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5390 if (dyn_castNotVal(Op0I->getOperand(1)))
5391 Op0I->swapOperands();
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005392 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005393 Value *NotY =
5394 Builder->CreateNot(Op0I->getOperand(1),
5395 Op0I->getOperand(1)->getName()+".not");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005396 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005397 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattnerc7694852009-08-30 07:44:24 +00005398 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005399 }
Chris Lattner6e060db2009-10-26 15:40:07 +00005400
5401 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5402 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5403 if (isFreeToInvert(Op0I->getOperand(0)) &&
5404 isFreeToInvert(Op0I->getOperand(1))) {
5405 Value *NotX =
5406 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5407 Value *NotY =
5408 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5409 if (Op0I->getOpcode() == Instruction::And)
5410 return BinaryOperator::CreateOr(NotX, NotY);
5411 return BinaryOperator::CreateAnd(NotX, NotY);
5412 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005413 }
5414 }
5415 }
5416
5417
5418 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00005419 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005420 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005421 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005422 return new ICmpInst(ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005423 ICI->getOperand(0), ICI->getOperand(1));
5424
Nick Lewycky1405e922007-08-06 20:04:16 +00005425 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005426 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005427 FCI->getOperand(0), FCI->getOperand(1));
5428 }
5429
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005430 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5431 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5432 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5433 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5434 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattnerc7694852009-08-30 07:44:24 +00005435 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5436 (RHS == ConstantExpr::getCast(Opcode,
5437 ConstantInt::getTrue(*Context),
5438 Op0C->getDestTy()))) {
5439 CI->setPredicate(CI->getInversePredicate());
5440 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005441 }
5442 }
5443 }
5444 }
5445
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005446 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5447 // ~(c-X) == X-c-1 == X+(-c-1)
5448 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5449 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005450 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5451 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005452 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005453 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005454 }
5455
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005456 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005457 if (Op0I->getOpcode() == Instruction::Add) {
5458 // ~(X-c) --> (-c-1)-X
5459 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005460 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005461 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00005462 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005463 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00005464 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005465 } else if (RHS->getValue().isSignBit()) {
5466 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005467 Constant *C = ConstantInt::get(*Context,
5468 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005469 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005470
5471 }
5472 } else if (Op0I->getOpcode() == Instruction::Or) {
5473 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5474 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005475 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005476 // Anything in both C1 and C2 is known to be zero, remove it from
5477 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00005478 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5479 NewRHS = ConstantExpr::getAnd(NewRHS,
5480 ConstantExpr::getNot(CommonBits));
Chris Lattner3183fb62009-08-30 06:13:40 +00005481 Worklist.Add(Op0I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005482 I.setOperand(0, Op0I->getOperand(0));
5483 I.setOperand(1, NewRHS);
5484 return &I;
5485 }
5486 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005487 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005488 }
5489
5490 // Try to fold constant and into select arguments.
5491 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5492 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5493 return R;
5494 if (isa<PHINode>(Op0))
5495 if (Instruction *NV = FoldOpIntoPhi(I))
5496 return NV;
5497 }
5498
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005499 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005500 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00005501 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005502
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005503 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005504 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00005505 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005506
5507
5508 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5509 if (Op1I) {
5510 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005511 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005512 if (A == Op0) { // B^(B|A) == (A|B)^B
5513 Op1I->swapOperands();
5514 I.swapOperands();
5515 std::swap(Op0, Op1);
5516 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5517 I.swapOperands(); // Simplified below.
5518 std::swap(Op0, Op1);
5519 }
Dan Gohmancdff2122009-08-12 16:23:25 +00005520 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005521 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005522 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005523 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005524 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005525 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005526 if (A == Op0) { // A^(A&B) -> A^(B&A)
5527 Op1I->swapOperands();
5528 std::swap(A, B);
5529 }
5530 if (B == Op0) { // A^(B&A) -> (B&A)^A
5531 I.swapOperands(); // Simplified below.
5532 std::swap(Op0, Op1);
5533 }
5534 }
5535 }
5536
5537 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5538 if (Op0I) {
5539 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005540 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005541 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005542 if (A == Op1) // (B|A)^B == (A|B)^B
5543 std::swap(A, B);
Chris Lattnerc7694852009-08-30 07:44:24 +00005544 if (B == Op1) // (A|B)^B == A & ~B
5545 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohmancdff2122009-08-12 16:23:25 +00005546 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005547 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005548 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005549 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005550 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005551 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005552 if (A == Op1) // (A&B)^A -> (B&A)^A
5553 std::swap(A, B);
5554 if (B == Op1 && // (B&A)^A == ~B & A
5555 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerc7694852009-08-30 07:44:24 +00005556 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005557 }
5558 }
5559 }
5560
5561 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5562 if (Op0I && Op1I && Op0I->isShift() &&
5563 Op0I->getOpcode() == Op1I->getOpcode() &&
5564 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5565 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005566 Value *NewOp =
5567 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5568 Op0I->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005569 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005570 Op1I->getOperand(1));
5571 }
5572
5573 if (Op0I && Op1I) {
5574 Value *A, *B, *C, *D;
5575 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005576 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5577 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005578 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005579 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005580 }
5581 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005582 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5583 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005584 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005585 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005586 }
5587
5588 // (A & B)^(C & D)
5589 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005590 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5591 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005592 // (X & Y)^(X & Y) -> (Y^Z) & X
5593 Value *X = 0, *Y = 0, *Z = 0;
5594 if (A == C)
5595 X = A, Y = B, Z = D;
5596 else if (A == D)
5597 X = A, Y = B, Z = C;
5598 else if (B == C)
5599 X = B, Y = A, Z = D;
5600 else if (B == D)
5601 X = B, Y = A, Z = C;
5602
5603 if (X) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005604 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005605 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005606 }
5607 }
5608 }
5609
5610 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5611 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005612 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005613 return R;
5614
5615 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005616 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005617 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5618 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5619 const Type *SrcTy = Op0C->getOperand(0)->getType();
5620 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5621 // Only do this if the casts both really cause code to be generated.
5622 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5623 I.getType(), TD) &&
5624 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5625 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005626 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5627 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005628 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005629 }
5630 }
Chris Lattner91882432007-10-24 05:38:08 +00005631 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005632
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005633 return Changed ? &I : 0;
5634}
5635
Owen Anderson24be4c12009-07-03 00:17:18 +00005636static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005637 LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005638 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005639}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005640
Dan Gohman8fd520a2009-06-15 22:12:54 +00005641static bool HasAddOverflow(ConstantInt *Result,
5642 ConstantInt *In1, ConstantInt *In2,
5643 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005644 if (IsSigned)
5645 if (In2->getValue().isNegative())
5646 return Result->getValue().sgt(In1->getValue());
5647 else
5648 return Result->getValue().slt(In1->getValue());
5649 else
5650 return Result->getValue().ult(In1->getValue());
5651}
5652
Dan Gohman8fd520a2009-06-15 22:12:54 +00005653/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005654/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005655static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005656 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005657 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005658 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005659
Dan Gohman8fd520a2009-06-15 22:12:54 +00005660 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5661 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005662 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005663 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5664 ExtractElement(In1, Idx, Context),
5665 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005666 IsSigned))
5667 return true;
5668 }
5669 return false;
5670 }
5671
5672 return HasAddOverflow(cast<ConstantInt>(Result),
5673 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5674 IsSigned);
5675}
5676
5677static bool HasSubOverflow(ConstantInt *Result,
5678 ConstantInt *In1, ConstantInt *In2,
5679 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005680 if (IsSigned)
5681 if (In2->getValue().isNegative())
5682 return Result->getValue().slt(In1->getValue());
5683 else
5684 return Result->getValue().sgt(In1->getValue());
5685 else
5686 return Result->getValue().ugt(In1->getValue());
5687}
5688
Dan Gohman8fd520a2009-06-15 22:12:54 +00005689/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5690/// overflowed for this type.
5691static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005692 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005693 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005694 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005695
5696 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5697 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005698 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005699 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5700 ExtractElement(In1, Idx, Context),
5701 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005702 IsSigned))
5703 return true;
5704 }
5705 return false;
5706 }
5707
5708 return HasSubOverflow(cast<ConstantInt>(Result),
5709 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5710 IsSigned);
5711}
5712
Chris Lattnereba75862008-04-22 02:53:33 +00005713
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005714/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5715/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohman17f46f72009-07-28 01:40:03 +00005716Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005717 ICmpInst::Predicate Cond,
5718 Instruction &I) {
Chris Lattnereba75862008-04-22 02:53:33 +00005719 // Look through bitcasts.
5720 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5721 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005722
5723 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohman17f46f72009-07-28 01:40:03 +00005724 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005725 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005726 // This transformation (ignoring the base and scales) is valid because we
Dan Gohman17f46f72009-07-28 01:40:03 +00005727 // know pointers can't overflow since the gep is inbounds. See if we can
5728 // output an optimized form.
Chris Lattnereba75862008-04-22 02:53:33 +00005729 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5730
5731 // If not, synthesize the offset the hard way.
5732 if (Offset == 0)
Chris Lattner93e6ff92009-11-04 08:05:20 +00005733 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005734 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonaac28372009-07-31 20:28:14 +00005735 Constant::getNullValue(Offset->getType()));
Dan Gohman17f46f72009-07-28 01:40:03 +00005736 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005737 // If the base pointers are different, but the indices are the same, just
5738 // compare the base pointer.
5739 if (PtrBase != GEPRHS->getOperand(0)) {
5740 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5741 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5742 GEPRHS->getOperand(0)->getType();
5743 if (IndicesTheSame)
5744 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5745 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5746 IndicesTheSame = false;
5747 break;
5748 }
5749
5750 // If all indices are the same, just compare the base pointers.
5751 if (IndicesTheSame)
Dan Gohmane6803b82009-08-25 23:17:54 +00005752 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005753 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5754
5755 // Otherwise, the base pointers are different and the indices are
5756 // different, bail out.
5757 return 0;
5758 }
5759
5760 // If one of the GEPs has all zero indices, recurse.
5761 bool AllZeros = true;
5762 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5763 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5764 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5765 AllZeros = false;
5766 break;
5767 }
5768 if (AllZeros)
5769 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5770 ICmpInst::getSwappedPredicate(Cond), I);
5771
5772 // If the other GEP has all zero indices, recurse.
5773 AllZeros = true;
5774 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5775 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5776 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5777 AllZeros = false;
5778 break;
5779 }
5780 if (AllZeros)
5781 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5782
5783 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5784 // If the GEPs only differ by one index, compare it.
5785 unsigned NumDifferences = 0; // Keep track of # differences.
5786 unsigned DiffOperand = 0; // The operand that differs.
5787 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5788 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5789 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5790 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5791 // Irreconcilable differences.
5792 NumDifferences = 2;
5793 break;
5794 } else {
5795 if (NumDifferences++) break;
5796 DiffOperand = i;
5797 }
5798 }
5799
5800 if (NumDifferences == 0) // SAME GEP?
5801 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson35b47072009-08-13 21:58:54 +00005802 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005803 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005804
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005805 else if (NumDifferences == 1) {
5806 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5807 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5808 // Make sure we do a signed comparison here.
Dan Gohmane6803b82009-08-25 23:17:54 +00005809 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005810 }
5811 }
5812
5813 // Only lower this if the icmp is the only user of the GEP or if we expect
5814 // the result to fold to a constant!
Dan Gohmana80e2712009-07-21 23:21:54 +00005815 if (TD &&
5816 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005817 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5818 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner93e6ff92009-11-04 08:05:20 +00005819 Value *L = EmitGEPOffset(GEPLHS, *this);
5820 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005821 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005822 }
5823 }
5824 return 0;
5825}
5826
Chris Lattnere6b62d92008-05-19 20:18:56 +00005827/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5828///
5829Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5830 Instruction *LHSI,
5831 Constant *RHSC) {
5832 if (!isa<ConstantFP>(RHSC)) return 0;
5833 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5834
5835 // Get the width of the mantissa. We don't want to hack on conversions that
5836 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005837 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005838 if (MantissaWidth == -1) return 0; // Unknown.
5839
5840 // Check to see that the input is converted from an integer type that is small
5841 // enough that preserves all bits. TODO: check here for "known" sign bits.
5842 // 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 +00005843 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005844
5845 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005846 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5847 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005848 ++InputSize;
5849
5850 // If the conversion would lose info, don't hack on this.
5851 if ((int)InputSize > MantissaWidth)
5852 return 0;
5853
5854 // Otherwise, we can potentially simplify the comparison. We know that it
5855 // will always come through as an integer value and we know the constant is
5856 // not a NAN (it would have been previously simplified).
5857 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5858
5859 ICmpInst::Predicate Pred;
5860 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005861 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnere6b62d92008-05-19 20:18:56 +00005862 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005863 case FCmpInst::FCMP_OEQ:
5864 Pred = ICmpInst::ICMP_EQ;
5865 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005866 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005867 case FCmpInst::FCMP_OGT:
5868 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5869 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005870 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005871 case FCmpInst::FCMP_OGE:
5872 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5873 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005874 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005875 case FCmpInst::FCMP_OLT:
5876 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5877 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005878 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005879 case FCmpInst::FCMP_OLE:
5880 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5881 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005882 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005883 case FCmpInst::FCMP_ONE:
5884 Pred = ICmpInst::ICMP_NE;
5885 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005886 case FCmpInst::FCMP_ORD:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005887 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005888 case FCmpInst::FCMP_UNO:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005889 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005890 }
5891
5892 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5893
5894 // Now we know that the APFloat is a normal number, zero or inf.
5895
Chris Lattnerf13ff492008-05-20 03:50:52 +00005896 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005897 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005898 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005899
Bill Wendling20636df2008-11-09 04:26:50 +00005900 if (!LHSUnsigned) {
5901 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5902 // and large values.
5903 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5904 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5905 APFloat::rmNearestTiesToEven);
5906 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5907 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5908 Pred == ICmpInst::ICMP_SLE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005909 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5910 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005911 }
5912 } else {
5913 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5914 // +INF and large values.
5915 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5916 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5917 APFloat::rmNearestTiesToEven);
5918 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5919 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5920 Pred == ICmpInst::ICMP_ULE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005921 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5922 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005923 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005924 }
5925
Bill Wendling20636df2008-11-09 04:26:50 +00005926 if (!LHSUnsigned) {
5927 // See if the RHS value is < SignedMin.
5928 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5929 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5930 APFloat::rmNearestTiesToEven);
5931 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5932 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5933 Pred == ICmpInst::ICMP_SGE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005934 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5935 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005936 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005937 }
5938
Bill Wendling20636df2008-11-09 04:26:50 +00005939 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5940 // [0, UMAX], but it may still be fractional. See if it is fractional by
5941 // casting the FP value to the integer value and back, checking for equality.
5942 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005943 Constant *RHSInt = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005944 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5945 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005946 if (!RHS.isZero()) {
5947 bool Equal = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005948 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5949 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005950 if (!Equal) {
5951 // If we had a comparison against a fractional value, we have to adjust
5952 // the compare predicate and sometimes the value. RHSC is rounded towards
5953 // zero at this point.
5954 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005955 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng14118132009-05-22 23:10:53 +00005956 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005957 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005958 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00005959 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005960 case ICmpInst::ICMP_ULE:
5961 // (float)int <= 4.4 --> int <= 4
5962 // (float)int <= -4.4 --> false
5963 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005964 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005965 break;
5966 case ICmpInst::ICMP_SLE:
5967 // (float)int <= 4.4 --> int <= 4
5968 // (float)int <= -4.4 --> int < -4
5969 if (RHS.isNegative())
5970 Pred = ICmpInst::ICMP_SLT;
5971 break;
5972 case ICmpInst::ICMP_ULT:
5973 // (float)int < -4.4 --> false
5974 // (float)int < 4.4 --> int <= 4
5975 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005976 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005977 Pred = ICmpInst::ICMP_ULE;
5978 break;
5979 case ICmpInst::ICMP_SLT:
5980 // (float)int < -4.4 --> int < -4
5981 // (float)int < 4.4 --> int <= 4
5982 if (!RHS.isNegative())
5983 Pred = ICmpInst::ICMP_SLE;
5984 break;
5985 case ICmpInst::ICMP_UGT:
5986 // (float)int > 4.4 --> int > 4
5987 // (float)int > -4.4 --> true
5988 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005989 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005990 break;
5991 case ICmpInst::ICMP_SGT:
5992 // (float)int > 4.4 --> int > 4
5993 // (float)int > -4.4 --> int >= -4
5994 if (RHS.isNegative())
5995 Pred = ICmpInst::ICMP_SGE;
5996 break;
5997 case ICmpInst::ICMP_UGE:
5998 // (float)int >= -4.4 --> true
5999 // (float)int >= 4.4 --> int > 4
6000 if (!RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00006001 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00006002 Pred = ICmpInst::ICMP_UGT;
6003 break;
6004 case ICmpInst::ICMP_SGE:
6005 // (float)int >= -4.4 --> int >= -4
6006 // (float)int >= 4.4 --> int > 4
6007 if (!RHS.isNegative())
6008 Pred = ICmpInst::ICMP_SGT;
6009 break;
6010 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00006011 }
6012 }
6013
6014 // Lower this FP comparison into an appropriate integer version of the
6015 // comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00006016 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00006017}
6018
Chris Lattner78264d82010-01-02 08:12:04 +00006019
6020/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
6021/// cmp pred (load (gep GV, ...)), cmpcst
6022/// where GV is a global variable with a constant initializer. Try to simplify
6023/// this into one or two simpler comparisons that do not need the load. For
6024/// example, we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into
6025/// "icmp eq i, 3". We assume that eliminating a load is always goodness.
6026Instruction *InstCombiner::
6027FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
6028 CmpInst &ICI) {
6029
6030 // There are many forms of this optimization we can handle, for now, just do
6031 // the simple index into a single-dimensional array.
6032 //
6033 // Require: GEP GV, 0, i
6034 if (GEP->getNumOperands() != 3 ||
6035 !isa<ConstantInt>(GEP->getOperand(1)) ||
6036 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
6037 return 0;
6038
6039 ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer());
6040 if (Init == 0 || Init->getNumOperands() > 1024) return 0;
6041
6042
6043 // Variables for our state machines.
6044
Chris Lattner24491ff2010-01-02 09:35:17 +00006045 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
6046 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
6047 // and 87 is the second (and last) index. FirstTrueElement is -1 when
6048 // undefined, otherwise set to the first true element. SecondTrueElement is
6049 // -1 when undefined, -2 when overdefined and >= 0 when that index is true.
6050 int FirstTrueElement = -1, SecondTrueElement = -1;
Chris Lattner78264d82010-01-02 08:12:04 +00006051
Chris Lattner24491ff2010-01-02 09:35:17 +00006052 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
6053 // form "i != 47 & i != 87". Same state transitions as for true elements.
6054 int FirstFalseElement = -1, SecondFalseElement = -1;
Chris Lattner78264d82010-01-02 08:12:04 +00006055
Chris Lattner0227f9a2010-01-02 08:56:52 +00006056 // MagicBitvector - This is a magic bitvector where we set a bit if the
6057 // comparison is true for element 'i'. If there are 64 elements or less in
6058 // the array, this will fully represent all the comparison results.
6059 uint64_t MagicBitvector = 0;
6060
6061
Chris Lattner78264d82010-01-02 08:12:04 +00006062 // Scan the array and see if one of our patterns matches.
6063 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
6064 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
6065 // Find out if the comparison would be true or false for the i'th element.
6066 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(),
6067 Init->getOperand(i),
6068 CompareRHS, TD);
6069 // If the result is undef for this element, ignore it.
6070 if (isa<UndefValue>(C)) continue;
6071
6072 // If we can't compute the result for any of the elements, we have to give
6073 // up evaluating the entire conditional.
6074 if (!isa<ConstantInt>(C)) return 0;
6075
6076 // Otherwise, we know if the comparison is true or false for this element,
6077 // update our state machines.
6078 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
6079
6080 // State machine for single index comparison.
6081 if (IsTrueForElt) {
Chris Lattner24491ff2010-01-02 09:35:17 +00006082 // Update the TrueElement state machine.
6083 if (FirstTrueElement == -1)
6084 FirstTrueElement = i;
6085 else if (SecondTrueElement == -1)
6086 SecondTrueElement = i;
6087 else
6088 SecondTrueElement = -2;
Chris Lattner78264d82010-01-02 08:12:04 +00006089 } else {
Chris Lattner24491ff2010-01-02 09:35:17 +00006090 // Update the FalseElement state machine.
6091 if (FirstFalseElement == -1)
6092 FirstFalseElement = i;
6093 else if (SecondFalseElement == -1)
6094 SecondFalseElement = i;
6095 else
6096 SecondFalseElement = -2;
Chris Lattner78264d82010-01-02 08:12:04 +00006097 }
6098
Chris Lattner0227f9a2010-01-02 08:56:52 +00006099 // If this element is in range, update our magic bitvector.
6100 if (i < 64 && IsTrueForElt)
Chris Lattner4e1a76f2010-01-02 09:22:13 +00006101 MagicBitvector |= 1ULL << i;
Chris Lattner0227f9a2010-01-02 08:56:52 +00006102
Chris Lattner78264d82010-01-02 08:12:04 +00006103 // If all of our states become overdefined, bail out early.
Chris Lattner24491ff2010-01-02 09:35:17 +00006104 if (i >= 64 && SecondTrueElement == -2 && SecondFalseElement == -2)
Chris Lattner78264d82010-01-02 08:12:04 +00006105 return 0;
6106 }
6107
6108 // Now that we've scanned the entire array, emit our new comparison(s). We
6109 // order the state machines in complexity of the generated code.
Chris Lattner24491ff2010-01-02 09:35:17 +00006110 Value *Idx = GEP->getOperand(2);
6111
6112 // If the comparison is only true for one or two elements, emit direct
6113 // comparisons.
6114 if (SecondTrueElement != -2) {
Chris Lattner78264d82010-01-02 08:12:04 +00006115 // None true -> false.
Chris Lattner24491ff2010-01-02 09:35:17 +00006116 if (FirstTrueElement == -1)
Chris Lattner78264d82010-01-02 08:12:04 +00006117 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6118
Chris Lattner24491ff2010-01-02 09:35:17 +00006119 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
6120
Chris Lattner78264d82010-01-02 08:12:04 +00006121 // True for one element -> 'i == 47'.
Chris Lattner24491ff2010-01-02 09:35:17 +00006122 if (SecondTrueElement == -1)
6123 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
6124
6125 // True for two elements -> 'i == 47 | i == 72'.
6126 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
6127 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
6128 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
6129 return BinaryOperator::CreateOr(C1, C2);
Chris Lattner78264d82010-01-02 08:12:04 +00006130 }
6131
Chris Lattner24491ff2010-01-02 09:35:17 +00006132 // If the comparison is only false for one or two elements, emit direct
6133 // comparisons.
6134 if (SecondFalseElement != -2) {
Chris Lattner78264d82010-01-02 08:12:04 +00006135 // None false -> true.
Chris Lattner24491ff2010-01-02 09:35:17 +00006136 if (FirstFalseElement == -1)
Chris Lattner78264d82010-01-02 08:12:04 +00006137 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6138
Chris Lattner24491ff2010-01-02 09:35:17 +00006139 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
6140
6141 // False for one element -> 'i != 47'.
6142 if (SecondFalseElement == -1)
6143 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
6144
6145 // False for two elements -> 'i != 47 & i != 72'.
6146 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
6147 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
6148 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
6149 return BinaryOperator::CreateAnd(C1, C2);
Chris Lattner78264d82010-01-02 08:12:04 +00006150 }
6151
Chris Lattner0227f9a2010-01-02 08:56:52 +00006152 // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
6153 // of this load, replace it with computation that does:
6154 // ((magic_cst >> i) & 1) != 0
6155 if (Init->getNumOperands() <= 32 ||
6156 (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) {
6157 const Type *Ty;
6158 if (Init->getNumOperands() <= 32)
6159 Ty = Type::getInt32Ty(Init->getContext());
6160 else
6161 Ty = Type::getInt64Ty(Init->getContext());
Chris Lattner24491ff2010-01-02 09:35:17 +00006162 Value *V = Builder->CreateIntCast(Idx, Ty, false);
Chris Lattner0227f9a2010-01-02 08:56:52 +00006163 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
6164 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
6165 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
6166 }
Chris Lattner78264d82010-01-02 08:12:04 +00006167
Chris Lattner24491ff2010-01-02 09:35:17 +00006168 // TODO: Range check
6169 // TODO: GEP 0, i, 4
Chris Lattner78264d82010-01-02 08:12:04 +00006170 return 0;
6171}
6172
6173
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006174Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattner454d7a02009-11-09 23:31:49 +00006175 bool Changed = false;
6176
6177 /// Orders the operands of the compare so that they are listed from most
6178 /// complex to least complex. This puts constants before unary operators,
6179 /// before binary operators.
6180 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6181 I.swapOperands();
6182 Changed = true;
6183 }
6184
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006185 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006186
Chris Lattner54c21352009-11-09 23:55:12 +00006187 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
6188 return ReplaceInstUsesWith(I, V);
6189
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006190 // Simplify 'fcmp pred X, X'
6191 if (Op0 == Op1) {
6192 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006193 default: llvm_unreachable("Unknown predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006194 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
6195 case FCmpInst::FCMP_ULT: // True if unordered or less than
6196 case FCmpInst::FCMP_UGT: // True if unordered or greater than
6197 case FCmpInst::FCMP_UNE: // True if unordered or not equal
6198 // Canonicalize these to be 'fcmp uno %X, 0.0'.
6199 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersonaac28372009-07-31 20:28:14 +00006200 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006201 return &I;
6202
6203 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
6204 case FCmpInst::FCMP_OEQ: // True if ordered and equal
6205 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
6206 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
6207 // Canonicalize these to be 'fcmp ord %X, 0.0'.
6208 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersonaac28372009-07-31 20:28:14 +00006209 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006210 return &I;
6211 }
6212 }
6213
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006214 // Handle fcmp with constant RHS
6215 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6216 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6217 switch (LHSI->getOpcode()) {
6218 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00006219 // Only fold fcmp into the PHI if the phi and fcmp are in the same
6220 // block. If in the same block, we're encouraging jump threading. If
6221 // not, we are just pessimizing the code by making an i1 phi.
6222 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00006223 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00006224 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006225 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00006226 case Instruction::SIToFP:
6227 case Instruction::UIToFP:
6228 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6229 return NV;
6230 break;
Chris Lattner37dfcfe2010-01-02 08:20:51 +00006231 case Instruction::Select: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006232 // If either operand of the select is a constant, we can fold the
6233 // comparison into the select arms, which will cause one to be
6234 // constant folded and the select turned into a bitwise or.
6235 Value *Op1 = 0, *Op2 = 0;
6236 if (LHSI->hasOneUse()) {
6237 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6238 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006239 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006240 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006241 Op2 = Builder->CreateFCmp(I.getPredicate(),
6242 LHSI->getOperand(2), RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006243 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6244 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006245 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006246 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006247 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6248 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006249 }
6250 }
6251
6252 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006253 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006254 break;
6255 }
Chris Lattner37dfcfe2010-01-02 08:20:51 +00006256 case Instruction::Load:
6257 if (GetElementPtrInst *GEP =
6258 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
6259 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6260 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
6261 !cast<LoadInst>(LHSI)->isVolatile())
6262 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6263 return Res;
6264 //errs() << "NOT HANDLED: " << *GV << "\n";
6265 //errs() << "\t" << *GEP << "\n";
6266 //errs() << "\t " << I << "\n\n\n";
6267 }
6268 break;
6269 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006270 }
6271
6272 return Changed ? &I : 0;
6273}
6274
6275Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattner454d7a02009-11-09 23:31:49 +00006276 bool Changed = false;
6277
6278 /// Orders the operands of the compare so that they are listed from most
6279 /// complex to least complex. This puts constants before unary operators,
6280 /// before binary operators.
6281 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6282 I.swapOperands();
6283 Changed = true;
6284 }
6285
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006286 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lambf78cd322007-12-18 21:32:20 +00006287
Chris Lattner54c21352009-11-09 23:55:12 +00006288 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6289 return ReplaceInstUsesWith(I, V);
6290
6291 const Type *Ty = Op0->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006292
6293 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson35b47072009-08-13 21:58:54 +00006294 if (Ty == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006295 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006296 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00006297 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattnerc7694852009-08-30 07:44:24 +00006298 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmancdff2122009-08-12 16:23:25 +00006299 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006300 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006301 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00006302 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006303
6304 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00006305 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006306 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006307 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattnerc7694852009-08-30 07:44:24 +00006308 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00006309 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006310 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006311 case ICmpInst::ICMP_SGT:
6312 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006313 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006314 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00006315 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006316 return BinaryOperator::CreateAnd(Not, Op0);
6317 }
6318 case ICmpInst::ICMP_UGE:
6319 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6320 // FALL THROUGH
6321 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattnerc7694852009-08-30 07:44:24 +00006322 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00006323 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006324 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006325 case ICmpInst::ICMP_SGE:
6326 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6327 // FALL THROUGH
6328 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00006329 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006330 return BinaryOperator::CreateOr(Not, Op0);
6331 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006332 }
6333 }
6334
Dan Gohman7934d592009-04-25 17:12:48 +00006335 unsigned BitWidth = 0;
6336 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00006337 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6338 else if (Ty->isIntOrIntVector())
6339 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00006340
6341 bool isSignBit = false;
6342
Dan Gohman58c09632008-09-16 18:46:06 +00006343 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006344 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00006345 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00006346
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006347 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
Chris Lattner78264d82010-01-02 08:12:04 +00006348 if (I.isEquality() && CI->isZero() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006349 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006350 // (icmp cond A B) if cond is equality
Dan Gohmane6803b82009-08-25 23:17:54 +00006351 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00006352 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006353
Dan Gohman58c09632008-09-16 18:46:06 +00006354 // If we have an icmp le or icmp ge instruction, turn it into the
6355 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner54c21352009-11-09 23:55:12 +00006356 // them being folded in the code below. The SimplifyICmpInst code has
6357 // already handled the edge cases for us, so we just assert on them.
Chris Lattner62d0f232008-07-11 05:08:55 +00006358 switch (I.getPredicate()) {
6359 default: break;
6360 case ICmpInst::ICMP_ULE:
Chris Lattner54c21352009-11-09 23:55:12 +00006361 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006362 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006363 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006364 case ICmpInst::ICMP_SLE:
Chris Lattner54c21352009-11-09 23:55:12 +00006365 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006366 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006367 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006368 case ICmpInst::ICMP_UGE:
Chris Lattner54c21352009-11-09 23:55:12 +00006369 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006370 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006371 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006372 case ICmpInst::ICMP_SGE:
Chris Lattner54c21352009-11-09 23:55:12 +00006373 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006374 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006375 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006376 }
6377
Chris Lattnera1308652008-07-11 05:40:05 +00006378 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006379 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006380 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006381 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6382 }
6383
6384 // See if we can fold the comparison based on range information we can get
6385 // by checking whether bits are known to be zero or one in the input.
6386 if (BitWidth != 0) {
6387 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6388 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6389
6390 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006391 isSignBit ? APInt::getSignBit(BitWidth)
6392 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006393 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006394 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006395 if (SimplifyDemandedBits(I.getOperandUse(1),
6396 APInt::getAllOnesValue(BitWidth),
6397 Op1KnownZero, Op1KnownOne, 0))
6398 return &I;
6399
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006400 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006401 // in. Compute the Min, Max and RHS values based on the known bits. For the
6402 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006403 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6404 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006405 if (I.isSigned()) {
Dan Gohman7934d592009-04-25 17:12:48 +00006406 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6407 Op0Min, Op0Max);
6408 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6409 Op1Min, Op1Max);
6410 } else {
6411 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6412 Op0Min, Op0Max);
6413 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6414 Op1Min, Op1Max);
6415 }
6416
Chris Lattnera1308652008-07-11 05:40:05 +00006417 // If Min and Max are known to be the same, then SimplifyDemandedBits
6418 // figured out that the LHS is a constant. Just constant fold this now so
6419 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006420 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006421 return new ICmpInst(I.getPredicate(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006422 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006423 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006424 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006425 ConstantInt::get(*Context, Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006426
Chris Lattnera1308652008-07-11 05:40:05 +00006427 // Based on the range information we know about the LHS, see if we can
6428 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006429 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006430 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner62d0f232008-07-11 05:08:55 +00006431 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006432 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006433 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006434 break;
6435 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006436 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006437 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006438 break;
6439 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006440 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006441 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006442 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006443 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006444 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006445 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006446 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6447 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006448 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006449 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006450
6451 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6452 if (CI->isMinValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006453 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006454 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006455 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006456 break;
6457 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006458 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006459 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006460 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006461 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006462
6463 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006464 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006465 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6466 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006467 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006468 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006469
6470 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6471 if (CI->isMaxValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006472 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006473 Constant::getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006474 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006475 break;
6476 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006477 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006478 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006479 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006480 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006481 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006482 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006483 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6484 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006485 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006486 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006487 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006488 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006489 case ICmpInst::ICMP_SGT:
6490 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006491 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006492 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006493 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006494
6495 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006496 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006497 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6498 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006499 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006500 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006501 }
6502 break;
6503 case ICmpInst::ICMP_SGE:
6504 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6505 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006506 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006507 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006508 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006509 break;
6510 case ICmpInst::ICMP_SLE:
6511 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6512 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006513 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006514 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006515 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006516 break;
6517 case ICmpInst::ICMP_UGE:
6518 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6519 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006520 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006521 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006522 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006523 break;
6524 case ICmpInst::ICMP_ULE:
6525 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6526 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006527 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006528 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006529 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006530 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006531 }
Dan Gohman7934d592009-04-25 17:12:48 +00006532
6533 // Turn a signed comparison into an unsigned one if both operands
6534 // are known to have the same sign.
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006535 if (I.isSigned() &&
Dan Gohman7934d592009-04-25 17:12:48 +00006536 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6537 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohmane6803b82009-08-25 23:17:54 +00006538 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006539 }
6540
6541 // Test if the ICmpInst instruction is used exclusively by a select as
6542 // part of a minimum or maximum operation. If so, refrain from doing
6543 // any other folding. This helps out other analyses which understand
6544 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6545 // and CodeGen. And in this case, at least one of the comparison
6546 // operands has at least one user besides the compare (the select),
6547 // which would often largely negate the benefit of folding anyway.
6548 if (I.hasOneUse())
6549 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6550 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6551 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6552 return 0;
6553
6554 // See if we are doing a comparison between a constant and an instruction that
6555 // can be folded into the comparison.
6556 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006557 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6558 // instruction, see if that instruction also has constants so that the
6559 // instruction can be folded into the icmp
6560 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6561 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6562 return Res;
6563 }
6564
6565 // Handle icmp with constant (but not simple integer constant) RHS
6566 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6567 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6568 switch (LHSI->getOpcode()) {
6569 case Instruction::GetElementPtr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006570 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner390035e2010-01-01 23:09:08 +00006571 if (RHSC->isNullValue() &&
6572 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
6573 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6574 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006575 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006576 case Instruction::PHI:
Chris Lattner9b61abd2009-09-27 20:46:36 +00006577 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattnera2417ba2008-06-08 20:52:11 +00006578 // block. If in the same block, we're encouraging jump threading. If
6579 // not, we are just pessimizing the code by making an i1 phi.
6580 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00006581 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00006582 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006583 break;
6584 case Instruction::Select: {
6585 // If either operand of the select is a constant, we can fold the
6586 // comparison into the select arms, which will cause one to be
6587 // constant folded and the select turned into a bitwise or.
6588 Value *Op1 = 0, *Op2 = 0;
Eli Friedman4779a952009-12-18 08:22:35 +00006589 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6590 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6591 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6592 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6593
6594 // We only want to perform this transformation if it will not lead to
6595 // additional code. This is true if either both sides of the select
6596 // fold to a constant (in which case the icmp is replaced with a select
6597 // which will usually simplify) or this is the only user of the
6598 // select (in which case we are trading a select+icmp for a simpler
6599 // select+icmp).
6600 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6601 if (!Op1)
Chris Lattnerc7694852009-08-30 07:44:24 +00006602 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6603 RHSC, I.getName());
Eli Friedman4779a952009-12-18 08:22:35 +00006604 if (!Op2)
6605 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6606 RHSC, I.getName());
Gabor Greifd6da1d02008-04-06 20:25:17 +00006607 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Eli Friedman4779a952009-12-18 08:22:35 +00006608 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006609 break;
6610 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006611 case Instruction::Call:
6612 // If we have (malloc != null), and if the malloc has a single use, we
6613 // can assume it is successful and remove the malloc.
6614 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6615 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez67439f02009-10-21 19:11:40 +00006616 // Need to explicitly erase malloc call here, instead of adding it to
6617 // Worklist, because it won't get DCE'd from the Worklist since
6618 // isInstructionTriviallyDead() returns false for function calls.
6619 // It is OK to replace LHSI/MallocCall with Undef because the
6620 // instruction that uses it will be erased via Worklist.
6621 if (extractMallocCall(LHSI)) {
6622 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6623 EraseInstFromFunction(*LHSI);
6624 return ReplaceInstUsesWith(I,
Victor Hernandez48c3c542009-09-18 22:35:49 +00006625 ConstantInt::get(Type::getInt1Ty(*Context),
6626 !I.isTrueWhenEqual()));
Victor Hernandez67439f02009-10-21 19:11:40 +00006627 }
6628 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6629 if (MallocCall->hasOneUse()) {
6630 MallocCall->replaceAllUsesWith(
6631 UndefValue::get(MallocCall->getType()));
6632 EraseInstFromFunction(*MallocCall);
6633 Worklist.Add(LHSI); // The malloc's bitcast use.
6634 return ReplaceInstUsesWith(I,
6635 ConstantInt::get(Type::getInt1Ty(*Context),
6636 !I.isTrueWhenEqual()));
6637 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006638 }
6639 break;
Chris Lattner390035e2010-01-01 23:09:08 +00006640 case Instruction::IntToPtr:
6641 // icmp pred inttoptr(X), null -> icmp pred X, 0
6642 if (RHSC->isNullValue() && TD &&
6643 TD->getIntPtrType(RHSC->getContext()) ==
6644 LHSI->getOperand(0)->getType())
6645 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6646 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6647 break;
Chris Lattner78264d82010-01-02 08:12:04 +00006648
6649 case Instruction::Load:
6650 if (GetElementPtrInst *GEP =
Chris Lattner37dfcfe2010-01-02 08:20:51 +00006651 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
Chris Lattner78264d82010-01-02 08:12:04 +00006652 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6653 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Chris Lattner37dfcfe2010-01-02 08:20:51 +00006654 !cast<LoadInst>(LHSI)->isVolatile())
Chris Lattner78264d82010-01-02 08:12:04 +00006655 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6656 return Res;
Chris Lattner37dfcfe2010-01-02 08:20:51 +00006657 //errs() << "NOT HANDLED: " << *GV << "\n";
6658 //errs() << "\t" << *GEP << "\n";
6659 //errs() << "\t " << I << "\n\n\n";
6660 }
Chris Lattner78264d82010-01-02 08:12:04 +00006661 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006662 }
6663 }
6664
6665 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohman17f46f72009-07-28 01:40:03 +00006666 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006667 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6668 return NI;
Dan Gohman17f46f72009-07-28 01:40:03 +00006669 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006670 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6671 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6672 return NI;
6673
6674 // Test to see if the operands of the icmp are casted versions of other
6675 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6676 // now.
6677 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6678 if (isa<PointerType>(Op0->getType()) &&
6679 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6680 // We keep moving the cast from the left operand over to the right
6681 // operand, where it can often be eliminated completely.
6682 Op0 = CI->getOperand(0);
6683
6684 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6685 // so eliminate it as well.
6686 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6687 Op1 = CI2->getOperand(0);
6688
6689 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006690 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006691 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00006692 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006693 } else {
6694 // Otherwise, cast the RHS right before the icmp
Chris Lattner78628292009-08-30 19:47:22 +00006695 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006696 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006697 }
Dan Gohmane6803b82009-08-25 23:17:54 +00006698 return new ICmpInst(I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006699 }
6700 }
6701
6702 if (isa<CastInst>(Op0)) {
6703 // Handle the special case of: icmp (cast bool to X), <cst>
6704 // This comes up when you have code like
6705 // int X = A < B;
6706 // if (X) ...
6707 // For generality, we handle any zero-extension of any operand comparison
6708 // with a constant or another cast from the same type.
Eli Friedmanbb8954b2009-12-17 21:27:47 +00006709 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006710 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6711 return R;
6712 }
6713
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006714 // See if it's the same type of instruction on the left and right.
6715 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6716 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006717 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006718 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006719 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006720 default: break;
6721 case Instruction::Add:
6722 case Instruction::Sub:
6723 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006724 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohmane6803b82009-08-25 23:17:54 +00006725 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006726 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006727 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6728 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6729 if (CI->getValue().isSignBit()) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006730 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006731 ? I.getUnsignedPredicate()
6732 : I.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006733 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006734 Op1I->getOperand(0));
6735 }
6736
6737 if (CI->getValue().isMaxSignedValue()) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006738 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006739 ? I.getUnsignedPredicate()
6740 : I.getSignedPredicate();
6741 Pred = I.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006742 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006743 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006744 }
6745 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006746 break;
6747 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006748 if (!I.isEquality())
6749 break;
6750
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006751 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6752 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6753 // Mask = -1 >> count-trailing-zeros(Cst).
6754 if (!CI->isZero() && !CI->isOne()) {
6755 const APInt &AP = CI->getValue();
Owen Andersoneacb44d2009-07-24 23:12:02 +00006756 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006757 APInt::getLowBitsSet(AP.getBitWidth(),
6758 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006759 AP.countTrailingZeros()));
Chris Lattnerc7694852009-08-30 07:44:24 +00006760 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6761 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohmane6803b82009-08-25 23:17:54 +00006762 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006763 }
6764 }
6765 break;
6766 }
6767 }
6768 }
6769 }
6770
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006771 // ~x < ~y --> y < x
6772 { Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00006773 if (match(Op0, m_Not(m_Value(A))) &&
6774 match(Op1, m_Not(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006775 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006776 }
6777
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006778 if (I.isEquality()) {
6779 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006780
6781 // -x == -y --> x == y
Dan Gohmancdff2122009-08-12 16:23:25 +00006782 if (match(Op0, m_Neg(m_Value(A))) &&
6783 match(Op1, m_Neg(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006784 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006785
Dan Gohmancdff2122009-08-12 16:23:25 +00006786 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006787 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6788 Value *OtherVal = A == Op1 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006789 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006790 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006791 }
6792
Dan Gohmancdff2122009-08-12 16:23:25 +00006793 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006794 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006795 ConstantInt *C1, *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00006796 if (match(B, m_ConstantInt(C1)) &&
6797 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006798 Constant *NC =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006799 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnerc7694852009-08-30 07:44:24 +00006800 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6801 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattner3b874082008-11-16 05:38:51 +00006802 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006803
6804 // A^B == A^D -> B == D
Dan Gohmane6803b82009-08-25 23:17:54 +00006805 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6806 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6807 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6808 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006809 }
6810 }
6811
Dan Gohmancdff2122009-08-12 16:23:25 +00006812 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006813 (A == Op0 || B == Op0)) {
6814 // A == (A^B) -> B == 0
6815 Value *OtherVal = A == Op0 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006816 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006817 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006818 }
Chris Lattner3b874082008-11-16 05:38:51 +00006819
6820 // (A-B) == A -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006821 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006822 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006823 Constant::getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006824
6825 // A == (A-B) -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006826 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006827 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006828 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006829
6830 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6831 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006832 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6833 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006834 Value *X = 0, *Y = 0, *Z = 0;
6835
6836 if (A == C) {
6837 X = B; Y = D; Z = A;
6838 } else if (A == D) {
6839 X = B; Y = C; Z = A;
6840 } else if (B == C) {
6841 X = A; Y = D; Z = B;
6842 } else if (B == D) {
6843 X = A; Y = C; Z = B;
6844 }
6845
6846 if (X) { // Build (X^Y) & Z
Chris Lattnerc7694852009-08-30 07:44:24 +00006847 Op1 = Builder->CreateXor(X, Y, "tmp");
6848 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006849 I.setOperand(0, Op1);
Owen Andersonaac28372009-07-31 20:28:14 +00006850 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006851 return &I;
6852 }
6853 }
6854 }
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006855
6856 {
6857 Value *X; ConstantInt *Cst;
Chris Lattnera54b96b2009-12-21 04:04:05 +00006858 // icmp X+Cst, X
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006859 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Chris Lattnera54b96b2009-12-21 04:04:05 +00006860 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
6861
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006862 // icmp X, X+Cst
6863 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Chris Lattnera54b96b2009-12-21 04:04:05 +00006864 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006865 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006866 return Changed ? &I : 0;
6867}
6868
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006869/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6870Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6871 Value *X, ConstantInt *CI,
Chris Lattnera54b96b2009-12-21 04:04:05 +00006872 ICmpInst::Predicate Pred,
6873 Value *TheAdd) {
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006874 // If we have X+0, exit early (simplifying logic below) and let it get folded
6875 // elsewhere. icmp X+0, X -> icmp X, X
6876 if (CI->isZero()) {
6877 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6878 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6879 }
6880
6881 // (X+4) == X -> false.
6882 if (Pred == ICmpInst::ICMP_EQ)
6883 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6884
6885 // (X+4) != X -> true.
6886 if (Pred == ICmpInst::ICMP_NE)
6887 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattnera54b96b2009-12-21 04:04:05 +00006888
6889 // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
6890 bool isNUW = false, isNSW = false;
6891 if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
6892 isNUW = Add->hasNoUnsignedWrap();
6893 isNSW = Add->hasNoSignedWrap();
6894 }
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006895
6896 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6897 // so the values can never be equal. Similiarly for all other "or equals"
6898 // operators.
6899
6900 // (X+1) <u X --> X >u (MAXUINT-1) --> X != 255
6901 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
6902 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
6903 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Chris Lattnera54b96b2009-12-21 04:04:05 +00006904 // If this is an NUW add, then this is always false.
6905 if (isNUW)
6906 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6907
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006908 Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
6909 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
6910 }
6911
6912 // (X+1) >u X --> X <u (0-1) --> X != 255
6913 // (X+2) >u X --> X <u (0-2) --> X <u 254
6914 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Chris Lattnera54b96b2009-12-21 04:04:05 +00006915 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
6916 // If this is an NUW add, then this is always true.
6917 if (isNUW)
6918 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006919 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Chris Lattnera54b96b2009-12-21 04:04:05 +00006920 }
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006921
6922 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
6923 ConstantInt *SMax = ConstantInt::get(X->getContext(),
6924 APInt::getSignedMaxValue(BitWidth));
6925
6926 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
6927 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
6928 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
6929 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
6930 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
6931 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Chris Lattnera54b96b2009-12-21 04:04:05 +00006932 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
6933 // If this is an NSW add, then we have two cases: if the constant is
6934 // positive, then this is always false, if negative, this is always true.
6935 if (isNSW) {
6936 bool isTrue = CI->getValue().isNegative();
6937 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6938 }
6939
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006940 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Chris Lattnera54b96b2009-12-21 04:04:05 +00006941 }
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006942
6943 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
6944 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
6945 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
6946 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
6947 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
6948 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Chris Lattnera54b96b2009-12-21 04:04:05 +00006949
6950 // If this is an NSW add, then we have two cases: if the constant is
6951 // positive, then this is always true, if negative, this is always false.
6952 if (isNSW) {
6953 bool isTrue = !CI->getValue().isNegative();
6954 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6955 }
6956
Chris Lattner258a2ffb2009-12-21 03:19:28 +00006957 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
6958 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
6959 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
6960}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006961
6962/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6963/// and CmpRHS are both known to be integer constants.
6964Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6965 ConstantInt *DivRHS) {
6966 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6967 const APInt &CmpRHSV = CmpRHS->getValue();
6968
6969 // FIXME: If the operand types don't match the type of the divide
6970 // then don't attempt this transform. The code below doesn't have the
6971 // logic to deal with a signed divide and an unsigned compare (and
6972 // vice versa). This is because (x /s C1) <s C2 produces different
6973 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6974 // (x /u C1) <u C2. Simply casting the operands and result won't
6975 // work. :( The if statement below tests that condition and bails
6976 // if it finds it.
6977 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006978 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006979 return 0;
6980 if (DivRHS->isZero())
6981 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006982 if (DivIsSigned && DivRHS->isAllOnesValue())
6983 return 0; // The overflow computation also screws up here
6984 if (DivRHS->isOne())
6985 return 0; // Not worth bothering, and eliminates some funny cases
6986 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006987
6988 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6989 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6990 // C2 (CI). By solving for X we can turn this into a range check
6991 // instead of computing a divide.
Owen Anderson02b48c32009-07-29 18:55:55 +00006992 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006993
6994 // Determine if the product overflows by seeing if the product is
6995 // not equal to the divide. Make sure we do the same kind of divide
6996 // as in the LHS instruction that we're folding.
Owen Anderson02b48c32009-07-29 18:55:55 +00006997 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6998 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006999
7000 // Get the ICmp opcode
7001 ICmpInst::Predicate Pred = ICI.getPredicate();
7002
7003 // Figure out the interval that is being checked. For example, a comparison
7004 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
7005 // Compute this interval based on the constants involved and the signedness of
7006 // the compare/divide. This computes a half-open interval, keeping track of
7007 // whether either value in the interval overflows. After analysis each
7008 // overflow variable is set to 0 if it's corresponding bound variable is valid
7009 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
7010 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00007011 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007012
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007013 if (!DivIsSigned) { // udiv
7014 // e.g. X/5 op 3 --> [15, 20)
7015 LoBound = Prod;
7016 HiOverflow = LoOverflow = ProdOV;
7017 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00007018 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00007019 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007020 if (CmpRHSV == 0) { // (X / pos) op 0
7021 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007022 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007023 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00007024 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007025 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
7026 HiOverflow = LoOverflow = ProdOV;
7027 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00007028 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007029 } else { // (X / pos) op neg
7030 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007031 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00007032 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
7033 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00007034 ConstantInt* DivNeg =
Owen Anderson02b48c32009-07-29 18:55:55 +00007035 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Anderson24be4c12009-07-03 00:17:18 +00007036 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00007037 true) ? -1 : 0;
7038 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007039 }
Dan Gohman5dceed12008-02-13 22:09:18 +00007040 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007041 if (CmpRHSV == 0) { // (X / neg) op 0
7042 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007043 LoBound = AddOne(DivRHS);
Owen Anderson02b48c32009-07-29 18:55:55 +00007044 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007045 if (HiBound == DivRHS) { // -INTMIN = INTMIN
7046 HiOverflow = 1; // [INTMIN+1, overflow)
7047 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
7048 }
Dan Gohman5dceed12008-02-13 22:09:18 +00007049 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007050 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007051 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007052 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
7053 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00007054 LoOverflow = AddWithOverflow(LoBound, HiBound,
7055 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007056 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00007057 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
7058 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00007059 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00007060 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007061 }
7062
7063 // Dividing by a negative swaps the condition. LT <-> GT
7064 Pred = ICmpInst::getSwappedPredicate(Pred);
7065 }
7066
7067 Value *X = DivI->getOperand(0);
7068 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00007069 default: llvm_unreachable("Unhandled icmp opcode!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007070 case ICmpInst::ICMP_EQ:
7071 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007072 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007073 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00007074 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007075 ICmpInst::ICMP_UGE, X, LoBound);
7076 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00007077 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007078 ICmpInst::ICMP_ULT, X, HiBound);
7079 else
7080 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
7081 case ICmpInst::ICMP_NE:
7082 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007083 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007084 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00007085 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007086 ICmpInst::ICMP_ULT, X, LoBound);
7087 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00007088 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007089 ICmpInst::ICMP_UGE, X, HiBound);
7090 else
7091 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
7092 case ICmpInst::ICMP_ULT:
7093 case ICmpInst::ICMP_SLT:
7094 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007095 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007096 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007097 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00007098 return new ICmpInst(Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007099 case ICmpInst::ICMP_UGT:
7100 case ICmpInst::ICMP_SGT:
7101 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007102 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007103 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007104 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007105 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohmane6803b82009-08-25 23:17:54 +00007106 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007107 else
Dan Gohmane6803b82009-08-25 23:17:54 +00007108 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007109 }
7110}
7111
7112
7113/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
7114///
7115Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
7116 Instruction *LHSI,
7117 ConstantInt *RHS) {
7118 const APInt &RHSV = RHS->getValue();
7119
7120 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00007121 case Instruction::Trunc:
7122 if (ICI.isEquality() && LHSI->hasOneUse()) {
7123 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
7124 // of the high bits truncated out of x are known.
7125 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
7126 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
7127 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
7128 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
7129 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
7130
7131 // If all the high bits are known, we can do this xform.
7132 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
7133 // Pull in the high bits from known-ones set.
7134 APInt NewRHS(RHS->getValue());
7135 NewRHS.zext(SrcBits);
7136 NewRHS |= KnownOne;
Dan Gohmane6803b82009-08-25 23:17:54 +00007137 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007138 ConstantInt::get(*Context, NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00007139 }
7140 }
7141 break;
7142
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007143 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
7144 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
7145 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
7146 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00007147 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
7148 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007149 Value *CompareVal = LHSI->getOperand(0);
7150
7151 // If the sign bit of the XorCST is not set, there is no change to
7152 // the operation, just stop using the Xor.
7153 if (!XorCST->getValue().isNegative()) {
7154 ICI.setOperand(0, CompareVal);
Chris Lattner3183fb62009-08-30 06:13:40 +00007155 Worklist.Add(LHSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007156 return &ICI;
7157 }
7158
7159 // Was the old condition true if the operand is positive?
7160 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
7161
7162 // If so, the new one isn't.
7163 isTrueIfPositive ^= true;
7164
7165 if (isTrueIfPositive)
Dan Gohmane6803b82009-08-25 23:17:54 +00007166 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007167 SubOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007168 else
Dan Gohmane6803b82009-08-25 23:17:54 +00007169 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007170 AddOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007171 }
Nick Lewyckydac84332009-01-31 21:30:05 +00007172
7173 if (LHSI->hasOneUse()) {
7174 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
7175 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
7176 const APInt &SignBit = XorCST->getValue();
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007177 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewyckydac84332009-01-31 21:30:05 +00007178 ? ICI.getUnsignedPredicate()
7179 : ICI.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00007180 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007181 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00007182 }
7183
7184 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00007185 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00007186 const APInt &NotSignBit = XorCST->getValue();
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007187 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewyckydac84332009-01-31 21:30:05 +00007188 ? ICI.getUnsignedPredicate()
7189 : ICI.getSignedPredicate();
7190 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00007191 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007192 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00007193 }
7194 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007195 }
7196 break;
7197 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
7198 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
7199 LHSI->getOperand(0)->hasOneUse()) {
7200 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
7201
7202 // If the LHS is an AND of a truncating cast, we can widen the
7203 // and/compare to be the input width without changing the value
7204 // produced, eliminating a cast.
7205 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
7206 // We can do this transformation if either the AND constant does not
7207 // have its sign bit set or if it is an equality comparison.
7208 // Extending a relational comparison when we're checking the sign
7209 // bit would not work.
7210 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00007211 (ICI.isEquality() ||
7212 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007213 uint32_t BitWidth =
7214 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
7215 APInt NewCST = AndCST->getValue();
7216 NewCST.zext(BitWidth);
7217 APInt NewCI = RHSV;
7218 NewCI.zext(BitWidth);
Chris Lattnerc7694852009-08-30 07:44:24 +00007219 Value *NewAnd =
7220 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007221 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00007222 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007223 ConstantInt::get(*Context, NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007224 }
7225 }
7226
7227 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
7228 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
7229 // happens a LOT in code produced by the C front-end, for bitfield
7230 // access.
7231 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
7232 if (Shift && !Shift->isShift())
7233 Shift = 0;
7234
7235 ConstantInt *ShAmt;
7236 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
7237 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
7238 const Type *AndTy = AndCST->getType(); // Type of the and.
7239
7240 // We can fold this as long as we can't shift unknown bits
7241 // into the mask. This can only happen with signed shift
7242 // rights, as they sign-extend.
7243 if (ShAmt) {
7244 bool CanFold = Shift->isLogicalShift();
7245 if (!CanFold) {
7246 // To test for the bad case of the signed shr, see if any
7247 // of the bits shifted in could be tested after the mask.
7248 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
7249 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
7250
7251 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
7252 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
7253 AndCST->getValue()) == 0)
7254 CanFold = true;
7255 }
7256
7257 if (CanFold) {
7258 Constant *NewCst;
7259 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00007260 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007261 else
Owen Anderson02b48c32009-07-29 18:55:55 +00007262 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007263
7264 // Check to see if we are shifting out any of the bits being
7265 // compared.
Owen Anderson02b48c32009-07-29 18:55:55 +00007266 if (ConstantExpr::get(Shift->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007267 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007268 // If we shifted bits out, the fold is not going to work out.
7269 // As a special case, check to see if this means that the
7270 // result is always true or false now.
7271 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007272 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007273 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007274 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007275 } else {
7276 ICI.setOperand(1, NewCst);
7277 Constant *NewAndCST;
7278 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00007279 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007280 else
Owen Anderson02b48c32009-07-29 18:55:55 +00007281 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007282 LHSI->setOperand(1, NewAndCST);
7283 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +00007284 Worklist.Add(Shift); // Shift is dead.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007285 return &ICI;
7286 }
7287 }
7288 }
7289
7290 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
7291 // preferable because it allows the C<<Y expression to be hoisted out
7292 // of a loop if Y is invariant and X is not.
7293 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00007294 ICI.isEquality() && !Shift->isArithmeticShift() &&
7295 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007296 // Compute C << Y.
7297 Value *NS;
7298 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007299 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007300 } else {
7301 // Insert a logical shift.
Chris Lattnerc7694852009-08-30 07:44:24 +00007302 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007303 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007304
7305 // Compute X & (C << Y).
Chris Lattnerc7694852009-08-30 07:44:24 +00007306 Value *NewAnd =
7307 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007308
7309 ICI.setOperand(0, NewAnd);
7310 return &ICI;
7311 }
7312 }
7313 break;
Nick Lewycky72c812c2010-01-02 15:25:44 +00007314
7315 case Instruction::Or: {
7316 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
7317 break;
7318 Value *P, *Q;
7319 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
7320 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
7321 // -> and (icmp eq P, null), (icmp eq Q, null).
7322
7323 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
7324 Constant::getNullValue(P->getType()));
7325 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
7326 Constant::getNullValue(Q->getType()));
7327 Instruction *And = BinaryOperator::CreateAnd(ICIP, ICIQ, "");
7328 And->takeName(&ICI);
7329 return And;
7330 }
7331 break;
7332 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007333
7334 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
7335 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7336 if (!ShAmt) break;
7337
7338 uint32_t TypeBits = RHSV.getBitWidth();
7339
7340 // Check that the shift amount is in range. If not, don't perform
7341 // undefined shifts. When the shift is visited it will be
7342 // simplified.
7343 if (ShAmt->uge(TypeBits))
7344 break;
7345
7346 if (ICI.isEquality()) {
7347 // If we are comparing against bits always shifted out, the
7348 // comparison cannot succeed.
7349 Constant *Comp =
Owen Anderson02b48c32009-07-29 18:55:55 +00007350 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Anderson24be4c12009-07-03 00:17:18 +00007351 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007352 if (Comp != RHS) {// Comparing against a bit that we know is zero.
7353 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00007354 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007355 return ReplaceInstUsesWith(ICI, Cst);
7356 }
7357
7358 if (LHSI->hasOneUse()) {
7359 // Otherwise strength reduce the shift into an and.
7360 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7361 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007362 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Anderson24be4c12009-07-03 00:17:18 +00007363 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007364
Chris Lattnerc7694852009-08-30 07:44:24 +00007365 Value *And =
7366 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007367 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007368 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007369 }
7370 }
7371
7372 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7373 bool TrueIfSigned = false;
7374 if (LHSI->hasOneUse() &&
7375 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7376 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneacb44d2009-07-24 23:12:02 +00007377 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007378 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattnerc7694852009-08-30 07:44:24 +00007379 Value *And =
7380 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007381 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00007382 And, Constant::getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007383 }
7384 break;
7385 }
7386
7387 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
7388 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007389 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007390 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00007391 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007392
Chris Lattner5ee84f82008-03-21 05:19:58 +00007393 // Check that the shift amount is in range. If not, don't perform
7394 // undefined shifts. When the shift is visited it will be
7395 // simplified.
7396 uint32_t TypeBits = RHSV.getBitWidth();
7397 if (ShAmt->uge(TypeBits))
7398 break;
7399
7400 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007401
Chris Lattner5ee84f82008-03-21 05:19:58 +00007402 // If we are comparing against bits always shifted out, the
7403 // comparison cannot succeed.
7404 APInt Comp = RHSV << ShAmtVal;
7405 if (LHSI->getOpcode() == Instruction::LShr)
7406 Comp = Comp.lshr(ShAmtVal);
7407 else
7408 Comp = Comp.ashr(ShAmtVal);
7409
7410 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7411 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00007412 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00007413 return ReplaceInstUsesWith(ICI, Cst);
7414 }
7415
7416 // Otherwise, check to see if the bits shifted out are known to be zero.
7417 // If so, we can compare against the unshifted value:
7418 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00007419 if (LHSI->hasOneUse() &&
7420 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007421 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007422 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007423 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00007424 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007425
Evan Chengfb9292a2008-04-23 00:38:06 +00007426 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007427 // Otherwise strength reduce the shift into an and.
7428 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007429 Constant *Mask = ConstantInt::get(*Context, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007430
Chris Lattnerc7694852009-08-30 07:44:24 +00007431 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7432 Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007433 return new ICmpInst(ICI.getPredicate(), And,
Owen Anderson02b48c32009-07-29 18:55:55 +00007434 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007435 }
7436 break;
7437 }
7438
7439 case Instruction::SDiv:
7440 case Instruction::UDiv:
7441 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7442 // Fold this div into the comparison, producing a range check.
7443 // Determine, based on the divide type, what the range is being
7444 // checked. If there is an overflow on the low or high side, remember
7445 // it, otherwise compute the range [low, hi) bounding the new value.
7446 // See: InsertRangeTest above for the kinds of replacements possible.
7447 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7448 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7449 DivRHS))
7450 return R;
7451 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007452
7453 case Instruction::Add:
Chris Lattner258a2ffb2009-12-21 03:19:28 +00007454 // Fold: icmp pred (add X, C1), C2
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007455 if (!ICI.isEquality()) {
7456 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7457 if (!LHSC) break;
7458 const APInt &LHSV = LHSC->getValue();
7459
7460 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7461 .subtract(LHSV);
7462
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007463 if (ICI.isSigned()) {
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007464 if (CR.getLower().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007465 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007466 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007467 } else if (CR.getUpper().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007468 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007469 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007470 }
7471 } else {
7472 if (CR.getLower().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007473 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007474 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007475 } else if (CR.getUpper().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007476 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007477 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007478 }
7479 }
7480 }
7481 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007482 }
7483
7484 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7485 if (ICI.isEquality()) {
7486 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7487
7488 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7489 // the second operand is a constant, simplify a bit.
7490 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7491 switch (BO->getOpcode()) {
7492 case Instruction::SRem:
7493 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7494 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7495 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7496 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007497 Value *NewRem =
7498 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7499 BO->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00007500 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersonaac28372009-07-31 20:28:14 +00007501 Constant::getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007502 }
7503 }
7504 break;
7505 case Instruction::Add:
7506 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7507 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7508 if (BO->hasOneUse())
Dan Gohmane6803b82009-08-25 23:17:54 +00007509 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007510 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007511 } else if (RHSV == 0) {
7512 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7513 // efficiently invertible, or if the add has just this one use.
7514 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7515
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007516 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohmane6803b82009-08-25 23:17:54 +00007517 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007518 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohmane6803b82009-08-25 23:17:54 +00007519 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007520 else if (BO->hasOneUse()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007521 Value *Neg = Builder->CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007522 Neg->takeName(BO);
Dan Gohmane6803b82009-08-25 23:17:54 +00007523 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007524 }
7525 }
7526 break;
7527 case Instruction::Xor:
7528 // For the xor case, we can xor two constants together, eliminating
7529 // the explicit xor.
7530 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00007531 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007532 ConstantExpr::getXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007533
7534 // FALLTHROUGH
7535 case Instruction::Sub:
7536 // Replace (([sub|xor] A, B) != 0) with (A != B)
7537 if (RHSV == 0)
Dan Gohmane6803b82009-08-25 23:17:54 +00007538 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007539 BO->getOperand(1));
7540 break;
7541
7542 case Instruction::Or:
7543 // If bits are being or'd in that are not present in the constant we
7544 // are comparing against, then the comparison could never succeed!
7545 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007546 Constant *NotCI = ConstantExpr::getNot(RHS);
7547 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00007548 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007549 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007550 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007551 }
7552 break;
7553
7554 case Instruction::And:
7555 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7556 // If bits are being compared against that are and'd out, then the
7557 // comparison can never succeed!
7558 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007559 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007560 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007561 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007562
7563 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7564 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohmane6803b82009-08-25 23:17:54 +00007565 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007566 ICmpInst::ICMP_NE, LHSI,
Owen Andersonaac28372009-07-31 20:28:14 +00007567 Constant::getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007568
7569 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007570 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007571 Value *X = BO->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +00007572 Constant *Zero = Constant::getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007573 ICmpInst::Predicate pred = isICMP_NE ?
7574 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohmane6803b82009-08-25 23:17:54 +00007575 return new ICmpInst(pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007576 }
7577
7578 // ((X & ~7) == 0) --> X < 8
7579 if (RHSV == 0 && isHighOnes(BOC)) {
7580 Value *X = BO->getOperand(0);
Owen Anderson02b48c32009-07-29 18:55:55 +00007581 Constant *NegX = ConstantExpr::getNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007582 ICmpInst::Predicate pred = isICMP_NE ?
7583 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohmane6803b82009-08-25 23:17:54 +00007584 return new ICmpInst(pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007585 }
7586 }
7587 default: break;
7588 }
7589 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7590 // Handle icmp {eq|ne} <intrinsic>, intcst.
7591 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner3183fb62009-08-30 06:13:40 +00007592 Worklist.Add(II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007593 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007594 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007595 return &ICI;
7596 }
7597 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007598 }
7599 return 0;
7600}
7601
7602/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7603/// We only handle extending casts so far.
7604///
7605Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7606 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7607 Value *LHSCIOp = LHSCI->getOperand(0);
7608 const Type *SrcTy = LHSCIOp->getType();
7609 const Type *DestTy = LHSCI->getType();
7610 Value *RHSCIOp;
7611
7612 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7613 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007614 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7615 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007616 cast<IntegerType>(DestTy)->getBitWidth()) {
7617 Value *RHSOp = 0;
7618 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007619 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007620 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7621 RHSOp = RHSC->getOperand(0);
7622 // If the pointer types don't match, insert a bitcast.
7623 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner78628292009-08-30 19:47:22 +00007624 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007625 }
7626
7627 if (RHSOp)
Dan Gohmane6803b82009-08-25 23:17:54 +00007628 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007629 }
7630
7631 // The code below only handles extension cast instructions, so far.
7632 // Enforce this.
7633 if (LHSCI->getOpcode() != Instruction::ZExt &&
7634 LHSCI->getOpcode() != Instruction::SExt)
7635 return 0;
7636
7637 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007638 bool isSignedCmp = ICI.isSigned();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007639
7640 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7641 // Not an extension from the same type?
7642 RHSCIOp = CI->getOperand(0);
7643 if (RHSCIOp->getType() != LHSCIOp->getType())
7644 return 0;
7645
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007646 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007647 // and the other is a zext), then we can't handle this.
7648 if (CI->getOpcode() != LHSCI->getOpcode())
7649 return 0;
7650
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007651 // Deal with equality cases early.
7652 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007653 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007654
7655 // A signed comparison of sign extended values simplifies into a
7656 // signed comparison.
7657 if (isSignedCmp && isSignedExt)
Dan Gohmane6803b82009-08-25 23:17:54 +00007658 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007659
7660 // The other three cases all fold into an unsigned comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00007661 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007662 }
7663
7664 // If we aren't dealing with a constant on the RHS, exit early
7665 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7666 if (!CI)
7667 return 0;
7668
7669 // Compute the constant that would happen if we truncated to SrcTy then
7670 // reextended to DestTy.
Owen Anderson02b48c32009-07-29 18:55:55 +00007671 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7672 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007673 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007674
7675 // If the re-extended constant didn't change...
7676 if (Res2 == CI) {
Eli Friedman96438472009-12-17 22:42:29 +00007677 // Deal with equality cases early.
7678 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007679 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Eli Friedman96438472009-12-17 22:42:29 +00007680
7681 // A signed comparison of sign extended values simplifies into a
7682 // signed comparison.
7683 if (isSignedExt && isSignedCmp)
7684 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7685
7686 // The other three cases all fold into an unsigned comparison.
7687 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007688 }
7689
7690 // The re-extended constant changed so the constant cannot be represented
7691 // in the shorter type. Consequently, we cannot emit a simple comparison.
7692
7693 // First, handle some easy cases. We know the result cannot be equal at this
7694 // point so handle the ICI.isEquality() cases
7695 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007696 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007697 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007698 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007699
7700 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7701 // should have been folded away previously and not enter in here.
7702 Value *Result;
7703 if (isSignedCmp) {
7704 // We're performing a signed comparison.
7705 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00007706 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007707 else
Owen Anderson4f720fa2009-07-31 17:39:07 +00007708 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007709 } else {
7710 // We're performing an unsigned comparison.
7711 if (isSignedExt) {
7712 // We're performing an unsigned comp with a sign extended value.
7713 // This is true if the input is >= 0. [aka >s -1]
Owen Andersonaac28372009-07-31 20:28:14 +00007714 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattnerc7694852009-08-30 07:44:24 +00007715 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007716 } else {
7717 // Unsigned extend & unsigned compare -> always true.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007718 Result = ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007719 }
7720 }
7721
7722 // Finally, return the value computed.
7723 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007724 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007725 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007726
7727 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7728 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7729 "ICmp should be folded!");
7730 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00007731 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohmancdff2122009-08-12 16:23:25 +00007732 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007733}
7734
7735Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7736 return commonShiftTransforms(I);
7737}
7738
7739Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7740 return commonShiftTransforms(I);
7741}
7742
7743Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007744 if (Instruction *R = commonShiftTransforms(I))
7745 return R;
7746
7747 Value *Op0 = I.getOperand(0);
7748
7749 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7750 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7751 if (CSI->isAllOnesValue())
7752 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007753
Dan Gohman2526aea2009-06-16 19:55:29 +00007754 // See if we can turn a signed shr into an unsigned shr.
7755 if (MaskedValueIsZero(Op0,
7756 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7757 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7758
7759 // Arithmetic shifting an all-sign-bit value is a no-op.
7760 unsigned NumSignBits = ComputeNumSignBits(Op0);
7761 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7762 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007763
Chris Lattnere3c504f2007-12-06 01:59:46 +00007764 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007765}
7766
7767Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7768 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7769 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7770
7771 // shl X, 0 == X and shr X, 0 == X
7772 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00007773 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7774 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007775 return ReplaceInstUsesWith(I, Op0);
7776
7777 if (isa<UndefValue>(Op0)) {
7778 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7779 return ReplaceInstUsesWith(I, Op0);
7780 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007781 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007782 }
7783 if (isa<UndefValue>(Op1)) {
7784 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7785 return ReplaceInstUsesWith(I, Op0);
7786 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007787 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007788 }
7789
Dan Gohman2bc21562009-05-21 02:28:33 +00007790 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007791 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007792 return &I;
7793
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007794 // Try to fold constant and into select arguments.
7795 if (isa<Constant>(Op0))
7796 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7797 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7798 return R;
7799
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007800 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7801 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7802 return Res;
7803 return 0;
7804}
7805
7806Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7807 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007808 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007809
7810 // See if we can simplify any instructions used by the instruction whose sole
7811 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007812 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007813
Dan Gohman9e1657f2009-06-14 23:30:43 +00007814 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7815 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007816 //
7817 if (Op1->uge(TypeBits)) {
7818 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007819 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007820 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007821 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007822 return &I;
7823 }
7824 }
7825
7826 // ((X*C1) << C2) == (X * (C1 << C2))
7827 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7828 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7829 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007830 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007831 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007832
7833 // Try to fold constant and into select arguments.
7834 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7835 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7836 return R;
7837 if (isa<PHINode>(Op0))
7838 if (Instruction *NV = FoldOpIntoPhi(I))
7839 return NV;
7840
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007841 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7842 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7843 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7844 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7845 // place. Don't try to do this transformation in this case. Also, we
7846 // require that the input operand is a shift-by-constant so that we have
7847 // confidence that the shifts will get folded together. We could do this
7848 // xform in more cases, but it is unlikely to be profitable.
7849 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7850 isa<ConstantInt>(TrOp->getOperand(1))) {
7851 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00007852 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00007853 // (shift2 (shift1 & 0x00FF), c2)
7854 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007855
7856 // For logical shifts, the truncation has the effect of making the high
7857 // part of the register be zeros. Emulate this by inserting an AND to
7858 // clear the top bits as needed. This 'and' will usually be zapped by
7859 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007860 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7861 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007862 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7863
7864 // The mask we constructed says what the trunc would do if occurring
7865 // between the shifts. We want to know the effect *after* the second
7866 // shift. We know that it is a logical shift by a constant, so adjust the
7867 // mask as appropriate.
7868 if (I.getOpcode() == Instruction::Shl)
7869 MaskV <<= Op1->getZExtValue();
7870 else {
7871 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7872 MaskV = MaskV.lshr(Op1->getZExtValue());
7873 }
7874
Chris Lattnerc7694852009-08-30 07:44:24 +00007875 // shift1 & 0x00FF
7876 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7877 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007878
7879 // Return the value truncated to the interesting size.
7880 return new TruncInst(And, I.getType());
7881 }
7882 }
7883
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007884 if (Op0->hasOneUse()) {
7885 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7886 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7887 Value *V1, *V2;
7888 ConstantInt *CC;
7889 switch (Op0BO->getOpcode()) {
7890 default: break;
7891 case Instruction::Add:
7892 case Instruction::And:
7893 case Instruction::Or:
7894 case Instruction::Xor: {
7895 // These operators commute.
7896 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7897 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007898 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerad7516a2009-08-30 18:50:58 +00007899 m_Specific(Op1)))) {
7900 Value *YS = // (Y << C)
7901 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7902 // (X + (Y << C))
7903 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7904 Op0BO->getOperand(1)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007905 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007906 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007907 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7908 }
7909
7910 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7911 Value *Op0BOOp1 = Op0BO->getOperand(1);
7912 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7913 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007914 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007915 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007916 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007917 Value *YS = // (Y << C)
7918 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7919 Op0BO->getName());
7920 // X & (CC << C)
7921 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7922 V1->getName()+".mask");
Gabor Greifa645dd32008-05-16 19:29:10 +00007923 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007924 }
7925 }
7926
7927 // FALL THROUGH.
7928 case Instruction::Sub: {
7929 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7930 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007931 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007932 m_Specific(Op1)))) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007933 Value *YS = // (Y << C)
7934 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7935 // (X + (Y << C))
7936 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7937 Op0BO->getOperand(0)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007938 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007939 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007940 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7941 }
7942
7943 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7944 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7945 match(Op0BO->getOperand(0),
7946 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007947 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007948 cast<BinaryOperator>(Op0BO->getOperand(0))
7949 ->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007950 Value *YS = // (Y << C)
7951 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7952 // X & (CC << C)
7953 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7954 V1->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007955
Gabor Greifa645dd32008-05-16 19:29:10 +00007956 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007957 }
7958
7959 break;
7960 }
7961 }
7962
7963
7964 // If the operand is an bitwise operator with a constant RHS, and the
7965 // shift is the only use, we can pull it out of the shift.
7966 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7967 bool isValid = true; // Valid only for And, Or, Xor
7968 bool highBitSet = false; // Transform if high bit of constant set?
7969
7970 switch (Op0BO->getOpcode()) {
7971 default: isValid = false; break; // Do not perform transform!
7972 case Instruction::Add:
7973 isValid = isLeftShift;
7974 break;
7975 case Instruction::Or:
7976 case Instruction::Xor:
7977 highBitSet = false;
7978 break;
7979 case Instruction::And:
7980 highBitSet = true;
7981 break;
7982 }
7983
7984 // If this is a signed shift right, and the high bit is modified
7985 // by the logical operation, do not perform the transformation.
7986 // The highBitSet boolean indicates the value of the high bit of
7987 // the constant which would cause it to be modified for this
7988 // operation.
7989 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007990 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007991 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007992
7993 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007994 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007995
Chris Lattnerad7516a2009-08-30 18:50:58 +00007996 Value *NewShift =
7997 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007998 NewShift->takeName(Op0BO);
7999
Gabor Greifa645dd32008-05-16 19:29:10 +00008000 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008001 NewRHS);
8002 }
8003 }
8004 }
8005 }
8006
8007 // Find out if this is a shift of a shift by a constant.
8008 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
8009 if (ShiftOp && !ShiftOp->isShift())
8010 ShiftOp = 0;
8011
8012 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
8013 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
8014 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
8015 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
8016 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
8017 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
8018 Value *X = ShiftOp->getOperand(0);
8019
8020 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008021
8022 const IntegerType *Ty = cast<IntegerType>(I.getType());
8023
8024 // Check for (X << c1) << c2 and (X >> c1) >> c2
8025 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00008026 // If this is oversized composite shift, then unsigned shifts get 0, ashr
8027 // saturates.
8028 if (AmtSum >= TypeBits) {
8029 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00008030 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00008031 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
8032 }
8033
Gabor Greifa645dd32008-05-16 19:29:10 +00008034 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008035 ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00008036 }
8037
8038 if (ShiftOp->getOpcode() == Instruction::LShr &&
8039 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00008040 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00008041 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00008042
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008043 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008044 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00008045 }
8046
8047 if (ShiftOp->getOpcode() == Instruction::AShr &&
8048 I.getOpcode() == Instruction::LShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008049 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00008050 if (AmtSum >= TypeBits)
8051 AmtSum = TypeBits-1;
8052
Chris Lattnerad7516a2009-08-30 18:50:58 +00008053 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008054
8055 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008056 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008057 }
8058
8059 // Okay, if we get here, one shift must be left, and the other shift must be
8060 // right. See if the amounts are equal.
8061 if (ShiftAmt1 == ShiftAmt2) {
8062 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
8063 if (I.getOpcode() == Instruction::Shl) {
8064 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008065 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008066 }
8067 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
8068 if (I.getOpcode() == Instruction::LShr) {
8069 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008070 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008071 }
8072 // We can simplify ((X << C) >>s C) into a trunc + sext.
8073 // NOTE: we could do this for any C, but that would make 'unusual' integer
8074 // types. For now, just stick to ones well-supported by the code
8075 // generators.
8076 const Type *SExtType = 0;
8077 switch (Ty->getBitWidth() - ShiftAmt1) {
8078 case 1 :
8079 case 8 :
8080 case 16 :
8081 case 32 :
8082 case 64 :
8083 case 128:
Owen Anderson35b47072009-08-13 21:58:54 +00008084 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008085 break;
8086 default: break;
8087 }
Chris Lattnerad7516a2009-08-30 18:50:58 +00008088 if (SExtType)
8089 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008090 // Otherwise, we can't handle it yet.
8091 } else if (ShiftAmt1 < ShiftAmt2) {
8092 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
8093
8094 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
8095 if (I.getOpcode() == Instruction::Shl) {
8096 assert(ShiftOp->getOpcode() == Instruction::LShr ||
8097 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008098 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008099
8100 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008101 return BinaryOperator::CreateAnd(Shift,
8102 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008103 }
8104
8105 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
8106 if (I.getOpcode() == Instruction::LShr) {
8107 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008108 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008109
8110 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008111 return BinaryOperator::CreateAnd(Shift,
8112 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008113 }
8114
8115 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
8116 } else {
8117 assert(ShiftAmt2 < ShiftAmt1);
8118 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
8119
8120 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
8121 if (I.getOpcode() == Instruction::Shl) {
8122 assert(ShiftOp->getOpcode() == Instruction::LShr ||
8123 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008124 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
8125 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008126
8127 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008128 return BinaryOperator::CreateAnd(Shift,
8129 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008130 }
8131
8132 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
8133 if (I.getOpcode() == Instruction::LShr) {
8134 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008135 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008136
8137 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008138 return BinaryOperator::CreateAnd(Shift,
8139 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008140 }
8141
8142 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
8143 }
8144 }
8145 return 0;
8146}
8147
8148
8149/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
8150/// expression. If so, decompose it, returning some value X, such that Val is
8151/// X*Scale+Offset.
8152///
8153static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00008154 int &Offset, LLVMContext *Context) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008155 assert(Val->getType() == Type::getInt32Ty(*Context) &&
8156 "Unexpected allocation size type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008157 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
8158 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00008159 Scale = 0;
Owen Anderson35b47072009-08-13 21:58:54 +00008160 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00008161 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
8162 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8163 if (I->getOpcode() == Instruction::Shl) {
8164 // This is a value scaled by '1 << the shift amt'.
8165 Scale = 1U << RHS->getZExtValue();
8166 Offset = 0;
8167 return I->getOperand(0);
8168 } else if (I->getOpcode() == Instruction::Mul) {
8169 // This value is scaled by 'RHS'.
8170 Scale = RHS->getZExtValue();
8171 Offset = 0;
8172 return I->getOperand(0);
8173 } else if (I->getOpcode() == Instruction::Add) {
8174 // We have X+C. Check to see if we really have (X*C2)+C1,
8175 // where C1 is divisible by C2.
8176 unsigned SubScale;
8177 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00008178 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
8179 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00008180 Offset += RHS->getZExtValue();
8181 Scale = SubScale;
8182 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008183 }
8184 }
8185 }
8186
8187 // Otherwise, we can't look past this.
8188 Scale = 1;
8189 Offset = 0;
8190 return Val;
8191}
8192
8193
8194/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
8195/// try to eliminate the cast by moving the type information into the alloc.
8196Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandezb1687302009-10-23 21:09:37 +00008197 AllocaInst &AI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008198 const PointerType *PTy = cast<PointerType>(CI.getType());
8199
Chris Lattnerad7516a2009-08-30 18:50:58 +00008200 BuilderTy AllocaBuilder(*Builder);
8201 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
8202
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008203 // Remove any uses of AI that are dead.
8204 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
8205
8206 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
8207 Instruction *User = cast<Instruction>(*UI++);
8208 if (isInstructionTriviallyDead(User)) {
8209 while (UI != E && *UI == User)
8210 ++UI; // If this instruction uses AI more than once, don't break UI.
8211
8212 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00008213 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008214 EraseInstFromFunction(*User);
8215 }
8216 }
Dan Gohmana80e2712009-07-21 23:21:54 +00008217
8218 // This requires TargetData to get the alloca alignment and size information.
8219 if (!TD) return 0;
8220
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008221 // Get the type really allocated and the type casted to.
8222 const Type *AllocElTy = AI.getAllocatedType();
8223 const Type *CastElTy = PTy->getElementType();
8224 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
8225
8226 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
8227 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
8228 if (CastElTyAlign < AllocElTyAlign) return 0;
8229
8230 // If the allocation has multiple uses, only promote it if we are strictly
8231 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00008232 // same, we open the door to infinite loops of various kinds. (A reference
8233 // from a dbg.declare doesn't count as a use for this purpose.)
8234 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
8235 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008236
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008237 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
8238 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008239 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
8240
8241 // See if we can satisfy the modulus by pulling a scale out of the array
8242 // size argument.
8243 unsigned ArraySizeScale;
8244 int ArrayOffset;
8245 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00008246 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
8247 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008248
8249 // If we can now satisfy the modulus, by using a non-1 scale, we really can
8250 // do the xform.
8251 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
8252 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
8253
8254 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
8255 Value *Amt = 0;
8256 if (Scale == 1) {
8257 Amt = NumElements;
8258 } else {
Owen Anderson35b47072009-08-13 21:58:54 +00008259 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008260 // Insert before the alloca, not before the cast.
8261 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008262 }
8263
8264 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson35b47072009-08-13 21:58:54 +00008265 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008266 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008267 }
8268
Victor Hernandezb1687302009-10-23 21:09:37 +00008269 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008270 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008271 New->takeName(&AI);
8272
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00008273 // If the allocation has one real use plus a dbg.declare, just remove the
8274 // declare.
8275 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
8276 EraseInstFromFunction(*DI);
8277 }
8278 // If the allocation has multiple real uses, insert a cast and change all
8279 // things that used it to use the new cast. This will also hack on CI, but it
8280 // will die soon.
8281 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008282 // New is the allocation instruction, pointer typed. AI is the original
8283 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008284 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008285 AI.replaceAllUsesWith(NewCast);
8286 }
8287 return ReplaceInstUsesWith(CI, New);
8288}
8289
8290/// CanEvaluateInDifferentType - Return true if we can take the specified value
8291/// and return it as type Ty without inserting any new casts and without
8292/// changing the computed value. This is used by code that tries to decide
8293/// whether promoting or shrinking integer operations to wider or smaller types
8294/// will allow us to eliminate a truncate or extend.
8295///
8296/// This is a truncation operation if Ty is smaller than V->getType(), or an
8297/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00008298///
8299/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
8300/// should return true if trunc(V) can be computed by computing V in the smaller
8301/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
8302/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8303/// efficiently truncated.
8304///
8305/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8306/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8307/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008308bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00008309 unsigned CastOpc,
8310 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008311 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008312 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008313 return true;
8314
8315 Instruction *I = dyn_cast<Instruction>(V);
8316 if (!I) return false;
8317
Dan Gohman8fd520a2009-06-15 22:12:54 +00008318 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008319
Chris Lattneref70bb82007-08-02 06:11:14 +00008320 // If this is an extension or truncate, we can often eliminate it.
8321 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8322 // If this is a cast from the destination type, we can trivially eliminate
8323 // it, and this will remove a cast overall.
8324 if (I->getOperand(0)->getType() == Ty) {
8325 // If the first operand is itself a cast, and is eliminable, do not count
8326 // this as an eliminable cast. We would prefer to eliminate those two
8327 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00008328 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00008329 ++NumCastsRemoved;
8330 return true;
8331 }
8332 }
8333
8334 // We can't extend or shrink something that has multiple uses: doing so would
8335 // require duplicating the instruction in general, which isn't profitable.
8336 if (!I->hasOneUse()) return false;
8337
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008338 unsigned Opc = I->getOpcode();
8339 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008340 case Instruction::Add:
8341 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008342 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008343 case Instruction::And:
8344 case Instruction::Or:
8345 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008346 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00008347 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008348 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00008349 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008350 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008351
Eli Friedman08c45bc2009-07-13 22:46:01 +00008352 case Instruction::UDiv:
8353 case Instruction::URem: {
8354 // UDiv and URem can be truncated if all the truncated bits are zero.
8355 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8356 uint32_t BitWidth = Ty->getScalarSizeInBits();
8357 if (BitWidth < OrigBitWidth) {
8358 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8359 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8360 MaskedValueIsZero(I->getOperand(1), Mask)) {
8361 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8362 NumCastsRemoved) &&
8363 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8364 NumCastsRemoved);
8365 }
8366 }
8367 break;
8368 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008369 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008370 // If we are truncating the result of this SHL, and if it's a shift of a
8371 // constant amount, we can always perform a SHL in a smaller type.
8372 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008373 uint32_t BitWidth = Ty->getScalarSizeInBits();
8374 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008375 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00008376 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008377 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008378 }
8379 break;
8380 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008381 // If this is a truncate of a logical shr, we can truncate it to a smaller
8382 // lshr iff we know that the bits we would otherwise be shifting in are
8383 // already zeros.
8384 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008385 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8386 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008387 if (BitWidth < OrigBitWidth &&
8388 MaskedValueIsZero(I->getOperand(0),
8389 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8390 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00008391 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008392 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008393 }
8394 }
8395 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008396 case Instruction::ZExt:
8397 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00008398 case Instruction::Trunc:
8399 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00008400 // can safely replace it. Note that replacing it does not reduce the number
8401 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008402 if (Opc == CastOpc)
8403 return true;
8404
8405 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00008406 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008407 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008408 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008409 case Instruction::Select: {
8410 SelectInst *SI = cast<SelectInst>(I);
8411 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008412 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008413 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008414 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008415 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008416 case Instruction::PHI: {
8417 // We can change a phi if we can change all operands.
8418 PHINode *PN = cast<PHINode>(I);
8419 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8420 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008421 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00008422 return false;
8423 return true;
8424 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008425 default:
8426 // TODO: Can handle more cases here.
8427 break;
8428 }
8429
8430 return false;
8431}
8432
8433/// EvaluateInDifferentType - Given an expression that
8434/// CanEvaluateInDifferentType returns true for, actually insert the code to
8435/// evaluate the expression.
8436Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8437 bool isSigned) {
8438 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner1cd526b2009-11-08 19:23:30 +00008439 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008440
8441 // Otherwise, it must be an instruction.
8442 Instruction *I = cast<Instruction>(V);
8443 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008444 unsigned Opc = I->getOpcode();
8445 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008446 case Instruction::Add:
8447 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00008448 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008449 case Instruction::And:
8450 case Instruction::Or:
8451 case Instruction::Xor:
8452 case Instruction::AShr:
8453 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00008454 case Instruction::Shl:
8455 case Instruction::UDiv:
8456 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008457 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8458 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008459 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008460 break;
8461 }
8462 case Instruction::Trunc:
8463 case Instruction::ZExt:
8464 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008465 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00008466 // just return the source. There's no need to insert it because it is not
8467 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008468 if (I->getOperand(0)->getType() == Ty)
8469 return I->getOperand(0);
8470
Chris Lattner4200c2062008-06-18 04:00:49 +00008471 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner1cd526b2009-11-08 19:23:30 +00008472 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00008473 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008474 case Instruction::Select: {
8475 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8476 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8477 Res = SelectInst::Create(I->getOperand(0), True, False);
8478 break;
8479 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008480 case Instruction::PHI: {
8481 PHINode *OPN = cast<PHINode>(I);
8482 PHINode *NPN = PHINode::Create(Ty);
8483 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8484 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8485 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8486 }
8487 Res = NPN;
8488 break;
8489 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008490 default:
8491 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00008492 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008493 break;
8494 }
8495
Chris Lattner4200c2062008-06-18 04:00:49 +00008496 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008497 return InsertNewInstBefore(Res, *I);
8498}
8499
8500/// @brief Implement the transforms common to all CastInst visitors.
8501Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8502 Value *Src = CI.getOperand(0);
8503
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008504 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8505 // eliminate it now.
8506 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8507 if (Instruction::CastOps opc =
8508 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8509 // The first cast (CSrc) is eliminable so we need to fix up or replace
8510 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008511 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008512 }
8513 }
8514
8515 // If we are casting a select then fold the cast into the select
8516 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8517 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8518 return NV;
8519
8520 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner1cd526b2009-11-08 19:23:30 +00008521 if (isa<PHINode>(Src)) {
8522 // We don't do this if this would create a PHI node with an illegal type if
8523 // it is currently legal.
8524 if (!isa<IntegerType>(Src->getType()) ||
8525 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerd0011092009-11-10 07:23:37 +00008526 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner1cd526b2009-11-08 19:23:30 +00008527 if (Instruction *NV = FoldOpIntoPhi(CI))
8528 return NV;
Chris Lattner1cd526b2009-11-08 19:23:30 +00008529 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008530
8531 return 0;
8532}
8533
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008534/// FindElementAtOffset - Given a type and a constant offset, determine whether
8535/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008536/// the specified offset. If so, fill them into NewIndices and return the
8537/// resultant element type, otherwise return null.
8538static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8539 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008540 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008541 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008542 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008543 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008544
8545 // Start with the index over the outer type. Note that the type size
8546 // might be zero (even if the offset isn't zero) if the indexed type
8547 // is something like [0 x {int, int}]
Owen Anderson35b47072009-08-13 21:58:54 +00008548 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008549 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008550 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008551 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008552 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008553
Chris Lattnerce48c462009-01-11 20:15:20 +00008554 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008555 if (Offset < 0) {
8556 --FirstIdx;
8557 Offset += TySize;
8558 assert(Offset >= 0);
8559 }
8560 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8561 }
8562
Owen Andersoneacb44d2009-07-24 23:12:02 +00008563 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008564
8565 // Index into the types. If we fail, set OrigBase to null.
8566 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008567 // Indexing into tail padding between struct/array elements.
8568 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008569 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008570
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008571 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8572 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008573 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8574 "Offset must stay within the indexed type");
8575
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008576 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson35b47072009-08-13 21:58:54 +00008577 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008578
8579 Offset -= SL->getElementOffset(Elt);
8580 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008581 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008582 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008583 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00008584 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008585 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008586 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008587 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008588 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008589 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008590 }
8591 }
8592
Chris Lattner54dddc72009-01-24 01:00:13 +00008593 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008594}
8595
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008596/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8597Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8598 Value *Src = CI.getOperand(0);
8599
8600 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8601 // If casting the result of a getelementptr instruction with no offset, turn
8602 // this into a cast of the original pointer!
8603 if (GEP->hasAllZeroIndices()) {
8604 // Changing the cast operand is usually not a good idea but it is safe
8605 // here because the pointer operand is being replaced with another
8606 // pointer operand so the opcode doesn't need to change.
Chris Lattner3183fb62009-08-30 06:13:40 +00008607 Worklist.Add(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008608 CI.setOperand(0, GEP->getOperand(0));
8609 return &CI;
8610 }
8611
8612 // If the GEP has a single use, and the base pointer is a bitcast, and the
8613 // GEP computes a constant offset, see if we can convert these three
8614 // instructions into fewer. This typically happens with unions and other
8615 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008616 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008617 if (GEP->hasAllConstantIndices()) {
8618 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner93e6ff92009-11-04 08:05:20 +00008619 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008620 int64_t Offset = OffsetV->getSExtValue();
8621
8622 // Get the base pointer input of the bitcast, and the type it points to.
8623 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8624 const Type *GEPIdxTy =
8625 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008626 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008627 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008628 // If we were able to index down into an element, create the GEP
8629 // and bitcast the result. This eliminates one bitcast, potentially
8630 // two.
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008631 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8632 Builder->CreateInBoundsGEP(OrigBase,
8633 NewIndices.begin(), NewIndices.end()) :
8634 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008635 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008636
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008637 if (isa<BitCastInst>(CI))
8638 return new BitCastInst(NGEP, CI.getType());
8639 assert(isa<PtrToIntInst>(CI));
8640 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008641 }
8642 }
8643 }
8644 }
8645
8646 return commonCastTransforms(CI);
8647}
8648
Eli Friedman827e37a2009-07-13 20:58:59 +00008649/// commonIntCastTransforms - This function implements the common transforms
8650/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008651Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8652 if (Instruction *Result = commonCastTransforms(CI))
8653 return Result;
8654
8655 Value *Src = CI.getOperand(0);
8656 const Type *SrcTy = Src->getType();
8657 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008658 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8659 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008660
8661 // See if we can simplify any instructions used by the LHS whose sole
8662 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008663 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008664 return &CI;
8665
8666 // If the source isn't an instruction or has more than one use then we
8667 // can't do anything more.
8668 Instruction *SrcI = dyn_cast<Instruction>(Src);
8669 if (!SrcI || !Src->hasOneUse())
8670 return 0;
8671
8672 // Attempt to propagate the cast into the instruction for int->int casts.
8673 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008674 // Only do this if the dest type is a simple type, don't convert the
8675 // expression tree to something weird like i93 unless the source is also
8676 // strange.
Chris Lattnerbc5d0132009-11-10 17:00:47 +00008677 if ((isa<VectorType>(DestTy) ||
8678 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8679 CanEvaluateInDifferentType(SrcI, DestTy,
8680 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008681 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008682 // eliminates the cast, so it is always a win. If this is a zero-extension,
8683 // we need to do an AND to maintain the clear top-part of the computation,
8684 // so we require that the input have eliminated at least one cast. If this
8685 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008686 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008687 bool DoXForm = false;
8688 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008689 switch (CI.getOpcode()) {
8690 default:
8691 // All the others use floating point so we shouldn't actually
8692 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008693 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008694 case Instruction::Trunc:
8695 DoXForm = true;
8696 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008697 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008698 DoXForm = NumCastsRemoved >= 1;
Chris Lattner2e9f5d02009-11-07 19:11:46 +00008699
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008700 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008701 // If it's unnecessary to issue an AND to clear the high bits, it's
8702 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008703 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008704 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8705 if (MaskedValueIsZero(TryRes, Mask))
8706 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008707
8708 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008709 if (TryI->use_empty())
8710 EraseInstFromFunction(*TryI);
8711 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008712 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008713 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008714 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008715 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008716 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008717 // If we do not have to emit the truncate + sext pair, then it's always
8718 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008719 //
8720 // It's not safe to eliminate the trunc + sext pair if one of the
8721 // eliminated cast is a truncate. e.g.
8722 // t2 = trunc i32 t1 to i16
8723 // t3 = sext i16 t2 to i32
8724 // !=
8725 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008726 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008727 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8728 if (NumSignBits > (DestBitSize - SrcBitSize))
8729 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008730
8731 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008732 if (TryI->use_empty())
8733 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008734 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008735 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008736 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008737 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008738
8739 if (DoXForm) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00008740 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8741 " to avoid cast: " << CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008742 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8743 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008744 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008745 // Just replace this cast with the result.
8746 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008747
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008748 assert(Res->getType() == DestTy);
8749 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008750 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008751 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008752 // Just replace this cast with the result.
8753 return ReplaceInstUsesWith(CI, Res);
8754 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008755 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008756
8757 // If the high bits are already zero, just replace this cast with the
8758 // result.
8759 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8760 if (MaskedValueIsZero(Res, Mask))
8761 return ReplaceInstUsesWith(CI, Res);
8762
8763 // We need to emit an AND to clear the high bits.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008764 Constant *C = ConstantInt::get(*Context,
8765 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008766 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008767 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008768 case Instruction::SExt: {
8769 // If the high bits are already filled with sign bit, just replace this
8770 // cast with the result.
8771 unsigned NumSignBits = ComputeNumSignBits(Res);
8772 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008773 return ReplaceInstUsesWith(CI, Res);
8774
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008775 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008776 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008777 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008778 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008779 }
8780 }
8781
8782 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8783 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8784
8785 switch (SrcI->getOpcode()) {
8786 case Instruction::Add:
8787 case Instruction::Mul:
8788 case Instruction::And:
8789 case Instruction::Or:
8790 case Instruction::Xor:
8791 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008792 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8793 // Don't insert two casts unless at least one can be eliminated.
8794 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008795 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008796 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8797 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008798 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008799 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8800 }
8801 }
8802
8803 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8804 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8805 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson4f720fa2009-07-31 17:39:07 +00008806 Op1 == ConstantInt::getTrue(*Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008807 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008808 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Anderson24be4c12009-07-03 00:17:18 +00008809 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008810 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008811 }
8812 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008813
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008814 case Instruction::Shl: {
8815 // Canonicalize trunc inside shl, if we can.
8816 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8817 if (CI && DestBitSize < SrcBitSize &&
8818 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008819 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8820 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008821 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008822 }
8823 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008824 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008825 }
8826 return 0;
8827}
8828
8829Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8830 if (Instruction *Result = commonIntCastTransforms(CI))
8831 return Result;
8832
8833 Value *Src = CI.getOperand(0);
8834 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008835 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8836 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008837
8838 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008839 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008840 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008841 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersonaac28372009-07-31 20:28:14 +00008842 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohmane6803b82009-08-25 23:17:54 +00008843 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008844 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008845
Chris Lattner32177f82009-03-24 18:15:30 +00008846 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8847 ConstantInt *ShAmtV = 0;
8848 Value *ShiftOp = 0;
8849 if (Src->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00008850 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner32177f82009-03-24 18:15:30 +00008851 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8852
8853 // Get a mask for the bits shifting in.
8854 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8855 if (MaskedValueIsZero(ShiftOp, Mask)) {
8856 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00008857 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008858
8859 // Okay, we can shrink this. Truncate the input, then return a new
8860 // shift.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008861 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Anderson02b48c32009-07-29 18:55:55 +00008862 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008863 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008864 }
8865 }
Chris Lattner1cd526b2009-11-08 19:23:30 +00008866
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008867 return 0;
8868}
8869
Evan Chenge3779cf2008-03-24 00:21:34 +00008870/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8871/// in order to eliminate the icmp.
8872Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8873 bool DoXform) {
8874 // If we are just checking for a icmp eq of a single bit and zext'ing it
8875 // to an integer, then shift the bit to the appropriate place and then
8876 // cast to integer to avoid the comparison.
8877 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8878 const APInt &Op1CV = Op1C->getValue();
8879
8880 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8881 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8882 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8883 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8884 if (!DoXform) return ICI;
8885
8886 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008887 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008888 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008889 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008890 if (In->getType() != CI.getType())
Chris Lattnerad7516a2009-08-30 18:50:58 +00008891 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008892
8893 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008894 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008895 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chenge3779cf2008-03-24 00:21:34 +00008896 }
8897
8898 return ReplaceInstUsesWith(CI, In);
8899 }
8900
8901
8902
8903 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8904 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8905 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8906 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8907 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8908 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8909 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8910 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8911 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8912 // This only works for EQ and NE
8913 ICI->isEquality()) {
8914 // If Op1C some other power of two, convert:
8915 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8916 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8917 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8918 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8919
8920 APInt KnownZeroMask(~KnownZero);
8921 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8922 if (!DoXform) return ICI;
8923
8924 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8925 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8926 // (X&4) == 2 --> false
8927 // (X&4) != 2 --> true
Owen Anderson35b47072009-08-13 21:58:54 +00008928 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00008929 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008930 return ReplaceInstUsesWith(CI, Res);
8931 }
8932
8933 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8934 Value *In = ICI->getOperand(0);
8935 if (ShiftAmt) {
8936 // Perform a logical shr by shiftamt.
8937 // Insert the shift to put the result in the low bit.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008938 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8939 In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008940 }
8941
8942 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008943 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008944 In = Builder->CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008945 }
8946
8947 if (CI.getType() == In->getType())
8948 return ReplaceInstUsesWith(CI, In);
8949 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008950 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008951 }
8952 }
8953 }
8954
Nick Lewyckyef61f692009-11-23 03:17:33 +00008955 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8956 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8957 // may lead to additional simplifications.
8958 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8959 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8960 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008961 Value *LHS = ICI->getOperand(0);
8962 Value *RHS = ICI->getOperand(1);
Nick Lewyckyef61f692009-11-23 03:17:33 +00008963
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008964 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8965 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8966 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8967 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8968 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewyckyef61f692009-11-23 03:17:33 +00008969
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008970 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
8971 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
8972 APInt UnknownBit = ~KnownBits;
8973 if (UnknownBit.countPopulation() == 1) {
Nick Lewyckyef61f692009-11-23 03:17:33 +00008974 if (!DoXform) return ICI;
8975
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008976 Value *Result = Builder->CreateXor(LHS, RHS);
8977
8978 // Mask off any bits that are set and won't be shifted away.
8979 if (KnownOneLHS.uge(UnknownBit))
8980 Result = Builder->CreateAnd(Result,
8981 ConstantInt::get(ITy, UnknownBit));
8982
8983 // Shift the bit we're testing down to the lsb.
8984 Result = Builder->CreateLShr(
8985 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
8986
Nick Lewyckyef61f692009-11-23 03:17:33 +00008987 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky2b7bc812009-12-05 05:00:00 +00008988 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
8989 Result->takeName(ICI);
8990 return ReplaceInstUsesWith(CI, Result);
Nick Lewyckyef61f692009-11-23 03:17:33 +00008991 }
8992 }
8993 }
8994 }
8995
Evan Chenge3779cf2008-03-24 00:21:34 +00008996 return 0;
8997}
8998
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008999Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
9000 // If one of the common conversion will work ..
9001 if (Instruction *Result = commonIntCastTransforms(CI))
9002 return Result;
9003
9004 Value *Src = CI.getOperand(0);
9005
Chris Lattner215d56e2009-02-17 20:47:23 +00009006 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
9007 // types and if the sizes are just right we can convert this into a logical
9008 // 'and' which will be much cheaper than the pair of casts.
9009 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
9010 // Get the sizes of the types involved. We know that the intermediate type
9011 // will be smaller than A or C, but don't know the relation between A and C.
9012 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00009013 unsigned SrcSize = A->getType()->getScalarSizeInBits();
9014 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
9015 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00009016 // If we're actually extending zero bits, then if
9017 // SrcSize < DstSize: zext(a & mask)
9018 // SrcSize == DstSize: a & mask
9019 // SrcSize > DstSize: trunc(a) & mask
9020 if (SrcSize < DstSize) {
9021 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00009022 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerad7516a2009-08-30 18:50:58 +00009023 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattner215d56e2009-02-17 20:47:23 +00009024 return new ZExtInst(And, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00009025 }
9026
9027 if (SrcSize == DstSize) {
Chris Lattner215d56e2009-02-17 20:47:23 +00009028 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00009029 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009030 AndValue));
Chris Lattnerad7516a2009-08-30 18:50:58 +00009031 }
9032 if (SrcSize > DstSize) {
9033 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattner215d56e2009-02-17 20:47:23 +00009034 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00009035 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00009036 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009037 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009038 }
9039 }
9040
Evan Chenge3779cf2008-03-24 00:21:34 +00009041 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
9042 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009043
Evan Chenge3779cf2008-03-24 00:21:34 +00009044 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
9045 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
9046 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
9047 // of the (zext icmp) will be transformed.
9048 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
9049 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
9050 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
9051 (transformZExtICmp(LHS, CI, false) ||
9052 transformZExtICmp(RHS, CI, false))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00009053 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
9054 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00009055 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009056 }
Evan Chenge3779cf2008-03-24 00:21:34 +00009057 }
9058
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00009059 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00009060 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
9061 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9062 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
9063 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00009064 if (TI0->getType() == CI.getType())
9065 return
9066 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00009067 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00009068 }
9069
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00009070 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
9071 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
9072 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9073 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
9074 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
9075 And->getOperand(1) == C)
9076 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
9077 Value *TI0 = TI->getOperand(0);
9078 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00009079 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00009080 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00009081 return BinaryOperator::CreateXor(NewAnd, ZC);
9082 }
9083 }
9084
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009085 return 0;
9086}
9087
9088Instruction *InstCombiner::visitSExt(SExtInst &CI) {
9089 if (Instruction *I = commonIntCastTransforms(CI))
9090 return I;
9091
9092 Value *Src = CI.getOperand(0);
9093
Dan Gohman35b76162008-10-30 20:40:10 +00009094 // Canonicalize sign-extend from i1 to a select.
Owen Anderson35b47072009-08-13 21:58:54 +00009095 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman35b76162008-10-30 20:40:10 +00009096 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00009097 Constant::getAllOnesValue(CI.getType()),
9098 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00009099
9100 // See if the value being truncated is already sign extended. If so, just
9101 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00009102 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00009103 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00009104 unsigned OpBits = Op->getType()->getScalarSizeInBits();
9105 unsigned MidBits = Src->getType()->getScalarSizeInBits();
9106 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00009107 unsigned NumSignBits = ComputeNumSignBits(Op);
9108
9109 if (OpBits == DestBits) {
9110 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
9111 // bits, it is already ready.
9112 if (NumSignBits > DestBits-MidBits)
9113 return ReplaceInstUsesWith(CI, Op);
9114 } else if (OpBits < DestBits) {
9115 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
9116 // bits, just sext from i32.
9117 if (NumSignBits > OpBits-MidBits)
9118 return new SExtInst(Op, CI.getType(), "tmp");
9119 } else {
9120 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
9121 // bits, just truncate to i32.
9122 if (NumSignBits > OpBits-MidBits)
9123 return new TruncInst(Op, CI.getType(), "tmp");
9124 }
9125 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00009126
9127 // If the input is a shl/ashr pair of a same constant, then this is a sign
9128 // extension from a smaller value. If we could trust arbitrary bitwidth
9129 // integers, we could turn this into a truncate to the smaller bit and then
9130 // use a sext for the whole extension. Since we don't, look deeper and check
9131 // for a truncate. If the source and dest are the same type, eliminate the
9132 // trunc and extend and just do shifts. For example, turn:
9133 // %a = trunc i32 %i to i8
9134 // %b = shl i8 %a, 6
9135 // %c = ashr i8 %b, 6
9136 // %d = sext i8 %c to i32
9137 // into:
9138 // %a = shl i32 %i, 30
9139 // %d = ashr i32 %a, 30
9140 Value *A = 0;
9141 ConstantInt *BA = 0, *CA = 0;
9142 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohmancdff2122009-08-12 16:23:25 +00009143 m_ConstantInt(CA))) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00009144 BA == CA && isa<TruncInst>(A)) {
9145 Value *I = cast<TruncInst>(A)->getOperand(0);
9146 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00009147 unsigned MidSize = Src->getType()->getScalarSizeInBits();
9148 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00009149 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00009150 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00009151 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner8a2d0592008-08-06 07:35:52 +00009152 return BinaryOperator::CreateAShr(I, ShAmtV);
9153 }
9154 }
9155
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009156 return 0;
9157}
9158
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009159/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
9160/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00009161static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00009162 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00009163 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009164 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00009165 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
9166 if (!losesInfo)
Owen Andersond363a0e2009-07-27 20:59:43 +00009167 return ConstantFP::get(*Context, F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009168 return 0;
9169}
9170
9171/// LookThroughFPExtensions - If this is an fp extension instruction, look
9172/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00009173static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009174 if (Instruction *I = dyn_cast<Instruction>(V))
9175 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00009176 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009177
9178 // If this value is a constant, return the constant in the smallest FP type
9179 // that can accurately represent it. This allows us to turn
9180 // (float)((double)X+2.0) into x+2.0f.
9181 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +00009182 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009183 return V; // No constant folding of this.
9184 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00009185 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009186 return V;
Owen Anderson35b47072009-08-13 21:58:54 +00009187 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009188 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00009189 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009190 return V;
9191 // Don't try to shrink to various long double types.
9192 }
9193
9194 return V;
9195}
9196
9197Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
9198 if (Instruction *I = commonCastTransforms(CI))
9199 return I;
9200
Dan Gohman7ce405e2009-06-04 22:49:04 +00009201 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009202 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00009203 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009204 // many builtins (sqrt, etc).
9205 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
9206 if (OpI && OpI->hasOneUse()) {
9207 switch (OpI->getOpcode()) {
9208 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009209 case Instruction::FAdd:
9210 case Instruction::FSub:
9211 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009212 case Instruction::FDiv:
9213 case Instruction::FRem:
9214 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00009215 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
9216 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009217 if (LHSTrunc->getType() != SrcTy &&
9218 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00009219 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009220 // If the source types were both smaller than the destination type of
9221 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00009222 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
9223 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00009224 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
9225 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00009226 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00009227 }
9228 }
9229 break;
9230 }
9231 }
9232 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009233}
9234
9235Instruction *InstCombiner::visitFPExt(CastInst &CI) {
9236 return commonCastTransforms(CI);
9237}
9238
Chris Lattnerdeef1a72008-05-19 20:25:04 +00009239Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00009240 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9241 if (OpI == 0)
9242 return commonCastTransforms(FI);
9243
9244 // fptoui(uitofp(X)) --> X
9245 // fptoui(sitofp(X)) --> X
9246 // This is safe if the intermediate type has enough bits in its mantissa to
9247 // accurately represent all values of X. For example, do not do this with
9248 // i64->float->i64. This is also safe for sitofp case, because any negative
9249 // 'X' value would cause an undefined result for the fptoui.
9250 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9251 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00009252 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00009253 OpI->getType()->getFPMantissaWidth())
9254 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00009255
9256 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009257}
9258
Chris Lattnerdeef1a72008-05-19 20:25:04 +00009259Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00009260 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9261 if (OpI == 0)
9262 return commonCastTransforms(FI);
9263
9264 // fptosi(sitofp(X)) --> X
9265 // fptosi(uitofp(X)) --> X
9266 // This is safe if the intermediate type has enough bits in its mantissa to
9267 // accurately represent all values of X. For example, do not do this with
9268 // i64->float->i64. This is also safe for sitofp case, because any negative
9269 // 'X' value would cause an undefined result for the fptoui.
9270 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9271 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00009272 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00009273 OpI->getType()->getFPMantissaWidth())
9274 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00009275
9276 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009277}
9278
9279Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
9280 return commonCastTransforms(CI);
9281}
9282
9283Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
9284 return commonCastTransforms(CI);
9285}
9286
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009287Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
9288 // If the destination integer type is smaller than the intptr_t type for
9289 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
9290 // trunc to be exposed to other transforms. Don't do this for extending
9291 // ptrtoint's, because we don't know if the target sign or zero extends its
9292 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00009293 if (TD &&
9294 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009295 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
9296 TD->getIntPtrType(CI.getContext()),
9297 "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009298 return new TruncInst(P, CI.getType());
9299 }
9300
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009301 return commonPointerCastTransforms(CI);
9302}
9303
Chris Lattner7c1626482008-01-08 07:23:51 +00009304Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009305 // If the source integer type is larger than the intptr_t type for
9306 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
9307 // allows the trunc to be exposed to other transforms. Don't do this for
9308 // extending inttoptr's, because we don't know if the target sign or zero
9309 // extends to pointers.
Chris Lattnerad7516a2009-08-30 18:50:58 +00009310 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009311 TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009312 Value *P = Builder->CreateTrunc(CI.getOperand(0),
9313 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00009314 return new IntToPtrInst(P, CI.getType());
9315 }
9316
Chris Lattner7c1626482008-01-08 07:23:51 +00009317 if (Instruction *I = commonCastTransforms(CI))
9318 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00009319
Chris Lattner7c1626482008-01-08 07:23:51 +00009320 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009321}
9322
9323Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
9324 // If the operands are integer typed then apply the integer transforms,
9325 // otherwise just apply the common ones.
9326 Value *Src = CI.getOperand(0);
9327 const Type *SrcTy = Src->getType();
9328 const Type *DestTy = CI.getType();
9329
Eli Friedman5013d3f2009-07-13 20:53:00 +00009330 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009331 if (Instruction *I = commonPointerCastTransforms(CI))
9332 return I;
9333 } else {
9334 if (Instruction *Result = commonCastTransforms(CI))
9335 return Result;
9336 }
9337
9338
9339 // Get rid of casts from one type to the same type. These are useless and can
9340 // be replaced by the operand.
9341 if (DestTy == Src->getType())
9342 return ReplaceInstUsesWith(CI, Src);
9343
9344 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9345 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9346 const Type *DstElTy = DstPTy->getElementType();
9347 const Type *SrcElTy = SrcPTy->getElementType();
9348
Nate Begemandf5b3612008-03-31 00:22:16 +00009349 // If the address spaces don't match, don't eliminate the bitcast, which is
9350 // required for changing types.
9351 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9352 return 0;
9353
Victor Hernandez48c3c542009-09-18 22:35:49 +00009354 // If we are casting a alloca to a pointer to a type of the same
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009355 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez48c3c542009-09-18 22:35:49 +00009356 // There is no need to modify malloc calls because it is their bitcast that
9357 // needs to be cleaned up.
Victor Hernandezb1687302009-10-23 21:09:37 +00009358 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009359 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9360 return V;
9361
9362 // If the source and destination are pointers, and this cast is equivalent
9363 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
9364 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson35b47072009-08-13 21:58:54 +00009365 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009366 unsigned NumZeros = 0;
9367 while (SrcElTy != DstElTy &&
9368 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9369 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9370 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9371 ++NumZeros;
9372 }
9373
9374 // If we found a path from the src to dest, create the getelementptr now.
9375 if (SrcElTy == DstElTy) {
9376 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf3a08b82009-09-07 23:54:19 +00009377 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9378 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009379 }
9380 }
9381
Eli Friedman1d31dee2009-07-18 23:06:53 +00009382 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9383 if (DestVTy->getNumElements() == 1) {
9384 if (!isa<VectorType>(SrcTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00009385 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00009386 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattnerd6164c22009-08-30 20:01:10 +00009387 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009388 }
9389 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9390 }
9391 }
9392
9393 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9394 if (SrcVTy->getNumElements() == 1) {
9395 if (!isa<VectorType>(DestTy)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009396 Value *Elem =
9397 Builder->CreateExtractElement(Src,
9398 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009399 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9400 }
9401 }
9402 }
9403
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009404 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9405 if (SVI->hasOneUse()) {
9406 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9407 // a bitconvert to a vector with the same # elts.
9408 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009409 cast<VectorType>(DestTy)->getNumElements() ==
9410 SVI->getType()->getNumElements() &&
9411 SVI->getType()->getNumElements() ==
9412 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009413 CastInst *Tmp;
9414 // If either of the operands is a cast from CI.getType(), then
9415 // evaluating the shuffle in the casted destination's type will allow
9416 // us to eliminate at least one cast.
9417 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9418 Tmp->getOperand(0)->getType() == DestTy) ||
9419 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9420 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00009421 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9422 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009423 // Return a new shuffle vector. Use the same element ID's, as we
9424 // know the vector types match #elts.
9425 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9426 }
9427 }
9428 }
9429 }
9430 return 0;
9431}
9432
9433/// GetSelectFoldableOperands - We want to turn code that looks like this:
9434/// %C = or %A, %B
9435/// %D = select %cond, %C, %A
9436/// into:
9437/// %C = select %cond, %B, 0
9438/// %D = or %A, %C
9439///
9440/// Assuming that the specified instruction is an operand to the select, return
9441/// a bitmask indicating which operands of this instruction are foldable if they
9442/// equal the other incoming value of the select.
9443///
9444static unsigned GetSelectFoldableOperands(Instruction *I) {
9445 switch (I->getOpcode()) {
9446 case Instruction::Add:
9447 case Instruction::Mul:
9448 case Instruction::And:
9449 case Instruction::Or:
9450 case Instruction::Xor:
9451 return 3; // Can fold through either operand.
9452 case Instruction::Sub: // Can only fold on the amount subtracted.
9453 case Instruction::Shl: // Can only fold on the shift amount.
9454 case Instruction::LShr:
9455 case Instruction::AShr:
9456 return 1;
9457 default:
9458 return 0; // Cannot fold
9459 }
9460}
9461
9462/// GetSelectFoldableConstant - For the same transformation as the previous
9463/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00009464static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00009465 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009466 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00009467 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009468 case Instruction::Add:
9469 case Instruction::Sub:
9470 case Instruction::Or:
9471 case Instruction::Xor:
9472 case Instruction::Shl:
9473 case Instruction::LShr:
9474 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00009475 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009476 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00009477 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009478 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00009479 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009480 }
9481}
9482
9483/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9484/// have the same opcode and only one use each. Try to simplify this.
9485Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9486 Instruction *FI) {
9487 if (TI->getNumOperands() == 1) {
9488 // If this is a non-volatile load or a cast from the same type,
9489 // merge.
9490 if (TI->isCast()) {
9491 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9492 return 0;
9493 } else {
9494 return 0; // unknown unary op.
9495 }
9496
9497 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009498 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00009499 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009500 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009501 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009502 TI->getType());
9503 }
9504
9505 // Only handle binary operators here.
9506 if (!isa<BinaryOperator>(TI))
9507 return 0;
9508
9509 // Figure out if the operations have any operands in common.
9510 Value *MatchOp, *OtherOpT, *OtherOpF;
9511 bool MatchIsOpZero;
9512 if (TI->getOperand(0) == FI->getOperand(0)) {
9513 MatchOp = TI->getOperand(0);
9514 OtherOpT = TI->getOperand(1);
9515 OtherOpF = FI->getOperand(1);
9516 MatchIsOpZero = true;
9517 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9518 MatchOp = TI->getOperand(1);
9519 OtherOpT = TI->getOperand(0);
9520 OtherOpF = FI->getOperand(0);
9521 MatchIsOpZero = false;
9522 } else if (!TI->isCommutative()) {
9523 return 0;
9524 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9525 MatchOp = TI->getOperand(0);
9526 OtherOpT = TI->getOperand(1);
9527 OtherOpF = FI->getOperand(0);
9528 MatchIsOpZero = true;
9529 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9530 MatchOp = TI->getOperand(1);
9531 OtherOpT = TI->getOperand(0);
9532 OtherOpF = FI->getOperand(1);
9533 MatchIsOpZero = true;
9534 } else {
9535 return 0;
9536 }
9537
9538 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009539 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9540 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009541 InsertNewInstBefore(NewSI, SI);
9542
9543 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9544 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009545 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009546 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009547 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009548 }
Edwin Törökbd448e32009-07-14 16:55:14 +00009549 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009550 return 0;
9551}
9552
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009553static bool isSelect01(Constant *C1, Constant *C2) {
9554 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9555 if (!C1I)
9556 return false;
9557 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9558 if (!C2I)
9559 return false;
9560 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9561}
9562
9563/// FoldSelectIntoOp - Try fold the select into one of the operands to
9564/// facilitate further optimization.
9565Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9566 Value *FalseVal) {
9567 // See the comment above GetSelectFoldableOperands for a description of the
9568 // transformation we are doing here.
9569 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9570 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9571 !isa<Constant>(FalseVal)) {
9572 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9573 unsigned OpToFold = 0;
9574 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9575 OpToFold = 1;
9576 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9577 OpToFold = 2;
9578 }
9579
9580 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009581 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009582 Value *OOp = TVI->getOperand(2-OpToFold);
9583 // Avoid creating select between 2 constants unless it's selecting
9584 // between 0 and 1.
9585 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9586 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9587 InsertNewInstBefore(NewSel, SI);
9588 NewSel->takeName(TVI);
9589 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9590 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009591 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009592 }
9593 }
9594 }
9595 }
9596 }
9597
9598 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9599 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9600 !isa<Constant>(TrueVal)) {
9601 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9602 unsigned OpToFold = 0;
9603 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9604 OpToFold = 1;
9605 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9606 OpToFold = 2;
9607 }
9608
9609 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009610 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009611 Value *OOp = FVI->getOperand(2-OpToFold);
9612 // Avoid creating select between 2 constants unless it's selecting
9613 // between 0 and 1.
9614 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9615 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9616 InsertNewInstBefore(NewSel, SI);
9617 NewSel->takeName(FVI);
9618 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9619 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009620 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009621 }
9622 }
9623 }
9624 }
9625 }
9626
9627 return 0;
9628}
9629
Dan Gohman58c09632008-09-16 18:46:06 +00009630/// visitSelectInstWithICmp - Visit a SelectInst that has an
9631/// ICmpInst as its first operand.
9632///
9633Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9634 ICmpInst *ICI) {
9635 bool Changed = false;
9636 ICmpInst::Predicate Pred = ICI->getPredicate();
9637 Value *CmpLHS = ICI->getOperand(0);
9638 Value *CmpRHS = ICI->getOperand(1);
9639 Value *TrueVal = SI.getTrueValue();
9640 Value *FalseVal = SI.getFalseValue();
9641
9642 // Check cases where the comparison is with a constant that
9643 // can be adjusted to fit the min/max idiom. We may edit ICI in
9644 // place here, so make sure the select is the only user.
9645 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009646 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009647 switch (Pred) {
9648 default: break;
9649 case ICmpInst::ICMP_ULT:
9650 case ICmpInst::ICMP_SLT: {
9651 // X < MIN ? T : F --> F
9652 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9653 return ReplaceInstUsesWith(SI, FalseVal);
9654 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009655 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009656 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9657 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9658 Pred = ICmpInst::getSwappedPredicate(Pred);
9659 CmpRHS = AdjustedRHS;
9660 std::swap(FalseVal, TrueVal);
9661 ICI->setPredicate(Pred);
9662 ICI->setOperand(1, CmpRHS);
9663 SI.setOperand(1, TrueVal);
9664 SI.setOperand(2, FalseVal);
9665 Changed = true;
9666 }
9667 break;
9668 }
9669 case ICmpInst::ICMP_UGT:
9670 case ICmpInst::ICMP_SGT: {
9671 // X > MAX ? T : F --> F
9672 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9673 return ReplaceInstUsesWith(SI, FalseVal);
9674 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009675 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009676 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9677 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9678 Pred = ICmpInst::getSwappedPredicate(Pred);
9679 CmpRHS = AdjustedRHS;
9680 std::swap(FalseVal, TrueVal);
9681 ICI->setPredicate(Pred);
9682 ICI->setOperand(1, CmpRHS);
9683 SI.setOperand(1, TrueVal);
9684 SI.setOperand(2, FalseVal);
9685 Changed = true;
9686 }
9687 break;
9688 }
9689 }
9690
Dan Gohman35b76162008-10-30 20:40:10 +00009691 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9692 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009693 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohmancdff2122009-08-12 16:23:25 +00009694 if (match(TrueVal, m_ConstantInt<-1>()) &&
9695 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009696 Pred = ICI->getPredicate();
Dan Gohmancdff2122009-08-12 16:23:25 +00009697 else if (match(TrueVal, m_ConstantInt<0>()) &&
9698 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009699 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9700
Dan Gohman35b76162008-10-30 20:40:10 +00009701 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9702 // If we are just checking for a icmp eq of a single bit and zext'ing it
9703 // to an integer, then shift the bit to the appropriate place and then
9704 // cast to integer to avoid the comparison.
9705 const APInt &Op1CV = CI->getValue();
9706
9707 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9708 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9709 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009710 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009711 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00009712 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009713 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009714 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00009715 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00009716 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009717 if (In->getType() != SI.getType())
9718 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009719 true/*SExt*/, "tmp", ICI);
9720
9721 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohmancdff2122009-08-12 16:23:25 +00009722 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman35b76162008-10-30 20:40:10 +00009723 In->getName()+".not"), *ICI);
9724
9725 return ReplaceInstUsesWith(SI, In);
9726 }
9727 }
9728 }
9729
Dan Gohman58c09632008-09-16 18:46:06 +00009730 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9731 // Transform (X == Y) ? X : Y -> Y
9732 if (Pred == ICmpInst::ICMP_EQ)
9733 return ReplaceInstUsesWith(SI, FalseVal);
9734 // Transform (X != Y) ? X : Y -> X
9735 if (Pred == ICmpInst::ICMP_NE)
9736 return ReplaceInstUsesWith(SI, TrueVal);
9737 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9738
9739 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9740 // Transform (X == Y) ? Y : X -> X
9741 if (Pred == ICmpInst::ICMP_EQ)
9742 return ReplaceInstUsesWith(SI, FalseVal);
9743 // Transform (X != Y) ? Y : X -> Y
9744 if (Pred == ICmpInst::ICMP_NE)
9745 return ReplaceInstUsesWith(SI, TrueVal);
9746 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9747 }
Dan Gohman58c09632008-09-16 18:46:06 +00009748 return Changed ? &SI : 0;
9749}
9750
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009751
Chris Lattnerb5ed7f02009-10-22 00:17:26 +00009752/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9753/// PHI node (but the two may be in different blocks). See if the true/false
9754/// values (V) are live in all of the predecessor blocks of the PHI. For
9755/// example, cases like this cannot be mapped:
9756///
9757/// X = phi [ C1, BB1], [C2, BB2]
9758/// Y = add
9759/// Z = select X, Y, 0
9760///
9761/// because Y is not live in BB1/BB2.
9762///
9763static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9764 const SelectInst &SI) {
9765 // If the value is a non-instruction value like a constant or argument, it
9766 // can always be mapped.
9767 const Instruction *I = dyn_cast<Instruction>(V);
9768 if (I == 0) return true;
9769
9770 // If V is a PHI node defined in the same block as the condition PHI, we can
9771 // map the arguments.
9772 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9773
9774 if (const PHINode *VP = dyn_cast<PHINode>(I))
9775 if (VP->getParent() == CondPHI->getParent())
9776 return true;
9777
9778 // Otherwise, if the PHI and select are defined in the same block and if V is
9779 // defined in a different block, then we can transform it.
9780 if (SI.getParent() == CondPHI->getParent() &&
9781 I->getParent() != CondPHI->getParent())
9782 return true;
9783
9784 // Otherwise we have a 'hard' case and we can't tell without doing more
9785 // detailed dominator based analysis, punt.
9786 return false;
9787}
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009788
Chris Lattner78500cb2009-12-21 06:03:05 +00009789/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
9790/// SPF2(SPF1(A, B), C)
9791Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
9792 SelectPatternFlavor SPF1,
9793 Value *A, Value *B,
9794 Instruction &Outer,
9795 SelectPatternFlavor SPF2, Value *C) {
9796 if (C == A || C == B) {
9797 // MAX(MAX(A, B), B) -> MAX(A, B)
9798 // MIN(MIN(a, b), a) -> MIN(a, b)
9799 if (SPF1 == SPF2)
9800 return ReplaceInstUsesWith(Outer, Inner);
9801
9802 // MAX(MIN(a, b), a) -> a
9803 // MIN(MAX(a, b), a) -> a
Daniel Dunbarb61aa2b2009-12-21 23:27:57 +00009804 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
9805 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
9806 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
9807 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattner78500cb2009-12-21 06:03:05 +00009808 return ReplaceInstUsesWith(Outer, C);
9809 }
9810
9811 // TODO: MIN(MIN(A, 23), 97)
9812 return 0;
9813}
9814
9815
9816
9817
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009818Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9819 Value *CondVal = SI.getCondition();
9820 Value *TrueVal = SI.getTrueValue();
9821 Value *FalseVal = SI.getFalseValue();
9822
9823 // select true, X, Y -> X
9824 // select false, X, Y -> Y
9825 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9826 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9827
9828 // select C, X, X -> X
9829 if (TrueVal == FalseVal)
9830 return ReplaceInstUsesWith(SI, TrueVal);
9831
9832 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9833 return ReplaceInstUsesWith(SI, FalseVal);
9834 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9835 return ReplaceInstUsesWith(SI, TrueVal);
9836 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9837 if (isa<Constant>(TrueVal))
9838 return ReplaceInstUsesWith(SI, TrueVal);
9839 else
9840 return ReplaceInstUsesWith(SI, FalseVal);
9841 }
9842
Owen Anderson35b47072009-08-13 21:58:54 +00009843 if (SI.getType() == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009844 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9845 if (C->getZExtValue()) {
9846 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009847 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009848 } else {
9849 // Change: A = select B, false, C --> A = and !B, C
9850 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009851 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009852 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009853 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009854 }
9855 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9856 if (C->getZExtValue() == false) {
9857 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009858 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009859 } else {
9860 // Change: A = select B, C, true --> A = or !B, C
9861 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009862 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009863 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009864 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009865 }
9866 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009867
9868 // select a, b, a -> a&b
9869 // select a, a, b -> a|b
9870 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009871 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009872 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009873 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009874 }
9875
9876 // Selecting between two integer constants?
9877 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9878 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9879 // select C, 1, 0 -> zext C to int
9880 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009881 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009882 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9883 // select C, 0, 1 -> zext !C to int
9884 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009885 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009886 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009887 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009888 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009889
9890 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009891 // If one of the constants is zero (we know they can't both be) and we
9892 // have an icmp instruction with zero, and we have an 'and' with the
9893 // non-constant value, eliminate this whole mess. This corresponds to
9894 // cases like this: ((X & 27) ? 27 : 0)
9895 if (TrueValC->isZero() || FalseValC->isZero())
9896 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9897 cast<Constant>(IC->getOperand(1))->isNullValue())
9898 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9899 if (ICA->getOpcode() == Instruction::And &&
9900 isa<ConstantInt>(ICA->getOperand(1)) &&
9901 (ICA->getOperand(1) == TrueValC ||
9902 ICA->getOperand(1) == FalseValC) &&
9903 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9904 // Okay, now we know that everything is set up, we just don't
9905 // know whether we have a icmp_ne or icmp_eq and whether the
9906 // true or false val is the zero.
9907 bool ShouldNotVal = !TrueValC->isZero();
9908 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9909 Value *V = ICA;
9910 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009911 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009912 Instruction::Xor, V, ICA->getOperand(1)), SI);
9913 return ReplaceInstUsesWith(SI, V);
9914 }
9915 }
9916 }
9917
9918 // See if we are selecting two values based on a comparison of the two values.
9919 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9920 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9921 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009922 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9923 // This is not safe in general for floating point:
9924 // consider X== -0, Y== +0.
9925 // It becomes safe if either operand is a nonzero constant.
9926 ConstantFP *CFPt, *CFPf;
9927 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9928 !CFPt->getValueAPF().isZero()) ||
9929 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9930 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009931 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009932 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009933 // Transform (X != Y) ? X : Y -> X
9934 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9935 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009936 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009937
9938 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9939 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009940 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9941 // This is not safe in general for floating point:
9942 // consider X== -0, Y== +0.
9943 // It becomes safe if either operand is a nonzero constant.
9944 ConstantFP *CFPt, *CFPf;
9945 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9946 !CFPt->getValueAPF().isZero()) ||
9947 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9948 !CFPf->getValueAPF().isZero()))
9949 return ReplaceInstUsesWith(SI, FalseVal);
9950 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009951 // Transform (X != Y) ? Y : X -> Y
9952 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9953 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009954 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009955 }
Dan Gohman58c09632008-09-16 18:46:06 +00009956 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009957 }
9958
9959 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009960 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9961 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9962 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009963
9964 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9965 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9966 if (TI->hasOneUse() && FI->hasOneUse()) {
9967 Instruction *AddOp = 0, *SubOp = 0;
9968
9969 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9970 if (TI->getOpcode() == FI->getOpcode())
9971 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9972 return IV;
9973
9974 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9975 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009976 if ((TI->getOpcode() == Instruction::Sub &&
9977 FI->getOpcode() == Instruction::Add) ||
9978 (TI->getOpcode() == Instruction::FSub &&
9979 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009980 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009981 } else if ((FI->getOpcode() == Instruction::Sub &&
9982 TI->getOpcode() == Instruction::Add) ||
9983 (FI->getOpcode() == Instruction::FSub &&
9984 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009985 AddOp = TI; SubOp = FI;
9986 }
9987
9988 if (AddOp) {
9989 Value *OtherAddOp = 0;
9990 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9991 OtherAddOp = AddOp->getOperand(1);
9992 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9993 OtherAddOp = AddOp->getOperand(0);
9994 }
9995
9996 if (OtherAddOp) {
9997 // So at this point we know we have (Y -> OtherAddOp):
9998 // select C, (add X, Y), (sub X, Z)
9999 Value *NegVal; // Compute -Z
10000 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +000010001 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010002 } else {
10003 NegVal = InsertNewInstBefore(
Dan Gohmancdff2122009-08-12 16:23:25 +000010004 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +000010005 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010006 }
10007
10008 Value *NewTrueOp = OtherAddOp;
10009 Value *NewFalseOp = NegVal;
10010 if (AddOp != TI)
10011 std::swap(NewTrueOp, NewFalseOp);
10012 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010013 SelectInst::Create(CondVal, NewTrueOp,
10014 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010015
10016 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +000010017 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010018 }
10019 }
10020 }
10021
10022 // See if we can fold the select into one of our operands.
10023 if (SI.getType()->isInteger()) {
Chris Lattner78500cb2009-12-21 06:03:05 +000010024 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Cheng9f8ee8f2009-03-31 20:42:45 +000010025 return FoldI;
Chris Lattner78500cb2009-12-21 06:03:05 +000010026
10027 // MAX(MAX(a, b), a) -> MAX(a, b)
10028 // MIN(MIN(a, b), a) -> MIN(a, b)
10029 // MAX(MIN(a, b), a) -> a
10030 // MIN(MAX(a, b), a) -> a
10031 Value *LHS, *RHS, *LHS2, *RHS2;
10032 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
10033 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
10034 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
10035 SI, SPF, RHS))
10036 return R;
10037 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
10038 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
10039 SI, SPF, LHS))
10040 return R;
10041 }
10042
10043 // TODO.
10044 // ABS(-X) -> ABS(X)
10045 // ABS(ABS(X)) -> ABS(X)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010046 }
10047
Chris Lattnerb5ed7f02009-10-22 00:17:26 +000010048 // See if we can fold the select into a phi node if the condition is a select.
10049 if (isa<PHINode>(SI.getCondition()))
10050 // The true/false values have to be live in the PHI predecessor's blocks.
10051 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
10052 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
10053 if (Instruction *NV = FoldOpIntoPhi(SI))
10054 return NV;
Chris Lattnerf7843b72009-09-27 19:57:57 +000010055
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010056 if (BinaryOperator::isNot(CondVal)) {
10057 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
10058 SI.setOperand(1, FalseVal);
10059 SI.setOperand(2, TrueVal);
10060 return &SI;
10061 }
10062
10063 return 0;
10064}
10065
Dan Gohman2d648bb2008-04-10 18:43:06 +000010066/// EnforceKnownAlignment - If the specified pointer points to an object that
10067/// we control, modify the object's alignment to PrefAlign. This isn't
10068/// often possible though. If alignment is important, a more reliable approach
10069/// is to simply align all global variables and allocation instructions to
10070/// their preferred alignment from the beginning.
10071///
10072static unsigned EnforceKnownAlignment(Value *V,
10073 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +000010074
Dan Gohman2d648bb2008-04-10 18:43:06 +000010075 User *U = dyn_cast<User>(V);
10076 if (!U) return Align;
10077
Dan Gohman9545fb02009-07-17 20:47:02 +000010078 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +000010079 default: break;
10080 case Instruction::BitCast:
10081 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
10082 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010083 // If all indexes are zero, it is just the alignment of the base pointer.
10084 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +000010085 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +000010086 if (!isa<Constant>(*i) ||
10087 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010088 AllZeroOperands = false;
10089 break;
10090 }
Chris Lattner47cf3452007-08-09 19:05:49 +000010091
10092 if (AllZeroOperands) {
10093 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010094 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +000010095 }
Dan Gohman2d648bb2008-04-10 18:43:06 +000010096 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010097 }
Dan Gohman2d648bb2008-04-10 18:43:06 +000010098 }
10099
10100 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
10101 // If there is a large requested alignment and we can, bump up the alignment
10102 // of the global.
10103 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +000010104 if (GV->getAlignment() >= PrefAlign)
10105 Align = GV->getAlignment();
10106 else {
10107 GV->setAlignment(PrefAlign);
10108 Align = PrefAlign;
10109 }
Dan Gohman2d648bb2008-04-10 18:43:06 +000010110 }
Chris Lattnere8ad9ae2009-09-27 21:42:46 +000010111 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
10112 // If there is a requested alignment and if this is an alloca, round up.
10113 if (AI->getAlignment() >= PrefAlign)
10114 Align = AI->getAlignment();
10115 else {
10116 AI->setAlignment(PrefAlign);
10117 Align = PrefAlign;
Dan Gohman2d648bb2008-04-10 18:43:06 +000010118 }
10119 }
10120
10121 return Align;
10122}
10123
10124/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
10125/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
10126/// and it is more than the alignment of the ultimate object, see if we can
10127/// increase the alignment of the ultimate object, making this check succeed.
10128unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
10129 unsigned PrefAlign) {
10130 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
10131 sizeof(PrefAlign) * CHAR_BIT;
10132 APInt Mask = APInt::getAllOnesValue(BitWidth);
10133 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
10134 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
10135 unsigned TrailZ = KnownZero.countTrailingOnes();
10136 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
10137
10138 if (PrefAlign > Align)
10139 Align = EnforceKnownAlignment(V, Align, PrefAlign);
10140
10141 // We don't need to make any adjustment.
10142 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010143}
10144
Chris Lattner00ae5132008-01-13 23:50:23 +000010145Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +000010146 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +000010147 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +000010148 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +000010149 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +000010150
10151 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000010152 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +000010153 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +000010154 return MI;
10155 }
10156
10157 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
10158 // load/store.
10159 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
10160 if (MemOpLength == 0) return 0;
10161
Chris Lattnerc669fb62008-01-14 00:28:35 +000010162 // Source and destination pointer types are always "i8*" for intrinsic. See
10163 // if the size is something we can handle with a single primitive load/store.
10164 // A single load+store correctly handles overlapping memory in the memmove
10165 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +000010166 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +000010167 if (Size == 0) return MI; // Delete this mem transfer.
10168
10169 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +000010170 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +000010171
Chris Lattnerc669fb62008-01-14 00:28:35 +000010172 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +000010173 Type *NewPtrTy =
Owen Anderson35b47072009-08-13 21:58:54 +000010174 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +000010175
10176 // Memcpy forces the use of i8* for the source and destination. That means
10177 // that if you're using memcpy to move one double around, you'll get a cast
10178 // from double* to i8*. We'd much rather use a double load+store rather than
10179 // an i64 load+store, here because this improves the odds that the source or
10180 // dest address will be promotable. See if we can find a better type than the
10181 // integer datatype.
10182 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
10183 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000010184 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +000010185 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
10186 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +000010187 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +000010188 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
10189 if (STy->getNumElements() == 1)
10190 SrcETy = STy->getElementType(0);
10191 else
10192 break;
10193 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
10194 if (ATy->getNumElements() == 1)
10195 SrcETy = ATy->getElementType();
10196 else
10197 break;
10198 } else
10199 break;
10200 }
10201
Dan Gohmanb8e94f62008-05-23 01:52:21 +000010202 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010203 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +000010204 }
10205 }
10206
10207
Chris Lattner00ae5132008-01-13 23:50:23 +000010208 // If the memcpy/memmove provides better alignment info than we can
10209 // infer, use it.
10210 SrcAlign = std::max(SrcAlign, CopyAlign);
10211 DstAlign = std::max(DstAlign, CopyAlign);
10212
Chris Lattner78628292009-08-30 19:47:22 +000010213 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
10214 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattnerc669fb62008-01-14 00:28:35 +000010215 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
10216 InsertNewInstBefore(L, *MI);
10217 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
10218
10219 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +000010220 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +000010221 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +000010222}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010223
Chris Lattner5af8a912008-04-30 06:39:11 +000010224Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
10225 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +000010226 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000010227 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +000010228 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +000010229 return MI;
10230 }
10231
10232 // Extract the length and alignment and fill if they are constant.
10233 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
10234 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson35b47072009-08-13 21:58:54 +000010235 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner5af8a912008-04-30 06:39:11 +000010236 return 0;
10237 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +000010238 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +000010239
10240 // If the length is zero, this is a no-op
10241 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
10242
10243 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
10244 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson35b47072009-08-13 21:58:54 +000010245 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +000010246
10247 Value *Dest = MI->getDest();
Chris Lattner78628292009-08-30 19:47:22 +000010248 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner5af8a912008-04-30 06:39:11 +000010249
10250 // Alignment 0 is identity for alignment 1 for memset, but not store.
10251 if (Alignment == 0) Alignment = 1;
10252
10253 // Extract the fill value and store.
10254 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +000010255 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +000010256 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +000010257
10258 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +000010259 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +000010260 return MI;
10261 }
10262
10263 return 0;
10264}
10265
10266
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010267/// visitCallInst - CallInst simplification. This mostly only handles folding
10268/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
10269/// the heavy lifting.
10270///
10271Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez93946082009-10-24 04:23:03 +000010272 if (isFreeCall(&CI))
10273 return visitFree(CI);
10274
Chris Lattneraa295aa2009-05-13 17:39:14 +000010275 // If the caller function is nounwind, mark the call as nounwind, even if the
10276 // callee isn't.
10277 if (CI.getParent()->getParent()->doesNotThrow() &&
10278 !CI.doesNotThrow()) {
10279 CI.setDoesNotThrow();
10280 return &CI;
10281 }
10282
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010283 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
10284 if (!II) return visitCallSite(&CI);
10285
10286 // Intrinsics cannot occur in an invoke, so handle them here instead of in
10287 // visitCallSite.
10288 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
10289 bool Changed = false;
10290
10291 // memmove/cpy/set of zero bytes is a noop.
10292 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
10293 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
10294
10295 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
10296 if (CI->getZExtValue() == 1) {
10297 // Replace the instruction with just byte operations. We would
10298 // transform other cases to loads/stores, but we don't know if
10299 // alignment is sufficient.
10300 }
10301 }
10302
10303 // If we have a memmove and the source operation is a constant global,
10304 // then the source and dest pointers can't alias, so we can change this
10305 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +000010306 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010307 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
10308 if (GVSrc->isConstant()) {
10309 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +000010310 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
10311 const Type *Tys[1];
10312 Tys[0] = CI.getOperand(3)->getType();
10313 CI.setOperand(0,
10314 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010315 Changed = true;
10316 }
Eli Friedman626e32a2009-12-17 21:07:31 +000010317 }
Chris Lattner59b27d92008-05-28 05:30:41 +000010318
Eli Friedman626e32a2009-12-17 21:07:31 +000010319 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattner59b27d92008-05-28 05:30:41 +000010320 // memmove(x,x,size) -> noop.
Eli Friedman626e32a2009-12-17 21:07:31 +000010321 if (MTI->getSource() == MTI->getDest())
Chris Lattner59b27d92008-05-28 05:30:41 +000010322 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010323 }
10324
10325 // If we can determine a pointer alignment that is bigger than currently
10326 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +000010327 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +000010328 if (Instruction *I = SimplifyMemTransfer(MI))
10329 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +000010330 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
10331 if (Instruction *I = SimplifyMemSet(MSI))
10332 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010333 }
10334
10335 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +000010336 }
10337
10338 switch (II->getIntrinsicID()) {
10339 default: break;
10340 case Intrinsic::bswap:
10341 // bswap(bswap(x)) -> x
10342 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
10343 if (Operand->getIntrinsicID() == Intrinsic::bswap)
10344 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattner723b9642010-01-01 18:34:40 +000010345
10346 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
10347 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
10348 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
10349 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
10350 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
10351 TI->getType()->getPrimitiveSizeInBits();
10352 Value *CV = ConstantInt::get(Operand->getType(), C);
10353 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
10354 return new TruncInst(V, TI->getType());
10355 }
10356 }
10357
Chris Lattner989ba312008-06-18 04:33:20 +000010358 break;
Chris Lattnerfd4f21a2010-01-01 01:52:15 +000010359 case Intrinsic::powi:
10360 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
10361 // powi(x, 0) -> 1.0
10362 if (Power->isZero())
10363 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
10364 // powi(x, 1) -> x
10365 if (Power->isOne())
10366 return ReplaceInstUsesWith(CI, II->getOperand(1));
10367 // powi(x, -1) -> 1/x
Chris Lattner60179fb2010-01-01 01:54:08 +000010368 if (Power->isAllOnesValue())
10369 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
10370 II->getOperand(1));
Chris Lattnerfd4f21a2010-01-01 01:52:15 +000010371 }
10372 break;
10373
Chris Lattner0b452262009-11-26 21:42:47 +000010374 case Intrinsic::uadd_with_overflow: {
10375 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10376 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10377 uint32_t BitWidth = IT->getBitWidth();
10378 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner65e34842009-11-26 22:08:06 +000010379 APInt LHSKnownZero(BitWidth, 0);
10380 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +000010381 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10382 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10383 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10384
10385 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner65e34842009-11-26 22:08:06 +000010386 APInt RHSKnownZero(BitWidth, 0);
10387 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +000010388 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10389 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10390 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10391 if (LHSKnownNegative && RHSKnownNegative) {
10392 // The sign bit is set in both cases: this MUST overflow.
10393 // Create a simple add instruction, and insert it into the struct.
10394 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10395 Worklist.Add(Add);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010396 Constant *V[] = {
10397 UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
10398 };
Chris Lattner0b452262009-11-26 21:42:47 +000010399 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10400 return InsertValueInst::Create(Struct, Add, 0);
10401 }
10402
10403 if (LHSKnownPositive && RHSKnownPositive) {
10404 // The sign bit is clear in both cases: this CANNOT overflow.
10405 // Create a simple add instruction, and insert it into the struct.
10406 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10407 Worklist.Add(Add);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010408 Constant *V[] = {
10409 UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
10410 };
Chris Lattner0b452262009-11-26 21:42:47 +000010411 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10412 return InsertValueInst::Create(Struct, Add, 0);
10413 }
10414 }
10415 }
10416 // FALL THROUGH uadd into sadd
10417 case Intrinsic::sadd_with_overflow:
10418 // Canonicalize constants into the RHS.
10419 if (isa<Constant>(II->getOperand(1)) &&
10420 !isa<Constant>(II->getOperand(2))) {
10421 Value *LHS = II->getOperand(1);
10422 II->setOperand(1, II->getOperand(2));
10423 II->setOperand(2, LHS);
10424 return II;
10425 }
10426
10427 // X + undef -> undef
10428 if (isa<UndefValue>(II->getOperand(2)))
10429 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10430
10431 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10432 // X + 0 -> {X, false}
10433 if (RHS->isZero()) {
10434 Constant *V[] = {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010435 UndefValue::get(II->getOperand(0)->getType()),
10436 ConstantInt::getFalse(*Context)
Chris Lattner0b452262009-11-26 21:42:47 +000010437 };
10438 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10439 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10440 }
10441 }
10442 break;
10443 case Intrinsic::usub_with_overflow:
10444 case Intrinsic::ssub_with_overflow:
10445 // undef - X -> undef
10446 // X - undef -> undef
10447 if (isa<UndefValue>(II->getOperand(1)) ||
10448 isa<UndefValue>(II->getOperand(2)))
10449 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10450
10451 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10452 // X - 0 -> {X, false}
10453 if (RHS->isZero()) {
10454 Constant *V[] = {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010455 UndefValue::get(II->getOperand(1)->getType()),
10456 ConstantInt::getFalse(*Context)
Chris Lattner0b452262009-11-26 21:42:47 +000010457 };
10458 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10459 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10460 }
10461 }
10462 break;
10463 case Intrinsic::umul_with_overflow:
10464 case Intrinsic::smul_with_overflow:
10465 // Canonicalize constants into the RHS.
10466 if (isa<Constant>(II->getOperand(1)) &&
10467 !isa<Constant>(II->getOperand(2))) {
10468 Value *LHS = II->getOperand(1);
10469 II->setOperand(1, II->getOperand(2));
10470 II->setOperand(2, LHS);
10471 return II;
10472 }
10473
10474 // X * undef -> undef
10475 if (isa<UndefValue>(II->getOperand(2)))
10476 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10477
10478 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10479 // X*0 -> {0, false}
10480 if (RHSI->isZero())
10481 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10482
10483 // X * 1 -> {X, false}
10484 if (RHSI->equalsInt(1)) {
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010485 Constant *V[] = {
10486 UndefValue::get(II->getOperand(1)->getType()),
10487 ConstantInt::getFalse(*Context)
10488 };
Chris Lattner0b452262009-11-26 21:42:47 +000010489 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
Chris Lattnerdbbf1b22009-11-29 02:57:29 +000010490 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner0b452262009-11-26 21:42:47 +000010491 }
10492 }
10493 break;
Chris Lattner989ba312008-06-18 04:33:20 +000010494 case Intrinsic::ppc_altivec_lvx:
10495 case Intrinsic::ppc_altivec_lvxl:
10496 case Intrinsic::x86_sse_loadu_ps:
10497 case Intrinsic::x86_sse2_loadu_pd:
10498 case Intrinsic::x86_sse2_loadu_dq:
10499 // Turn PPC lvx -> load if the pointer is known aligned.
10500 // Turn X86 loadups -> load if the pointer is known aligned.
10501 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner78628292009-08-30 19:47:22 +000010502 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10503 PointerType::getUnqual(II->getType()));
Chris Lattner989ba312008-06-18 04:33:20 +000010504 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010505 }
Chris Lattner989ba312008-06-18 04:33:20 +000010506 break;
10507 case Intrinsic::ppc_altivec_stvx:
10508 case Intrinsic::ppc_altivec_stvxl:
10509 // Turn stvx -> store if the pointer is known aligned.
10510 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10511 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010512 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner78628292009-08-30 19:47:22 +000010513 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +000010514 return new StoreInst(II->getOperand(1), Ptr);
10515 }
10516 break;
10517 case Intrinsic::x86_sse_storeu_ps:
10518 case Intrinsic::x86_sse2_storeu_pd:
10519 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +000010520 // Turn X86 storeu -> store if the pointer is known aligned.
10521 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10522 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010523 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner78628292009-08-30 19:47:22 +000010524 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +000010525 return new StoreInst(II->getOperand(2), Ptr);
10526 }
10527 break;
10528
10529 case Intrinsic::x86_sse_cvttss2si: {
10530 // These intrinsics only demands the 0th element of its input vector. If
10531 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +000010532 unsigned VWidth =
10533 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10534 APInt DemandedElts(VWidth, 1);
10535 APInt UndefElts(VWidth, 0);
10536 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +000010537 UndefElts)) {
10538 II->setOperand(1, V);
10539 return II;
10540 }
10541 break;
10542 }
10543
10544 case Intrinsic::ppc_altivec_vperm:
10545 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10546 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10547 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010548
Chris Lattner989ba312008-06-18 04:33:20 +000010549 // Check that all of the elements are integer constants or undefs.
10550 bool AllEltsOk = true;
10551 for (unsigned i = 0; i != 16; ++i) {
10552 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10553 !isa<UndefValue>(Mask->getOperand(i))) {
10554 AllEltsOk = false;
10555 break;
10556 }
10557 }
10558
10559 if (AllEltsOk) {
10560 // Cast the input vectors to byte vectors.
Chris Lattner78628292009-08-30 19:47:22 +000010561 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10562 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Andersonb99ecca2009-07-30 23:03:37 +000010563 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010564
Chris Lattner989ba312008-06-18 04:33:20 +000010565 // Only extract each element once.
10566 Value *ExtractedElts[32];
10567 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10568
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010569 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +000010570 if (isa<UndefValue>(Mask->getOperand(i)))
10571 continue;
10572 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10573 Idx &= 31; // Match the hardware behavior.
10574
10575 if (ExtractedElts[Idx] == 0) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010576 ExtractedElts[Idx] =
10577 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
10578 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10579 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010580 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010581
Chris Lattner989ba312008-06-18 04:33:20 +000010582 // Insert this value into the result vector.
Chris Lattnerad7516a2009-08-30 18:50:58 +000010583 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10584 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10585 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010586 }
Chris Lattner989ba312008-06-18 04:33:20 +000010587 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010588 }
Chris Lattner989ba312008-06-18 04:33:20 +000010589 }
10590 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010591
Chris Lattner989ba312008-06-18 04:33:20 +000010592 case Intrinsic::stackrestore: {
10593 // If the save is right next to the restore, remove the restore. This can
10594 // happen when variable allocas are DCE'd.
10595 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10596 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10597 BasicBlock::iterator BI = SS;
10598 if (&*++BI == II)
10599 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010600 }
Chris Lattner989ba312008-06-18 04:33:20 +000010601 }
10602
10603 // Scan down this block to see if there is another stack restore in the
10604 // same block without an intervening call/alloca.
10605 BasicBlock::iterator BI = II;
10606 TerminatorInst *TI = II->getParent()->getTerminator();
10607 bool CannotRemove = false;
10608 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez48c3c542009-09-18 22:35:49 +000010609 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner989ba312008-06-18 04:33:20 +000010610 CannotRemove = true;
10611 break;
10612 }
Chris Lattnera6b477c2008-06-25 05:59:28 +000010613 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10614 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10615 // If there is a stackrestore below this one, remove this one.
10616 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10617 return EraseInstFromFunction(CI);
10618 // Otherwise, ignore the intrinsic.
10619 } else {
10620 // If we found a non-intrinsic call, we can't remove the stack
10621 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +000010622 CannotRemove = true;
10623 break;
10624 }
Chris Lattner989ba312008-06-18 04:33:20 +000010625 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010626 }
Chris Lattner989ba312008-06-18 04:33:20 +000010627
10628 // If the stack restore is in a return/unwind block and if there are no
10629 // allocas or calls between the restore and the return, nuke the restore.
10630 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10631 return EraseInstFromFunction(CI);
10632 break;
10633 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010634 }
10635
10636 return visitCallSite(II);
10637}
10638
10639// InvokeInst simplification
10640//
10641Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10642 return visitCallSite(&II);
10643}
10644
Dale Johannesen96021832008-04-25 21:16:07 +000010645/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10646/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +000010647static bool isSafeToEliminateVarargsCast(const CallSite CS,
10648 const CastInst * const CI,
10649 const TargetData * const TD,
10650 const int ix) {
10651 if (!CI->isLosslessCast())
10652 return false;
10653
10654 // The size of ByVal arguments is derived from the type, so we
10655 // can't change to a type with a different size. If the size were
10656 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +000010657 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +000010658 return true;
10659
10660 const Type* SrcTy =
10661 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10662 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10663 if (!SrcTy->isSized() || !DstTy->isSized())
10664 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +000010665 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +000010666 return false;
10667 return true;
10668}
10669
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010670// visitCallSite - Improvements for call and invoke instructions.
10671//
10672Instruction *InstCombiner::visitCallSite(CallSite CS) {
10673 bool Changed = false;
10674
10675 // If the callee is a constexpr cast of a function, attempt to move the cast
10676 // to the arguments of the call/invoke.
10677 if (transformConstExprCastCall(CS)) return 0;
10678
10679 Value *Callee = CS.getCalledValue();
10680
10681 if (Function *CalleeF = dyn_cast<Function>(Callee))
10682 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10683 Instruction *OldCall = CS.getInstruction();
10684 // If the call and callee calling conventions don't match, this call must
10685 // be unreachable, as the call is undefined.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010686 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000010687 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Anderson24be4c12009-07-03 00:17:18 +000010688 OldCall);
Devang Patele3829c82009-10-13 22:56:32 +000010689 // If OldCall dues not return void then replaceAllUsesWith undef.
10690 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010691 if (!OldCall->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010692 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010693 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10694 return EraseInstFromFunction(*OldCall);
10695 return 0;
10696 }
10697
10698 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10699 // This instruction is not reachable, just remove it. We insert a store to
10700 // undef so that we know that this code is not reachable, despite the fact
10701 // that we can't modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010702 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000010703 UndefValue::get(Type::getInt1PtrTy(*Context)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010704 CS.getInstruction());
10705
Devang Patele3829c82009-10-13 22:56:32 +000010706 // If CS dues not return void then replaceAllUsesWith undef.
10707 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010708 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010709 CS.getInstruction()->
10710 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010711
10712 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10713 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010714 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson4f720fa2009-07-31 17:39:07 +000010715 ConstantInt::getTrue(*Context), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010716 }
10717 return EraseInstFromFunction(*CS.getInstruction());
10718 }
10719
Duncan Sands74833f22007-09-17 10:26:40 +000010720 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10721 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10722 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10723 return transformCallThroughTrampoline(CS);
10724
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010725 const PointerType *PTy = cast<PointerType>(Callee->getType());
10726 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10727 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +000010728 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010729 // See if we can optimize any arguments passed through the varargs area of
10730 // the call.
10731 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +000010732 E = CS.arg_end(); I != E; ++I, ++ix) {
10733 CastInst *CI = dyn_cast<CastInst>(*I);
10734 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10735 *I = CI->getOperand(0);
10736 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010737 }
Dale Johannesen35615462008-04-23 18:34:37 +000010738 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010739 }
10740
Duncan Sands2937e352007-12-19 21:13:37 +000010741 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010742 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010743 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010744 Changed = true;
10745 }
10746
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010747 return Changed ? CS.getInstruction() : 0;
10748}
10749
10750// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10751// attempt to move the cast to the arguments of the call/invoke.
10752//
10753bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10754 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10755 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10756 if (CE->getOpcode() != Instruction::BitCast ||
10757 !isa<Function>(CE->getOperand(0)))
10758 return false;
10759 Function *Callee = cast<Function>(CE->getOperand(0));
10760 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010761 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010762
10763 // Okay, this is a cast from a function to a different type. Unless doing so
10764 // would cause a type conversion of one of our arguments, change this call to
10765 // be a direct call with arguments casted to the appropriate types.
10766 //
10767 const FunctionType *FT = Callee->getFunctionType();
10768 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010769 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010770
Duncan Sands7901ce12008-06-01 07:38:42 +000010771 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010772 return false; // TODO: Handle multiple return values.
10773
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010774 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010775 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010776 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010777 // Conversion is ok if changing from one pointer type to another or from
10778 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +000010779 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010780 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000010781 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010782 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010783 return false; // Cannot transform this return value.
10784
Duncan Sands5c489582008-01-06 10:12:28 +000010785 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010786 // void -> non-void is handled specially
Devang Patele9d08b82009-10-14 17:29:00 +000010787 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010788 return false; // Cannot transform this return value.
10789
Chris Lattner1c8733e2008-03-12 17:45:29 +000010790 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010791 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010792 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010793 return false; // Attribute not compatible with transformed value.
10794 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010795
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010796 // If the callsite is an invoke instruction, and the return value is used by
10797 // a PHI node in a successor, we cannot change the return type of the call
10798 // because there is no place to put the cast instruction (without breaking
10799 // the critical edge). Bail out in this case.
10800 if (!Caller->use_empty())
10801 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10802 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10803 UI != E; ++UI)
10804 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10805 if (PN->getParent() == II->getNormalDest() ||
10806 PN->getParent() == II->getUnwindDest())
10807 return false;
10808 }
10809
10810 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10811 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10812
10813 CallSite::arg_iterator AI = CS.arg_begin();
10814 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10815 const Type *ParamTy = FT->getParamType(i);
10816 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010817
10818 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010819 return false; // Cannot transform this parameter value.
10820
Devang Patelf2a4a922008-09-26 22:53:05 +000010821 if (CallerPAL.getParamAttributes(i + 1)
10822 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010823 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010824
Duncan Sands7901ce12008-06-01 07:38:42 +000010825 // Converting from one pointer type to another or between a pointer and an
10826 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010827 bool isConvertible = ActTy == ParamTy ||
Owen Anderson35b47072009-08-13 21:58:54 +000010828 (TD && ((isa<PointerType>(ParamTy) ||
10829 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10830 (isa<PointerType>(ActTy) ||
10831 ActTy == TD->getIntPtrType(Caller->getContext()))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010832 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010833 }
10834
10835 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10836 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010837 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010838
Chris Lattner1c8733e2008-03-12 17:45:29 +000010839 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10840 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010841 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010842 // won't be dropping them. Check that these extra arguments have attributes
10843 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010844 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10845 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010846 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010847 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010848 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010849 return false;
10850 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010851
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010852 // Okay, we decided that this is a safe thing to do: go ahead and start
10853 // inserting cast instructions as necessary...
10854 std::vector<Value*> Args;
10855 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010856 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010857 attrVec.reserve(NumCommonArgs);
10858
10859 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010860 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010861
10862 // If the return value is not being used, the type may not be compatible
10863 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010864 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010865
10866 // Add the new return attributes.
10867 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010868 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010869
10870 AI = CS.arg_begin();
10871 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10872 const Type *ParamTy = FT->getParamType(i);
10873 if ((*AI)->getType() == ParamTy) {
10874 Args.push_back(*AI);
10875 } else {
10876 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10877 false, ParamTy, false);
Chris Lattnerad7516a2009-08-30 18:50:58 +000010878 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010879 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010880
10881 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010882 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010883 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010884 }
10885
10886 // If the function takes more arguments than the call was taking, add them
Chris Lattnerad7516a2009-08-30 18:50:58 +000010887 // now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010888 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +000010889 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010890
Chris Lattnerad7516a2009-08-30 18:50:58 +000010891 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010892 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010893 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +000010894 errs() << "WARNING: While resolving call to function '"
10895 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010896 } else {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010897 // Add all of the arguments in their promoted form to the arg list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010898 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10899 const Type *PTy = getPromotedType((*AI)->getType());
10900 if (PTy != (*AI)->getType()) {
10901 // Must promote to pass through va_arg area!
Chris Lattnerad7516a2009-08-30 18:50:58 +000010902 Instruction::CastOps opcode =
10903 CastInst::getCastOpcode(*AI, false, PTy, false);
10904 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010905 } else {
10906 Args.push_back(*AI);
10907 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010908
Duncan Sands4ced1f82008-01-13 08:02:44 +000010909 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010910 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010911 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010912 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010913 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010914 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010915
Devang Patelf2a4a922008-09-26 22:53:05 +000010916 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10917 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10918
Devang Patele9d08b82009-10-14 17:29:00 +000010919 if (NewRetTy->isVoidTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010920 Caller->setName(""); // Void type should not have a name.
10921
Eric Christopher3e7381f2009-07-25 02:45:27 +000010922 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10923 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010924
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010925 Instruction *NC;
10926 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010927 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010928 Args.begin(), Args.end(),
10929 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010930 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010931 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010932 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010933 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10934 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010935 CallInst *CI = cast<CallInst>(Caller);
10936 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010937 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010938 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010939 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010940 }
10941
10942 // Insert a cast of the return type as necessary.
10943 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010944 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patele9d08b82009-10-14 17:29:00 +000010945 if (!NV->getType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010946 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010947 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010948 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010949
10950 // If this is an invoke instruction, we should insert it after the first
10951 // non-phi, instruction in the normal successor block.
10952 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010953 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010954 InsertNewInstBefore(NC, *I);
10955 } else {
10956 // Otherwise, it's a call, just insert cast right after the call instr
10957 InsertNewInstBefore(NC, *Caller);
10958 }
Chris Lattner4796b622009-08-30 06:22:51 +000010959 Worklist.AddUsersToWorkList(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010960 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010961 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010962 }
10963 }
10964
Devang Pateledad36f2009-10-13 21:41:20 +000010965
Chris Lattner26b7f942009-08-31 05:17:58 +000010966 if (!Caller->use_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010967 Caller->replaceAllUsesWith(NV);
Chris Lattner26b7f942009-08-31 05:17:58 +000010968
10969 EraseInstFromFunction(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010970 return true;
10971}
10972
Duncan Sands74833f22007-09-17 10:26:40 +000010973// transformCallThroughTrampoline - Turn a call to a function created by the
10974// init_trampoline intrinsic into a direct call to the underlying function.
10975//
10976Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10977 Value *Callee = CS.getCalledValue();
10978 const PointerType *PTy = cast<PointerType>(Callee->getType());
10979 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010980 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010981
10982 // If the call already has the 'nest' attribute somewhere then give up -
10983 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010984 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010985 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010986
10987 IntrinsicInst *Tramp =
10988 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10989
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010990 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010991 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10992 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10993
Devang Pateld222f862008-09-25 21:00:45 +000010994 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010995 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010996 unsigned NestIdx = 1;
10997 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010998 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010999
11000 // Look for a parameter marked with the 'nest' attribute.
11001 for (FunctionType::param_iterator I = NestFTy->param_begin(),
11002 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000011003 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000011004 // Record the parameter type and any other attributes.
11005 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000011006 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000011007 break;
11008 }
11009
11010 if (NestTy) {
11011 Instruction *Caller = CS.getInstruction();
11012 std::vector<Value*> NewArgs;
11013 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
11014
Devang Pateld222f862008-09-25 21:00:45 +000011015 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000011016 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000011017
Duncan Sands74833f22007-09-17 10:26:40 +000011018 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000011019 // mean appending it. Likewise for attributes.
11020
Devang Patelf2a4a922008-09-26 22:53:05 +000011021 // Add any result attributes.
11022 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000011023 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000011024
Duncan Sands74833f22007-09-17 10:26:40 +000011025 {
11026 unsigned Idx = 1;
11027 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
11028 do {
11029 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000011030 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000011031 Value *NestVal = Tramp->getOperand(3);
11032 if (NestVal->getType() != NestTy)
11033 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
11034 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000011035 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000011036 }
11037
11038 if (I == E)
11039 break;
11040
Duncan Sands48b81112008-01-14 19:52:09 +000011041 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000011042 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000011043 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000011044 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000011045 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000011046
11047 ++Idx, ++I;
11048 } while (1);
11049 }
11050
Devang Patelf2a4a922008-09-26 22:53:05 +000011051 // Add any function attributes.
11052 if (Attributes Attr = Attrs.getFnAttributes())
11053 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
11054
Duncan Sands74833f22007-09-17 10:26:40 +000011055 // The trampoline may have been bitcast to a bogus type (FTy).
11056 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000011057 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000011058
Duncan Sands74833f22007-09-17 10:26:40 +000011059 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000011060 NewTypes.reserve(FTy->getNumParams()+1);
11061
Duncan Sands74833f22007-09-17 10:26:40 +000011062 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000011063 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000011064 {
11065 unsigned Idx = 1;
11066 FunctionType::param_iterator I = FTy->param_begin(),
11067 E = FTy->param_end();
11068
11069 do {
Duncan Sands48b81112008-01-14 19:52:09 +000011070 if (Idx == NestIdx)
11071 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000011072 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000011073
11074 if (I == E)
11075 break;
11076
Duncan Sands48b81112008-01-14 19:52:09 +000011077 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000011078 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000011079
11080 ++Idx, ++I;
11081 } while (1);
11082 }
11083
11084 // Replace the trampoline call with a direct call. Let the generic
11085 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011086 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +000011087 FTy->isVarArg());
11088 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011089 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +000011090 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011091 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +000011092 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
11093 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000011094
11095 Instruction *NewCaller;
11096 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000011097 NewCaller = InvokeInst::Create(NewCallee,
11098 II->getNormalDest(), II->getUnwindDest(),
11099 NewArgs.begin(), NewArgs.end(),
11100 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000011101 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000011102 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000011103 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000011104 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
11105 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000011106 if (cast<CallInst>(Caller)->isTailCall())
11107 cast<CallInst>(NewCaller)->setTailCall();
11108 cast<CallInst>(NewCaller)->
11109 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000011110 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000011111 }
Devang Patele9d08b82009-10-14 17:29:00 +000011112 if (!Caller->getType()->isVoidTy())
Duncan Sands74833f22007-09-17 10:26:40 +000011113 Caller->replaceAllUsesWith(NewCaller);
11114 Caller->eraseFromParent();
Chris Lattner3183fb62009-08-30 06:13:40 +000011115 Worklist.Remove(Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000011116 return 0;
11117 }
11118 }
11119
11120 // Replace the trampoline call with a direct call. Since there is no 'nest'
11121 // parameter, there is no need to adjust the argument list. Let the generic
11122 // code sort out any function type mismatches.
11123 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000011124 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +000011125 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000011126 CS.setCalledFunction(NewCallee);
11127 return CS.getInstruction();
11128}
11129
Dan Gohman09cf2b62009-09-16 16:50:24 +000011130/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
11131/// and if a/b/c and the add's all have a single use, turn this into a phi
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011132/// and a single binop.
11133Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
11134 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000011135 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011136 unsigned Opc = FirstInst->getOpcode();
11137 Value *LHSVal = FirstInst->getOperand(0);
11138 Value *RHSVal = FirstInst->getOperand(1);
11139
11140 const Type *LHSType = LHSVal->getType();
11141 const Type *RHSType = RHSVal->getType();
11142
Dan Gohman09cf2b62009-09-16 16:50:24 +000011143 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000011144 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011145 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11146 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
11147 // Verify type of the LHS matches so we don't fold cmp's of different
11148 // types or GEP's with different index types.
11149 I->getOperand(0)->getType() != LHSType ||
11150 I->getOperand(1)->getType() != RHSType)
11151 return 0;
11152
11153 // If they are CmpInst instructions, check their predicates
11154 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
11155 if (cast<CmpInst>(I)->getPredicate() !=
11156 cast<CmpInst>(FirstInst)->getPredicate())
11157 return 0;
11158
11159 // Keep track of which operand needs a phi node.
11160 if (I->getOperand(0) != LHSVal) LHSVal = 0;
11161 if (I->getOperand(1) != RHSVal) RHSVal = 0;
11162 }
Dan Gohman09cf2b62009-09-16 16:50:24 +000011163
11164 // If both LHS and RHS would need a PHI, don't do this transformation,
11165 // because it would increase the number of PHIs entering the block,
11166 // which leads to higher register pressure. This is especially
11167 // bad when the PHIs are in the header of a loop.
11168 if (!LHSVal && !RHSVal)
11169 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011170
Chris Lattner30078012008-12-01 03:42:51 +000011171 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011172
11173 Value *InLHS = FirstInst->getOperand(0);
11174 Value *InRHS = FirstInst->getOperand(1);
11175 PHINode *NewLHS = 0, *NewRHS = 0;
11176 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000011177 NewLHS = PHINode::Create(LHSType,
11178 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011179 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
11180 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
11181 InsertNewInstBefore(NewLHS, PN);
11182 LHSVal = NewLHS;
11183 }
11184
11185 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000011186 NewRHS = PHINode::Create(RHSType,
11187 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011188 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
11189 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
11190 InsertNewInstBefore(NewRHS, PN);
11191 RHSVal = NewRHS;
11192 }
11193
11194 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000011195 if (NewLHS || NewRHS) {
11196 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11197 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
11198 if (NewLHS) {
11199 Value *NewInLHS = InInst->getOperand(0);
11200 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
11201 }
11202 if (NewRHS) {
11203 Value *NewInRHS = InInst->getOperand(1);
11204 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
11205 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011206 }
11207 }
11208
11209 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000011210 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000011211 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohmane6803b82009-08-25 23:17:54 +000011212 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson6601fcd2009-07-09 23:48:35 +000011213 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011214}
11215
Chris Lattner9e1916e2008-12-01 02:34:36 +000011216Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
11217 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
11218
11219 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
11220 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000011221 // This is true if all GEP bases are allocas and if all indices into them are
11222 // constants.
11223 bool AllBasePointersAreAllocas = true;
Dan Gohman37a534b2009-09-16 02:01:52 +000011224
11225 // We don't want to replace this phi if the replacement would require
Dan Gohman09cf2b62009-09-16 16:50:24 +000011226 // more than one phi, which leads to higher register pressure. This is
11227 // especially bad when the PHIs are in the header of a loop.
Dan Gohman37a534b2009-09-16 02:01:52 +000011228 bool NeededPhi = false;
Chris Lattner9e1916e2008-12-01 02:34:36 +000011229
Dan Gohman09cf2b62009-09-16 16:50:24 +000011230 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000011231 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
11232 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
11233 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
11234 GEP->getNumOperands() != FirstInst->getNumOperands())
11235 return 0;
11236
Chris Lattneradf354b2009-02-21 00:46:50 +000011237 // Keep track of whether or not all GEPs are of alloca pointers.
11238 if (AllBasePointersAreAllocas &&
11239 (!isa<AllocaInst>(GEP->getOperand(0)) ||
11240 !GEP->hasAllConstantIndices()))
11241 AllBasePointersAreAllocas = false;
11242
Chris Lattner9e1916e2008-12-01 02:34:36 +000011243 // Compare the operand lists.
11244 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
11245 if (FirstInst->getOperand(op) == GEP->getOperand(op))
11246 continue;
11247
11248 // Don't merge two GEPs when two operands differ (introducing phi nodes)
11249 // if one of the PHIs has a constant for the index. The index may be
11250 // substantially cheaper to compute for the constants, so making it a
11251 // variable index could pessimize the path. This also handles the case
11252 // for struct indices, which must always be constant.
11253 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
11254 isa<ConstantInt>(GEP->getOperand(op)))
11255 return 0;
11256
11257 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
11258 return 0;
Dan Gohman37a534b2009-09-16 02:01:52 +000011259
11260 // If we already needed a PHI for an earlier operand, and another operand
11261 // also requires a PHI, we'd be introducing more PHIs than we're
11262 // eliminating, which increases register pressure on entry to the PHI's
11263 // block.
11264 if (NeededPhi)
11265 return 0;
11266
Chris Lattner9e1916e2008-12-01 02:34:36 +000011267 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohman37a534b2009-09-16 02:01:52 +000011268 NeededPhi = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000011269 }
11270 }
11271
Chris Lattneradf354b2009-02-21 00:46:50 +000011272 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000011273 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000011274 // offset calculation, but all the predecessors will have to materialize the
11275 // stack address into a register anyway. We'd actually rather *clone* the
11276 // load up into the predecessors so that we have a load of a gep of an alloca,
11277 // which can usually all be folded into the load.
11278 if (AllBasePointersAreAllocas)
11279 return 0;
11280
Chris Lattner9e1916e2008-12-01 02:34:36 +000011281 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
11282 // that is variable.
11283 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
11284
11285 bool HasAnyPHIs = false;
11286 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
11287 if (FixedOperands[i]) continue; // operand doesn't need a phi.
11288 Value *FirstOp = FirstInst->getOperand(i);
11289 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
11290 FirstOp->getName()+".pn");
11291 InsertNewInstBefore(NewPN, PN);
11292
11293 NewPN->reserveOperandSpace(e);
11294 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
11295 OperandPhis[i] = NewPN;
11296 FixedOperands[i] = NewPN;
11297 HasAnyPHIs = true;
11298 }
11299
11300
11301 // Add all operands to the new PHIs.
11302 if (HasAnyPHIs) {
11303 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11304 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
11305 BasicBlock *InBB = PN.getIncomingBlock(i);
11306
11307 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
11308 if (PHINode *OpPhi = OperandPhis[op])
11309 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
11310 }
11311 }
11312
11313 Value *Base = FixedOperands[0];
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011314 return cast<GEPOperator>(FirstInst)->isInBounds() ?
11315 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
11316 FixedOperands.end()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000011317 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
11318 FixedOperands.end());
Chris Lattner9e1916e2008-12-01 02:34:36 +000011319}
11320
11321
Chris Lattnerf1e30c82009-02-23 05:56:17 +000011322/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
11323/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000011324/// obvious the value of the load is not changed from the point of the load to
11325/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011326///
11327/// Finally, it is safe, but not profitable, to sink a load targetting a
11328/// non-address-taken alloca. Doing so will cause us to not promote the alloca
11329/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000011330static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011331 BasicBlock::iterator BBI = L, E = L->getParent()->end();
11332
11333 for (++BBI; BBI != E; ++BBI)
11334 if (BBI->mayWriteToMemory())
11335 return false;
11336
11337 // Check for non-address taken alloca. If not address-taken already, it isn't
11338 // profitable to do this xform.
11339 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
11340 bool isAddressTaken = false;
11341 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
11342 UI != E; ++UI) {
11343 if (isa<LoadInst>(UI)) continue;
11344 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
11345 // If storing TO the alloca, then the address isn't taken.
11346 if (SI->getOperand(1) == AI) continue;
11347 }
11348 isAddressTaken = true;
11349 break;
11350 }
11351
Chris Lattneradf354b2009-02-21 00:46:50 +000011352 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011353 return false;
11354 }
11355
Chris Lattneradf354b2009-02-21 00:46:50 +000011356 // If this load is a load from a GEP with a constant offset from an alloca,
11357 // then we don't want to sink it. In its present form, it will be
11358 // load [constant stack offset]. Sinking it will cause us to have to
11359 // materialize the stack addresses in each predecessor in a register only to
11360 // do a shared load from register in the successor.
11361 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
11362 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
11363 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
11364 return false;
11365
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011366 return true;
11367}
11368
Chris Lattner38751f82009-11-01 20:04:24 +000011369Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
11370 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
11371
11372 // When processing loads, we need to propagate two bits of information to the
11373 // sunk load: whether it is volatile, and what its alignment is. We currently
11374 // don't sink loads when some have their alignment specified and some don't.
11375 // visitLoadInst will propagate an alignment onto the load when TD is around,
11376 // and if TD isn't around, we can't handle the mixed case.
11377 bool isVolatile = FirstLI->isVolatile();
11378 unsigned LoadAlignment = FirstLI->getAlignment();
11379
11380 // We can't sink the load if the loaded value could be modified between the
11381 // load and the PHI.
11382 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11383 !isSafeAndProfitableToSinkLoad(FirstLI))
11384 return 0;
11385
11386 // If the PHI is of volatile loads and the load block has multiple
11387 // successors, sinking it would remove a load of the volatile value from
11388 // the path through the other successor.
11389 if (isVolatile &&
11390 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11391 return 0;
11392
11393 // Check to see if all arguments are the same operation.
11394 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11395 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11396 if (!LI || !LI->hasOneUse())
11397 return 0;
11398
11399 // We can't sink the load if the loaded value could be modified between
11400 // the load and the PHI.
11401 if (LI->isVolatile() != isVolatile ||
11402 LI->getParent() != PN.getIncomingBlock(i) ||
11403 !isSafeAndProfitableToSinkLoad(LI))
11404 return 0;
11405
11406 // If some of the loads have an alignment specified but not all of them,
11407 // we can't do the transformation.
11408 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11409 return 0;
11410
Chris Lattner52fe1bc2009-11-01 20:07:07 +000011411 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner38751f82009-11-01 20:04:24 +000011412
11413 // If the PHI is of volatile loads and the load block has multiple
11414 // successors, sinking it would remove a load of the volatile value from
11415 // the path through the other successor.
11416 if (isVolatile &&
11417 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11418 return 0;
11419 }
11420
11421 // Okay, they are all the same operation. Create a new PHI node of the
11422 // correct type, and PHI together all of the LHS's of the instructions.
11423 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11424 PN.getName()+".in");
11425 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11426
11427 Value *InVal = FirstLI->getOperand(0);
11428 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11429
11430 // Add all operands to the new PHI.
11431 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11432 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11433 if (NewInVal != InVal)
11434 InVal = 0;
11435 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11436 }
11437
11438 Value *PhiVal;
11439 if (InVal) {
11440 // The new PHI unions all of the same values together. This is really
11441 // common, so we handle it intelligently here for compile-time speed.
11442 PhiVal = InVal;
11443 delete NewPN;
11444 } else {
11445 InsertNewInstBefore(NewPN, PN);
11446 PhiVal = NewPN;
11447 }
11448
11449 // If this was a volatile load that we are merging, make sure to loop through
11450 // and mark all the input loads as non-volatile. If we don't do this, we will
11451 // insert a new volatile load and the old ones will not be deletable.
11452 if (isVolatile)
11453 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11454 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11455
11456 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11457}
11458
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011459
Chris Lattnerd0011092009-11-10 07:23:37 +000011460
11461/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11462/// operator and they all are only used by the PHI, PHI together their
11463/// inputs, and do the operation once, to the result of the PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011464Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11465 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11466
Chris Lattner38751f82009-11-01 20:04:24 +000011467 if (isa<GetElementPtrInst>(FirstInst))
11468 return FoldPHIArgGEPIntoPHI(PN);
11469 if (isa<LoadInst>(FirstInst))
11470 return FoldPHIArgLoadIntoPHI(PN);
11471
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011472 // Scan the instruction, looking for input operations that can be folded away.
11473 // If all input operands to the phi are the same instruction (e.g. a cast from
11474 // the same type or "+42") we can pull the operation through the PHI, reducing
11475 // code size and simplifying code.
11476 Constant *ConstantOp = 0;
11477 const Type *CastSrcTy = 0;
Chris Lattner310a00f2009-11-01 19:50:13 +000011478
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011479 if (isa<CastInst>(FirstInst)) {
11480 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattner4ca73902009-11-08 21:20:06 +000011481
11482 // Be careful about transforming integer PHIs. We don't want to pessimize
11483 // the code by turning an i32 into an i1293.
11484 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerd0011092009-11-10 07:23:37 +000011485 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattner4ca73902009-11-08 21:20:06 +000011486 return 0;
11487 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011488 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
11489 // Can fold binop, compare or shift here if the RHS is a constant,
11490 // otherwise call FoldPHIArgBinOpIntoPHI.
11491 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
11492 if (ConstantOp == 0)
11493 return FoldPHIArgBinOpIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011494 } else {
11495 return 0; // Cannot fold this operation.
11496 }
11497
11498 // Check to see if all arguments are the same operation.
11499 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner38751f82009-11-01 20:04:24 +000011500 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11501 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011502 return 0;
11503 if (CastSrcTy) {
11504 if (I->getOperand(0)->getType() != CastSrcTy)
11505 return 0; // Cast operation must match.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011506 } else if (I->getOperand(1) != ConstantOp) {
11507 return 0;
11508 }
11509 }
11510
11511 // Okay, they are all the same operation. Create a new PHI node of the
11512 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000011513 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11514 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011515 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11516
11517 Value *InVal = FirstInst->getOperand(0);
11518 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11519
11520 // Add all operands to the new PHI.
11521 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11522 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11523 if (NewInVal != InVal)
11524 InVal = 0;
11525 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11526 }
11527
11528 Value *PhiVal;
11529 if (InVal) {
11530 // The new PHI unions all of the same values together. This is really
11531 // common, so we handle it intelligently here for compile-time speed.
11532 PhiVal = InVal;
11533 delete NewPN;
11534 } else {
11535 InsertNewInstBefore(NewPN, PN);
11536 PhiVal = NewPN;
11537 }
11538
11539 // Insert and return the new operation.
Chris Lattner310a00f2009-11-01 19:50:13 +000011540 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000011541 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner310a00f2009-11-01 19:50:13 +000011542
Chris Lattnerfc984e92008-04-29 17:13:43 +000011543 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000011544 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner310a00f2009-11-01 19:50:13 +000011545
Chris Lattner38751f82009-11-01 20:04:24 +000011546 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11547 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11548 PhiVal, ConstantOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011549}
11550
11551/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11552/// that is dead.
11553static bool DeadPHICycle(PHINode *PN,
11554 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
11555 if (PN->use_empty()) return true;
11556 if (!PN->hasOneUse()) return false;
11557
11558 // Remember this node, and if we find the cycle, return.
11559 if (!PotentiallyDeadPHIs.insert(PN))
11560 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000011561
11562 // Don't scan crazily complex things.
11563 if (PotentiallyDeadPHIs.size() == 16)
11564 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011565
11566 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11567 return DeadPHICycle(PU, PotentiallyDeadPHIs);
11568
11569 return false;
11570}
11571
Chris Lattner27b695d2007-11-06 21:52:06 +000011572/// PHIsEqualValue - Return true if this phi node is always equal to
11573/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11574/// z = some value; x = phi (y, z); y = phi (x, z)
11575static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11576 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11577 // See if we already saw this PHI node.
11578 if (!ValueEqualPHIs.insert(PN))
11579 return true;
11580
11581 // Don't scan crazily complex things.
11582 if (ValueEqualPHIs.size() == 16)
11583 return false;
11584
11585 // Scan the operands to see if they are either phi nodes or are equal to
11586 // the value.
11587 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11588 Value *Op = PN->getIncomingValue(i);
11589 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11590 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11591 return false;
11592 } else if (Op != NonPhiInVal)
11593 return false;
11594 }
11595
11596 return true;
11597}
11598
11599
Chris Lattner1cd526b2009-11-08 19:23:30 +000011600namespace {
11601struct PHIUsageRecord {
Chris Lattner073c12c2009-11-09 01:38:00 +000011602 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner1cd526b2009-11-08 19:23:30 +000011603 unsigned Shift; // The amount shifted.
11604 Instruction *Inst; // The trunc instruction.
11605
Chris Lattner073c12c2009-11-09 01:38:00 +000011606 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11607 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner1cd526b2009-11-08 19:23:30 +000011608
11609 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattner073c12c2009-11-09 01:38:00 +000011610 if (PHIId < RHS.PHIId) return true;
11611 if (PHIId > RHS.PHIId) return false;
Chris Lattner1cd526b2009-11-08 19:23:30 +000011612 if (Shift < RHS.Shift) return true;
Chris Lattner073c12c2009-11-09 01:38:00 +000011613 if (Shift > RHS.Shift) return false;
11614 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner1cd526b2009-11-08 19:23:30 +000011615 RHS.Inst->getType()->getPrimitiveSizeInBits();
11616 }
11617};
Chris Lattner073c12c2009-11-09 01:38:00 +000011618
11619struct LoweredPHIRecord {
11620 PHINode *PN; // The PHI that was lowered.
11621 unsigned Shift; // The amount shifted.
11622 unsigned Width; // The width extracted.
11623
11624 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11625 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11626
11627 // Ctor form used by DenseMap.
11628 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11629 : PN(pn), Shift(Sh), Width(0) {}
11630};
11631}
11632
11633namespace llvm {
11634 template<>
11635 struct DenseMapInfo<LoweredPHIRecord> {
11636 static inline LoweredPHIRecord getEmptyKey() {
11637 return LoweredPHIRecord(0, 0);
11638 }
11639 static inline LoweredPHIRecord getTombstoneKey() {
11640 return LoweredPHIRecord(0, 1);
11641 }
11642 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11643 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11644 (Val.Width>>3);
11645 }
11646 static bool isEqual(const LoweredPHIRecord &LHS,
11647 const LoweredPHIRecord &RHS) {
11648 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11649 LHS.Width == RHS.Width;
11650 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011651 };
Chris Lattner169f3a22009-12-15 07:26:43 +000011652 template <>
11653 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner1cd526b2009-11-08 19:23:30 +000011654}
11655
11656
11657/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11658/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11659/// so, we split the PHI into the various pieces being extracted. This sort of
11660/// thing is introduced when SROA promotes an aggregate to large integer values.
11661///
11662/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11663/// inttoptr. We should produce new PHIs in the right type.
11664///
Chris Lattner073c12c2009-11-09 01:38:00 +000011665Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11666 // PHIUsers - Keep track of all of the truncated values extracted from a set
11667 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner1cd526b2009-11-08 19:23:30 +000011668 SmallVector<PHIUsageRecord, 16> PHIUsers;
11669
Chris Lattner073c12c2009-11-09 01:38:00 +000011670 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11671 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11672 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11673 // check the uses of (to ensure they are all extracts).
11674 SmallVector<PHINode*, 8> PHIsToSlice;
11675 SmallPtrSet<PHINode*, 8> PHIsInspected;
11676
11677 PHIsToSlice.push_back(&FirstPhi);
11678 PHIsInspected.insert(&FirstPhi);
11679
11680 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11681 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner1cd526b2009-11-08 19:23:30 +000011682
Chris Lattner4a01aaa2009-12-19 07:01:15 +000011683 // Scan the input list of the PHI. If any input is an invoke, and if the
11684 // input is defined in the predecessor, then we won't be split the critical
11685 // edge which is required to insert a truncate. Because of this, we have to
11686 // bail out.
11687 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11688 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11689 if (II == 0) continue;
11690 if (II->getParent() != PN->getIncomingBlock(i))
11691 continue;
11692
11693 // If we have a phi, and if it's directly in the predecessor, then we have
11694 // a critical edge where we need to put the truncate. Since we can't
11695 // split the edge in instcombine, we have to bail out.
11696 return 0;
11697 }
11698
11699
Chris Lattner073c12c2009-11-09 01:38:00 +000011700 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11701 UI != E; ++UI) {
11702 Instruction *User = cast<Instruction>(*UI);
11703
11704 // If the user is a PHI, inspect its uses recursively.
11705 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11706 if (PHIsInspected.insert(UserPN))
11707 PHIsToSlice.push_back(UserPN);
11708 continue;
11709 }
11710
11711 // Truncates are always ok.
11712 if (isa<TruncInst>(User)) {
11713 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11714 continue;
11715 }
11716
11717 // Otherwise it must be a lshr which can only be used by one trunc.
11718 if (User->getOpcode() != Instruction::LShr ||
11719 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11720 !isa<ConstantInt>(User->getOperand(1)))
11721 return 0;
11722
11723 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11724 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner1cd526b2009-11-08 19:23:30 +000011725 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011726 }
11727
11728 // If we have no users, they must be all self uses, just nuke the PHI.
11729 if (PHIUsers.empty())
Chris Lattner073c12c2009-11-09 01:38:00 +000011730 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner1cd526b2009-11-08 19:23:30 +000011731
11732 // If this phi node is transformable, create new PHIs for all the pieces
11733 // extracted out of it. First, sort the users by their offset and size.
11734 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11735
Chris Lattner073c12c2009-11-09 01:38:00 +000011736 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11737 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11738 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11739 );
Chris Lattner1cd526b2009-11-08 19:23:30 +000011740
Chris Lattner073c12c2009-11-09 01:38:00 +000011741 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11742 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner1cd526b2009-11-08 19:23:30 +000011743 DenseMap<BasicBlock*, Value*> PredValues;
11744
Chris Lattner073c12c2009-11-09 01:38:00 +000011745 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11746 // introduce redundant PHIs.
11747 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11748
11749 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11750 unsigned PHIId = PHIUsers[UserI].PHIId;
11751 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner1cd526b2009-11-08 19:23:30 +000011752 unsigned Offset = PHIUsers[UserI].Shift;
11753 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner1cd526b2009-11-08 19:23:30 +000011754
Chris Lattner073c12c2009-11-09 01:38:00 +000011755 PHINode *EltPHI;
11756
11757 // If we've already lowered a user like this, reuse the previously lowered
11758 // value.
11759 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner1cd526b2009-11-08 19:23:30 +000011760
Chris Lattner073c12c2009-11-09 01:38:00 +000011761 // Otherwise, Create the new PHI node for this user.
11762 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11763 assert(EltPHI->getType() != PN->getType() &&
11764 "Truncate didn't shrink phi?");
11765
11766 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11767 BasicBlock *Pred = PN->getIncomingBlock(i);
11768 Value *&PredVal = PredValues[Pred];
11769
11770 // If we already have a value for this predecessor, reuse it.
11771 if (PredVal) {
11772 EltPHI->addIncoming(PredVal, Pred);
11773 continue;
11774 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011775
Chris Lattner073c12c2009-11-09 01:38:00 +000011776 // Handle the PHI self-reuse case.
11777 Value *InVal = PN->getIncomingValue(i);
11778 if (InVal == PN) {
11779 PredVal = EltPHI;
11780 EltPHI->addIncoming(PredVal, Pred);
11781 continue;
Chris Lattner4a01aaa2009-12-19 07:01:15 +000011782 }
11783
11784 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattner073c12c2009-11-09 01:38:00 +000011785 // If the incoming value was a PHI, and if it was one of the PHIs we
11786 // already rewrote it, just use the lowered value.
11787 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11788 PredVal = Res;
11789 EltPHI->addIncoming(PredVal, Pred);
11790 continue;
11791 }
11792 }
11793
11794 // Otherwise, do an extract in the predecessor.
11795 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11796 Value *Res = InVal;
11797 if (Offset)
11798 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11799 Offset), "extract");
11800 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11801 PredVal = Res;
11802 EltPHI->addIncoming(Res, Pred);
11803
11804 // If the incoming value was a PHI, and if it was one of the PHIs we are
11805 // rewriting, we will ultimately delete the code we inserted. This
11806 // means we need to revisit that PHI to make sure we extract out the
11807 // needed piece.
11808 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11809 if (PHIsInspected.count(OldInVal)) {
11810 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11811 OldInVal)-PHIsToSlice.begin();
11812 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11813 cast<Instruction>(Res)));
11814 ++UserE;
11815 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011816 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011817 PredValues.clear();
Chris Lattner1cd526b2009-11-08 19:23:30 +000011818
Chris Lattner073c12c2009-11-09 01:38:00 +000011819 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11820 << *EltPHI << '\n');
11821 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner1cd526b2009-11-08 19:23:30 +000011822 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011823
Chris Lattner073c12c2009-11-09 01:38:00 +000011824 // Replace the use of this piece with the PHI node.
11825 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner1cd526b2009-11-08 19:23:30 +000011826 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011827
11828 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11829 // with undefs.
11830 Value *Undef = UndefValue::get(FirstPhi.getType());
11831 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11832 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11833 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner1cd526b2009-11-08 19:23:30 +000011834}
11835
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011836// PHINode simplification
11837//
11838Instruction *InstCombiner::visitPHINode(PHINode &PN) {
11839 // If LCSSA is around, don't mess with Phi nodes
11840 if (MustPreserveLCSSA) return 0;
11841
11842 if (Value *V = PN.hasConstantValue())
11843 return ReplaceInstUsesWith(PN, V);
11844
11845 // If all PHI operands are the same operation, pull them through the PHI,
11846 // reducing code size.
11847 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000011848 isa<Instruction>(PN.getIncomingValue(1)) &&
11849 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11850 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11851 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11852 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011853 PN.getIncomingValue(0)->hasOneUse())
11854 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11855 return Result;
11856
11857 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11858 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11859 // PHI)... break the cycle.
11860 if (PN.hasOneUse()) {
11861 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11862 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
11863 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
11864 PotentiallyDeadPHIs.insert(&PN);
11865 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011866 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011867 }
11868
11869 // If this phi has a single use, and if that use just computes a value for
11870 // the next iteration of a loop, delete the phi. This occurs with unused
11871 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11872 // common case here is good because the only other things that catch this
11873 // are induction variable analysis (sometimes) and ADCE, which is only run
11874 // late.
11875 if (PHIUser->hasOneUse() &&
11876 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11877 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000011878 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011879 }
11880 }
11881
Chris Lattner27b695d2007-11-06 21:52:06 +000011882 // We sometimes end up with phi cycles that non-obviously end up being the
11883 // same value, for example:
11884 // z = some value; x = phi (y, z); y = phi (x, z)
11885 // where the phi nodes don't necessarily need to be in the same block. Do a
11886 // quick check to see if the PHI node only contains a single non-phi value, if
11887 // so, scan to see if the phi cycle is actually equal to that value.
11888 {
11889 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11890 // Scan for the first non-phi operand.
11891 while (InValNo != NumOperandVals &&
11892 isa<PHINode>(PN.getIncomingValue(InValNo)))
11893 ++InValNo;
11894
11895 if (InValNo != NumOperandVals) {
11896 Value *NonPhiInVal = PN.getOperand(InValNo);
11897
11898 // Scan the rest of the operands to see if there are any conflicts, if so
11899 // there is no need to recursively scan other phis.
11900 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11901 Value *OpVal = PN.getIncomingValue(InValNo);
11902 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11903 break;
11904 }
11905
11906 // If we scanned over all operands, then we have one unique value plus
11907 // phi values. Scan PHI nodes to see if they all merge in each other or
11908 // the value.
11909 if (InValNo == NumOperandVals) {
11910 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11911 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11912 return ReplaceInstUsesWith(PN, NonPhiInVal);
11913 }
11914 }
11915 }
Dan Gohman012d03d2009-10-30 22:22:22 +000011916
Dan Gohman2cc8e842009-10-31 14:22:52 +000011917 // If there are multiple PHIs, sort their operands so that they all list
11918 // the blocks in the same order. This will help identical PHIs be eliminated
11919 // by other passes. Other passes shouldn't depend on this for correctness
11920 // however.
11921 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11922 if (&PN != FirstPN)
11923 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman012d03d2009-10-30 22:22:22 +000011924 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman2cc8e842009-10-31 14:22:52 +000011925 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11926 if (BBA != BBB) {
11927 Value *VA = PN.getIncomingValue(i);
11928 unsigned j = PN.getBasicBlockIndex(BBB);
11929 Value *VB = PN.getIncomingValue(j);
11930 PN.setIncomingBlock(i, BBB);
11931 PN.setIncomingValue(i, VB);
11932 PN.setIncomingBlock(j, BBA);
11933 PN.setIncomingValue(j, VA);
Chris Lattnerd56c0cb2009-10-31 17:48:31 +000011934 // NOTE: Instcombine normally would want us to "return &PN" if we
11935 // modified any of the operands of an instruction. However, since we
11936 // aren't adding or removing uses (just rearranging them) we don't do
11937 // this in this case.
Dan Gohman2cc8e842009-10-31 14:22:52 +000011938 }
Dan Gohman012d03d2009-10-30 22:22:22 +000011939 }
11940
Chris Lattner1cd526b2009-11-08 19:23:30 +000011941 // If this is an integer PHI and we know that it has an illegal type, see if
11942 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11943 // PHI into the various pieces being extracted. This sort of thing is
11944 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattner4ca73902009-11-08 21:20:06 +000011945 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner1cd526b2009-11-08 19:23:30 +000011946 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11947 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11948 return Res;
11949
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011950 return 0;
11951}
11952
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011953Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5594a482009-11-27 00:29:05 +000011954 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11955
11956 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11957 return ReplaceInstUsesWith(GEP, V);
11958
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011959 Value *PtrOp = GEP.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011960
11961 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011962 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011963
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011964 // Eliminate unneeded casts for indices.
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011965 if (TD) {
11966 bool MadeChange = false;
11967 unsigned PtrSize = TD->getPointerSizeInBits();
11968
11969 gep_type_iterator GTI = gep_type_begin(GEP);
11970 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11971 I != E; ++I, ++GTI) {
11972 if (!isa<SequentialType>(*GTI)) continue;
11973
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011974 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011975 // to what we need. If narrower, sign-extend it to what we need. This
11976 // explicit cast can make subsequent optimizations more obvious.
11977 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011978 if (OpBits == PtrSize)
11979 continue;
11980
Chris Lattnerd6164c22009-08-30 20:01:10 +000011981 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011982 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011983 }
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011984 if (MadeChange) return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011985 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011986
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011987 // Combine Indices - If the source pointer to this getelementptr instruction
11988 // is a getelementptr instruction, combine the indices of the two
11989 // getelementptr instructions into a single instruction.
11990 //
Dan Gohman17f46f72009-07-28 01:40:03 +000011991 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011992 // Note that if our source is a gep chain itself that we wait for that
11993 // chain to be resolved before we perform this transformation. This
11994 // avoids us creating a TON of code in some cases.
11995 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011996 if (GetElementPtrInst *SrcGEP =
11997 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11998 if (SrcGEP->getNumOperands() == 2)
11999 return 0; // Wait until our source is folded to completion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012000
12001 SmallVector<Value*, 8> Indices;
12002
12003 // Find out whether the last index in the source GEP is a sequential idx.
12004 bool EndsWithSequential = false;
Chris Lattner1c641fc2009-08-30 05:30:55 +000012005 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
12006 I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012007 EndsWithSequential = !isa<StructType>(*I);
12008
12009 // Can we combine the two pointer arithmetics offsets?
12010 if (EndsWithSequential) {
12011 // Replace: gep (gep %P, long B), long A, ...
12012 // With: T = long A+B; gep %P, T, ...
12013 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000012014 Value *Sum;
12015 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
12016 Value *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +000012017 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012018 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +000012019 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012020 Sum = SO1;
12021 } else {
Chris Lattner1c641fc2009-08-30 05:30:55 +000012022 // If they aren't the same type, then the input hasn't been processed
12023 // by the loop above yet (which canonicalizes sequential index types to
12024 // intptr_t). Just avoid transforming this until the input has been
12025 // normalized.
12026 if (SO1->getType() != GO1->getType())
12027 return 0;
Chris Lattnerad7516a2009-08-30 18:50:58 +000012028 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012029 }
12030
Chris Lattner1c641fc2009-08-30 05:30:55 +000012031 // Update the GEP in place if possible.
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000012032 if (Src->getNumOperands() == 2) {
12033 GEP.setOperand(0, Src->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012034 GEP.setOperand(1, Sum);
12035 return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012036 }
Chris Lattner1c641fc2009-08-30 05:30:55 +000012037 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000012038 Indices.push_back(Sum);
Chris Lattner1c641fc2009-08-30 05:30:55 +000012039 Indices.append(GEP.op_begin()+2, GEP.op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012040 } else if (isa<Constant>(*GEP.idx_begin()) &&
12041 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000012042 Src->getNumOperands() != 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012043 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner1c641fc2009-08-30 05:30:55 +000012044 Indices.append(Src->op_begin()+1, Src->op_end());
12045 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012046 }
12047
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012048 if (!Indices.empty())
12049 return (cast<GEPOperator>(&GEP)->isInBounds() &&
12050 Src->isInBounds()) ?
12051 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
12052 Indices.end(), GEP.getName()) :
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000012053 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerc0f553e2009-08-30 04:49:01 +000012054 Indices.end(), GEP.getName());
Chris Lattner95ba1ec2009-08-30 05:00:50 +000012055 }
12056
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000012057 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
12058 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner95ba1ec2009-08-30 05:00:50 +000012059 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattnerf3a23592009-08-30 20:36:46 +000012060
Chris Lattner83288fa2009-08-30 20:38:21 +000012061 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
12062 // want to change the gep until the bitcasts are eliminated.
12063 if (getBitCastOperand(X)) {
12064 Worklist.AddValue(PtrOp);
12065 return 0;
12066 }
12067
Chris Lattner5594a482009-11-27 00:29:05 +000012068 bool HasZeroPointerIndex = false;
12069 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
12070 HasZeroPointerIndex = C->isZero();
12071
Chris Lattnerf3a23592009-08-30 20:36:46 +000012072 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
12073 // into : GEP [10 x i8]* X, i32 0, ...
12074 //
12075 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
12076 // into : GEP i8* X, ...
12077 //
12078 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner95ba1ec2009-08-30 05:00:50 +000012079 if (HasZeroPointerIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012080 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
12081 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000012082 if (const ArrayType *CATy =
12083 dyn_cast<ArrayType>(CPTy->getElementType())) {
12084 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
12085 if (CATy->getElementType() == XTy->getElementType()) {
12086 // -> GEP i8* X, ...
12087 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012088 return cast<GEPOperator>(&GEP)->isInBounds() ?
12089 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
12090 GEP.getName()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000012091 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
12092 GEP.getName());
Chris Lattnerf3a23592009-08-30 20:36:46 +000012093 }
12094
12095 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sandscf866e62009-03-02 09:18:21 +000012096 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012097 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000012098 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012099 // At this point, we know that the cast source type is a pointer
12100 // to an array of the same type as the destination pointer
12101 // array. Because the array type is never stepped over (there
12102 // is a leading zero) we can fold the cast into this GEP.
12103 GEP.setOperand(0, X);
12104 return &GEP;
12105 }
Duncan Sandscf866e62009-03-02 09:18:21 +000012106 }
12107 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012108 } else if (GEP.getNumOperands() == 2) {
12109 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000012110 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
12111 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012112 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
12113 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000012114 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000012115 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
12116 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000012117 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000012118 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000012119 Idx[1] = GEP.getOperand(1);
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012120 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12121 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerad7516a2009-08-30 18:50:58 +000012122 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012123 // V and GEP are both pointer types --> BitCast
Chris Lattnerad7516a2009-08-30 18:50:58 +000012124 return new BitCastInst(NewGEP, GEP.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012125 }
12126
12127 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000012128 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012129 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000012130 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012131
Owen Anderson35b47072009-08-13 21:58:54 +000012132 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012133 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000012134 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012135
12136 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
12137 // allow either a mul, shift, or constant here.
12138 Value *NewIdx = 0;
12139 ConstantInt *Scale = 0;
12140 if (ArrayEltSize == 1) {
12141 NewIdx = GEP.getOperand(1);
Chris Lattner1c641fc2009-08-30 05:30:55 +000012142 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012143 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000012144 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012145 Scale = CI;
12146 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
12147 if (Inst->getOpcode() == Instruction::Shl &&
12148 isa<ConstantInt>(Inst->getOperand(1))) {
12149 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
12150 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +000012151 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000012152 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012153 NewIdx = Inst->getOperand(0);
12154 } else if (Inst->getOpcode() == Instruction::Mul &&
12155 isa<ConstantInt>(Inst->getOperand(1))) {
12156 Scale = cast<ConstantInt>(Inst->getOperand(1));
12157 NewIdx = Inst->getOperand(0);
12158 }
12159 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000012160
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012161 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000012162 // out, perform the transformation. Note, we don't know whether Scale is
12163 // signed or not. We'll use unsigned version of division/modulo
12164 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000012165 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000012166 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000012167 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000012168 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012169 if (Scale->getZExtValue() != 1) {
Chris Lattnerbf09d632009-08-30 05:56:44 +000012170 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
12171 false /*ZExt*/);
Chris Lattnerad7516a2009-08-30 18:50:58 +000012172 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012173 }
12174
12175 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000012176 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000012177 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000012178 Idx[1] = NewIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012179 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12180 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
12181 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012182 // The NewGEP must be pointer typed, so must the old one -> BitCast
12183 return new BitCastInst(NewGEP, GEP.getType());
12184 }
12185 }
12186 }
12187 }
Chris Lattner111ea772009-01-09 04:53:57 +000012188
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012189 /// See if we can simplify:
Chris Lattner5119c702009-08-30 05:55:36 +000012190 /// X = bitcast A* to B*
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012191 /// Y = gep X, <...constant indices...>
12192 /// into a gep of the original struct. This is important for SROA and alias
12193 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000012194 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000012195 if (TD &&
12196 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012197 // Determine how much the GEP moves the pointer. We are guaranteed to get
12198 // a constant back from EmitGEPOffset.
Chris Lattner93e6ff92009-11-04 08:05:20 +000012199 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012200 int64_t Offset = OffsetV->getSExtValue();
12201
12202 // If this GEP instruction doesn't move the pointer, just replace the GEP
12203 // with a bitcast of the real input to the dest type.
12204 if (Offset == 0) {
12205 // If the bitcast is of an allocation, and the allocation will be
12206 // converted to match the type of the cast, don't touch this.
Victor Hernandezb1687302009-10-23 21:09:37 +000012207 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez48c3c542009-09-18 22:35:49 +000012208 isMalloc(BCI->getOperand(0))) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012209 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
12210 if (Instruction *I = visitBitCast(*BCI)) {
12211 if (I != BCI) {
12212 I->takeName(BCI);
12213 BCI->getParent()->getInstList().insert(BCI, I);
12214 ReplaceInstUsesWith(*BCI, I);
12215 }
12216 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000012217 }
Chris Lattner111ea772009-01-09 04:53:57 +000012218 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012219 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000012220 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012221
12222 // Otherwise, if the offset is non-zero, we need to find out if there is a
12223 // field at Offset in 'A's type. If so, we can pull the cast through the
12224 // GEP.
12225 SmallVector<Value*, 8> NewIndices;
12226 const Type *InTy =
12227 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000012228 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012229 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12230 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
12231 NewIndices.end()) :
12232 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
12233 NewIndices.end());
Chris Lattnerad7516a2009-08-30 18:50:58 +000012234
12235 if (NGEP->getType() == GEP.getType())
12236 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner94ccd5f2009-01-09 05:44:56 +000012237 NGEP->takeName(&GEP);
12238 return new BitCastInst(NGEP, GEP.getType());
12239 }
Chris Lattner111ea772009-01-09 04:53:57 +000012240 }
12241 }
12242
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012243 return 0;
12244}
12245
Victor Hernandezb1687302009-10-23 21:09:37 +000012246Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattner310a00f2009-11-01 19:50:13 +000012247 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000012248 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012249 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
12250 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000012251 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandez37f513d2009-10-17 01:18:07 +000012252 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandezb1687302009-10-23 21:09:37 +000012253 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerad7516a2009-08-30 18:50:58 +000012254 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012255
12256 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000012257 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012258 //
12259 BasicBlock::iterator It = New;
Victor Hernandezb1687302009-10-23 21:09:37 +000012260 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012261
12262 // Now that I is pointing to the first non-allocation-inst in the block,
12263 // insert our getelementptr instruction...
12264 //
Owen Anderson35b47072009-08-13 21:58:54 +000012265 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000012266 Value *Idx[2];
12267 Idx[0] = NullIdx;
12268 Idx[1] = NullIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012269 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
12270 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012271
12272 // Now make everything use the getelementptr instead of the original
12273 // allocation.
12274 return ReplaceInstUsesWith(AI, V);
12275 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +000012276 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012277 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000012278 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012279
Dan Gohmana80e2712009-07-21 23:21:54 +000012280 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000012281 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000012282 // Note that we only do this for alloca's, because malloc should allocate
12283 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000012284 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +000012285 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000012286
12287 // If the alignment is 0 (unspecified), assign it the preferred alignment.
12288 if (AI.getAlignment() == 0)
12289 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
12290 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012291
12292 return 0;
12293}
12294
Victor Hernandez93946082009-10-24 04:23:03 +000012295Instruction *InstCombiner::visitFree(Instruction &FI) {
12296 Value *Op = FI.getOperand(1);
12297
12298 // free undef -> unreachable.
12299 if (isa<UndefValue>(Op)) {
12300 // Insert a new store to null because we cannot modify the CFG here.
12301 new StoreInst(ConstantInt::getTrue(*Context),
12302 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
12303 return EraseInstFromFunction(FI);
12304 }
12305
12306 // If we have 'free null' delete the instruction. This can happen in stl code
12307 // when lots of inlining happens.
12308 if (isa<ConstantPointerNull>(Op))
12309 return EraseInstFromFunction(FI);
12310
Victor Hernandezf9a7a332009-10-26 23:43:48 +000012311 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman1674ea52009-10-27 00:11:02 +000012312 if (isMalloc(Op)) {
Victor Hernandez93946082009-10-24 04:23:03 +000012313 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
12314 if (Op->hasOneUse() && CI->hasOneUse()) {
12315 EraseInstFromFunction(FI);
12316 EraseInstFromFunction(*CI);
12317 return EraseInstFromFunction(*cast<Instruction>(Op));
12318 }
12319 } else {
12320 // Op is a call to malloc
12321 if (Op->hasOneUse()) {
12322 EraseInstFromFunction(FI);
12323 return EraseInstFromFunction(*cast<Instruction>(Op));
12324 }
12325 }
Dan Gohman1674ea52009-10-27 00:11:02 +000012326 }
Victor Hernandez93946082009-10-24 04:23:03 +000012327
12328 return 0;
12329}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012330
12331/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000012332static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000012333 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012334 User *CI = cast<User>(LI.getOperand(0));
12335 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000012336 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012337
Mon P Wangbd05ed82009-02-07 22:19:29 +000012338 const PointerType *DestTy = cast<PointerType>(CI->getType());
12339 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012340 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000012341
12342 // If the address spaces don't match, don't eliminate the cast.
12343 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
12344 return 0;
12345
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012346 const Type *SrcPTy = SrcTy->getElementType();
12347
12348 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
12349 isa<VectorType>(DestPTy)) {
12350 // If the source is an array, the code below will not succeed. Check to
12351 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12352 // constants.
12353 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
12354 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
12355 if (ASrcTy->getNumElements() != 0) {
12356 Value *Idxs[2];
Chris Lattner7bdc6d52009-10-22 06:44:07 +000012357 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12358 Idxs[1] = Idxs[0];
Owen Anderson02b48c32009-07-29 18:55:55 +000012359 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012360 SrcTy = cast<PointerType>(CastOp->getType());
12361 SrcPTy = SrcTy->getElementType();
12362 }
12363
Dan Gohmana80e2712009-07-21 23:21:54 +000012364 if (IC.getTargetData() &&
12365 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012366 isa<VectorType>(SrcPTy)) &&
12367 // Do not allow turning this into a load of an integer, which is then
12368 // casted to a pointer, this pessimizes pointer analysis a lot.
12369 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000012370 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
12371 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012372
12373 // Okay, we are casting from one integer or pointer type to another of
12374 // the same size. Instead of casting the pointer before the load, cast
12375 // the result of the loaded value.
Chris Lattnerad7516a2009-08-30 18:50:58 +000012376 Value *NewLoad =
12377 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012378 // Now cast the result of the load.
12379 return new BitCastInst(NewLoad, LI.getType());
12380 }
12381 }
12382 }
12383 return 0;
12384}
12385
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012386Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12387 Value *Op = LI.getOperand(0);
12388
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012389 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000012390 if (TD) {
12391 unsigned KnownAlign =
12392 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12393 if (KnownAlign >
12394 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12395 LI.getAlignment()))
12396 LI.setAlignment(KnownAlign);
12397 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012398
Chris Lattnerf3a23592009-08-30 20:36:46 +000012399 // load (cast X) --> cast (load X) iff safe.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012400 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000012401 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012402 return Res;
12403
12404 // None of the following transforms are legal for volatile loads.
12405 if (LI.isVolatile()) return 0;
12406
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000012407 // Do really simple store-to-load forwarding and load CSE, to catch cases
12408 // where there are several consequtive memory accesses to the same location,
12409 // separated by a few arithmetic operations.
12410 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000012411 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12412 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012413
Chris Lattner05274832009-10-22 06:25:11 +000012414 // load(gep null, ...) -> unreachable
Christopher Lamb2c175392007-12-29 07:56:53 +000012415 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12416 const Value *GEPI0 = GEPI->getOperand(0);
12417 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +000012418 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012419 // Insert a new store to null instruction before the load to indicate
12420 // that this code is not reachable. We do this instead of inserting
12421 // an unreachable instruction directly because we cannot modify the
12422 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012423 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000012424 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000012425 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012426 }
Christopher Lamb2c175392007-12-29 07:56:53 +000012427 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012428
Chris Lattner05274832009-10-22 06:25:11 +000012429 // load null/undef -> unreachable
12430 // TODO: Consider a target hook for valid address spaces for this xform.
12431 if (isa<UndefValue>(Op) ||
12432 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12433 // Insert a new store to null instruction before the load to indicate that
12434 // this code is not reachable. We do this instead of inserting an
12435 // unreachable instruction directly because we cannot modify the CFG.
12436 new StoreInst(UndefValue::get(LI.getType()),
12437 Constant::getNullValue(Op->getType()), &LI);
12438 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012439 }
Chris Lattner05274832009-10-22 06:25:11 +000012440
12441 // Instcombine load (constantexpr_cast global) -> cast (load global)
12442 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12443 if (CE->isCast())
12444 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12445 return Res;
12446
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012447 if (Op->hasOneUse()) {
12448 // Change select and PHI nodes to select values instead of addresses: this
12449 // helps alias analysis out a lot, allows many others simplifications, and
12450 // exposes redundancy in the code.
12451 //
12452 // Note that we cannot do the transformation unless we know that the
12453 // introduced loads cannot trap! Something like this is valid as long as
12454 // the condition is always false: load (select bool %C, int* null, int* %G),
12455 // but it would not be valid if we transformed it to load from null
12456 // unconditionally.
12457 //
12458 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12459 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
12460 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12461 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000012462 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12463 SI->getOperand(1)->getName()+".val");
12464 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12465 SI->getOperand(2)->getName()+".val");
Gabor Greifd6da1d02008-04-06 20:25:17 +000012466 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012467 }
12468
12469 // load (select (cond, null, P)) -> load P
12470 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12471 if (C->isNullValue()) {
12472 LI.setOperand(0, SI->getOperand(2));
12473 return &LI;
12474 }
12475
12476 // load (select (cond, P, null)) -> load P
12477 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12478 if (C->isNullValue()) {
12479 LI.setOperand(0, SI->getOperand(1));
12480 return &LI;
12481 }
12482 }
12483 }
12484 return 0;
12485}
12486
12487/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000012488/// when possible. This makes it generally easy to do alias analysis and/or
12489/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012490static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12491 User *CI = cast<User>(SI.getOperand(1));
12492 Value *CastOp = CI->getOperand(0);
12493
12494 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000012495 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12496 if (SrcTy == 0) return 0;
12497
12498 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012499
Chris Lattnera032c0e2009-01-16 20:08:59 +000012500 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12501 return 0;
12502
Chris Lattner54dddc72009-01-24 01:00:13 +000012503 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12504 /// to its first element. This allows us to handle things like:
12505 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12506 /// on 32-bit hosts.
12507 SmallVector<Value*, 4> NewGEPIndices;
12508
Chris Lattnera032c0e2009-01-16 20:08:59 +000012509 // If the source is an array, the code below will not succeed. Check to
12510 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12511 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000012512 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12513 // Index through pointer.
Owen Anderson35b47072009-08-13 21:58:54 +000012514 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner54dddc72009-01-24 01:00:13 +000012515 NewGEPIndices.push_back(Zero);
12516
12517 while (1) {
12518 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000012519 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000012520 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000012521 NewGEPIndices.push_back(Zero);
12522 SrcPTy = STy->getElementType(0);
12523 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12524 NewGEPIndices.push_back(Zero);
12525 SrcPTy = ATy->getElementType();
12526 } else {
12527 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012528 }
Chris Lattner54dddc72009-01-24 01:00:13 +000012529 }
12530
Owen Anderson6b6e2d92009-07-29 22:17:13 +000012531 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000012532 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000012533
12534 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12535 return 0;
12536
Chris Lattnerc73a0d12009-01-16 20:12:52 +000012537 // If the pointers point into different address spaces or if they point to
12538 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000012539 if (!IC.getTargetData() ||
12540 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000012541 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000012542 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12543 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000012544 return 0;
12545
12546 // Okay, we are casting from one integer or pointer type to another of
12547 // the same size. Instead of casting the pointer before
12548 // the store, cast the value to be stored.
12549 Value *NewCast;
12550 Value *SIOp0 = SI.getOperand(0);
12551 Instruction::CastOps opcode = Instruction::BitCast;
12552 const Type* CastSrcTy = SIOp0->getType();
12553 const Type* CastDstTy = SrcPTy;
12554 if (isa<PointerType>(CastDstTy)) {
12555 if (CastSrcTy->isInteger())
12556 opcode = Instruction::IntToPtr;
12557 } else if (isa<IntegerType>(CastDstTy)) {
12558 if (isa<PointerType>(SIOp0->getType()))
12559 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012560 }
Chris Lattner54dddc72009-01-24 01:00:13 +000012561
12562 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12563 // emit a GEP to index into its first field.
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012564 if (!NewGEPIndices.empty())
12565 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12566 NewGEPIndices.end());
Chris Lattner54dddc72009-01-24 01:00:13 +000012567
Chris Lattnerad7516a2009-08-30 18:50:58 +000012568 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12569 SIOp0->getName()+".c");
Chris Lattnera032c0e2009-01-16 20:08:59 +000012570 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012571}
12572
Chris Lattner6fd8c802008-11-27 08:56:30 +000012573/// equivalentAddressValues - Test if A and B will obviously have the same
12574/// value. This includes recognizing that %t0 and %t1 will have the same
12575/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000012576/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000012577/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000012578/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000012579/// %t2 = load i32* %t1
12580///
12581static bool equivalentAddressValues(Value *A, Value *B) {
12582 // Test if the values are trivially equivalent.
12583 if (A == B) return true;
12584
12585 // Test if the values come form identical arithmetic instructions.
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000012586 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12587 // its only used to compare two uses within the same basic block, which
12588 // means that they'll always either have the same value or one of them
12589 // will have an undefined value.
Chris Lattner6fd8c802008-11-27 08:56:30 +000012590 if (isa<BinaryOperator>(A) ||
12591 isa<CastInst>(A) ||
12592 isa<PHINode>(A) ||
12593 isa<GetElementPtrInst>(A))
12594 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000012595 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner6fd8c802008-11-27 08:56:30 +000012596 return true;
12597
12598 // Otherwise they may not be equivalent.
12599 return false;
12600}
12601
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012602// If this instruction has two uses, one of which is a llvm.dbg.declare,
12603// return the llvm.dbg.declare.
12604DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12605 if (!V->hasNUses(2))
12606 return 0;
12607 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12608 UI != E; ++UI) {
12609 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12610 return DI;
12611 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12612 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12613 return DI;
12614 }
12615 }
12616 return 0;
12617}
12618
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012619Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12620 Value *Val = SI.getOperand(0);
12621 Value *Ptr = SI.getOperand(1);
12622
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012623 // If the RHS is an alloca with a single use, zapify the store, making the
12624 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012625 // If the RHS is an alloca with a two uses, the other one being a
12626 // llvm.dbg.declare, zapify the store and the declare, making the
12627 // alloca dead. We must do this to prevent declare's from affecting
12628 // codegen.
12629 if (!SI.isVolatile()) {
12630 if (Ptr->hasOneUse()) {
12631 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012632 EraseInstFromFunction(SI);
12633 ++NumCombined;
12634 return 0;
12635 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012636 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12637 if (isa<AllocaInst>(GEP->getOperand(0))) {
12638 if (GEP->getOperand(0)->hasOneUse()) {
12639 EraseInstFromFunction(SI);
12640 ++NumCombined;
12641 return 0;
12642 }
12643 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12644 EraseInstFromFunction(*DI);
12645 EraseInstFromFunction(SI);
12646 ++NumCombined;
12647 return 0;
12648 }
12649 }
12650 }
12651 }
12652 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12653 EraseInstFromFunction(*DI);
12654 EraseInstFromFunction(SI);
12655 ++NumCombined;
12656 return 0;
12657 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012658 }
12659
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012660 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000012661 if (TD) {
12662 unsigned KnownAlign =
12663 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12664 if (KnownAlign >
12665 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12666 SI.getAlignment()))
12667 SI.setAlignment(KnownAlign);
12668 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012669
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012670 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012671 // stores to the same location, separated by a few arithmetic operations. This
12672 // situation often occurs with bitfield accesses.
12673 BasicBlock::iterator BBI = &SI;
12674 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12675 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000012676 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000012677 // Don't count debug info directives, lest they affect codegen,
12678 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12679 // It is necessary for correctness to skip those that feed into a
12680 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000012681 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000012682 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012683 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012684 continue;
12685 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012686
12687 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12688 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000012689 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12690 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012691 ++NumDeadStore;
12692 ++BBI;
12693 EraseInstFromFunction(*PrevSI);
12694 continue;
12695 }
12696 break;
12697 }
12698
12699 // If this is a load, we have to stop. However, if the loaded value is from
12700 // the pointer we're loading and is producing the pointer we're storing,
12701 // then *this* store is dead (X = load P; store X -> P).
12702 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000012703 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12704 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012705 EraseInstFromFunction(SI);
12706 ++NumCombined;
12707 return 0;
12708 }
12709 // Otherwise, this is a load from some other location. Stores before it
12710 // may not be dead.
12711 break;
12712 }
12713
12714 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000012715 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012716 break;
12717 }
12718
12719
12720 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
12721
12722 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner6807a242009-08-30 20:06:40 +000012723 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012724 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012725 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012726 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner3183fb62009-08-30 06:13:40 +000012727 Worklist.Add(U); // Dropped a use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012728 ++NumCombined;
12729 }
12730 return 0; // Do not modify these!
12731 }
12732
12733 // store undef, Ptr -> noop
12734 if (isa<UndefValue>(Val)) {
12735 EraseInstFromFunction(SI);
12736 ++NumCombined;
12737 return 0;
12738 }
12739
12740 // If the pointer destination is a cast, see if we can fold the cast into the
12741 // source instead.
12742 if (isa<CastInst>(Ptr))
12743 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12744 return Res;
12745 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
12746 if (CE->isCast())
12747 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12748 return Res;
12749
12750
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012751 // If this store is the last instruction in the basic block (possibly
12752 // excepting debug info instructions and the pointer bitcasts that feed
12753 // into them), and if the block ends with an unconditional branch, try
12754 // to move it to the successor block.
12755 BBI = &SI;
12756 do {
12757 ++BBI;
12758 } while (isa<DbgInfoIntrinsic>(BBI) ||
12759 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012760 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
12761 if (BI->isUnconditional())
12762 if (SimplifyStoreAtEndOfBlock(SI))
12763 return 0; // xform done!
12764
12765 return 0;
12766}
12767
12768/// SimplifyStoreAtEndOfBlock - Turn things like:
12769/// if () { *P = v1; } else { *P = v2 }
12770/// into a phi node with a store in the successor.
12771///
12772/// Simplify things like:
12773/// *P = v1; if () { *P = v2; }
12774/// into a phi node with a store in the successor.
12775///
12776bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12777 BasicBlock *StoreBB = SI.getParent();
12778
12779 // Check to see if the successor block has exactly two incoming edges. If
12780 // so, see if the other predecessor contains a store to the same location.
12781 // if so, insert a PHI node (if needed) and move the stores down.
12782 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12783
12784 // Determine whether Dest has exactly two predecessors and, if so, compute
12785 // the other predecessor.
12786 pred_iterator PI = pred_begin(DestBB);
12787 BasicBlock *OtherBB = 0;
12788 if (*PI != StoreBB)
12789 OtherBB = *PI;
12790 ++PI;
12791 if (PI == pred_end(DestBB))
12792 return false;
12793
12794 if (*PI != StoreBB) {
12795 if (OtherBB)
12796 return false;
12797 OtherBB = *PI;
12798 }
12799 if (++PI != pred_end(DestBB))
12800 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000012801
12802 // Bail out if all the relevant blocks aren't distinct (this can happen,
12803 // for example, if SI is in an infinite loop)
12804 if (StoreBB == DestBB || OtherBB == DestBB)
12805 return false;
12806
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012807 // Verify that the other block ends in a branch and is not otherwise empty.
12808 BasicBlock::iterator BBI = OtherBB->getTerminator();
12809 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12810 if (!OtherBr || BBI == OtherBB->begin())
12811 return false;
12812
12813 // If the other block ends in an unconditional branch, check for the 'if then
12814 // else' case. there is an instruction before the branch.
12815 StoreInst *OtherStore = 0;
12816 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012817 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012818 // Skip over debugging info.
12819 while (isa<DbgInfoIntrinsic>(BBI) ||
12820 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12821 if (BBI==OtherBB->begin())
12822 return false;
12823 --BBI;
12824 }
Chris Lattner69fa3f52009-11-02 02:06:37 +000012825 // If this isn't a store, isn't a store to the same location, or if the
12826 // alignments differ, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012827 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner69fa3f52009-11-02 02:06:37 +000012828 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12829 OtherStore->getAlignment() != SI.getAlignment())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012830 return false;
12831 } else {
12832 // Otherwise, the other block ended with a conditional branch. If one of the
12833 // destinations is StoreBB, then we have the if/then case.
12834 if (OtherBr->getSuccessor(0) != StoreBB &&
12835 OtherBr->getSuccessor(1) != StoreBB)
12836 return false;
12837
12838 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12839 // if/then triangle. See if there is a store to the same ptr as SI that
12840 // lives in OtherBB.
12841 for (;; --BBI) {
12842 // Check to see if we find the matching store.
12843 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner69fa3f52009-11-02 02:06:37 +000012844 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12845 OtherStore->getAlignment() != SI.getAlignment())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012846 return false;
12847 break;
12848 }
Eli Friedman3a311d52008-06-13 22:02:12 +000012849 // If we find something that may be using or overwriting the stored
12850 // value, or if we run out of instructions, we can't do the xform.
12851 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012852 BBI == OtherBB->begin())
12853 return false;
12854 }
12855
12856 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000012857 // make sure nothing reads or overwrites the stored value in
12858 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012859 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12860 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000012861 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012862 return false;
12863 }
12864 }
12865
12866 // Insert a PHI node now if we need it.
12867 Value *MergedVal = OtherStore->getOperand(0);
12868 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000012869 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012870 PN->reserveOperandSpace(2);
12871 PN->addIncoming(SI.getOperand(0), SI.getParent());
12872 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12873 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12874 }
12875
12876 // Advance to a place where it is safe to insert the new store and
12877 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000012878 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012879 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner69fa3f52009-11-02 02:06:37 +000012880 OtherStore->isVolatile(),
12881 SI.getAlignment()), *BBI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012882
12883 // Nuke the old stores.
12884 EraseInstFromFunction(SI);
12885 EraseInstFromFunction(*OtherStore);
12886 ++NumCombined;
12887 return true;
12888}
12889
12890
12891Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12892 // Change br (not X), label True, label False to: br X, label False, True
12893 Value *X = 0;
12894 BasicBlock *TrueDest;
12895 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +000012896 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012897 !isa<Constant>(X)) {
12898 // Swap Destinations and condition...
12899 BI.setCondition(X);
12900 BI.setSuccessor(0, FalseDest);
12901 BI.setSuccessor(1, TrueDest);
12902 return &BI;
12903 }
12904
12905 // Cannonicalize fcmp_one -> fcmp_oeq
12906 FCmpInst::Predicate FPred; Value *Y;
12907 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000012908 TrueDest, FalseDest)) &&
12909 BI.getCondition()->hasOneUse())
12910 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12911 FPred == FCmpInst::FCMP_OGE) {
12912 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12913 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12914
12915 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012916 BI.setSuccessor(0, FalseDest);
12917 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000012918 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012919 return &BI;
12920 }
12921
12922 // Cannonicalize icmp_ne -> icmp_eq
12923 ICmpInst::Predicate IPred;
12924 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000012925 TrueDest, FalseDest)) &&
12926 BI.getCondition()->hasOneUse())
12927 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12928 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12929 IPred == ICmpInst::ICMP_SGE) {
12930 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12931 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12932 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012933 BI.setSuccessor(0, FalseDest);
12934 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000012935 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012936 return &BI;
12937 }
12938
12939 return 0;
12940}
12941
12942Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12943 Value *Cond = SI.getCondition();
12944 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12945 if (I->getOpcode() == Instruction::Add)
12946 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12947 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12948 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012949 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +000012950 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012951 AddRHS));
12952 SI.setOperand(0, I->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +000012953 Worklist.Add(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012954 return &SI;
12955 }
12956 }
12957 return 0;
12958}
12959
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012960Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012961 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012962
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012963 if (!EV.hasIndices())
12964 return ReplaceInstUsesWith(EV, Agg);
12965
12966 if (Constant *C = dyn_cast<Constant>(Agg)) {
12967 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012968 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012969
12970 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +000012971 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012972
12973 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12974 // Extract the element indexed by the first index out of the constant
12975 Value *V = C->getOperand(*EV.idx_begin());
12976 if (EV.getNumIndices() > 1)
12977 // Extract the remaining indices out of the constant indexed by the
12978 // first index
12979 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12980 else
12981 return ReplaceInstUsesWith(EV, V);
12982 }
12983 return 0; // Can't handle other constants
12984 }
12985 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12986 // We're extracting from an insertvalue instruction, compare the indices
12987 const unsigned *exti, *exte, *insi, *inse;
12988 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12989 exte = EV.idx_end(), inse = IV->idx_end();
12990 exti != exte && insi != inse;
12991 ++exti, ++insi) {
12992 if (*insi != *exti)
12993 // The insert and extract both reference distinctly different elements.
12994 // This means the extract is not influenced by the insert, and we can
12995 // replace the aggregate operand of the extract with the aggregate
12996 // operand of the insert. i.e., replace
12997 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12998 // %E = extractvalue { i32, { i32 } } %I, 0
12999 // with
13000 // %E = extractvalue { i32, { i32 } } %A, 0
13001 return ExtractValueInst::Create(IV->getAggregateOperand(),
13002 EV.idx_begin(), EV.idx_end());
13003 }
13004 if (exti == exte && insi == inse)
13005 // Both iterators are at the end: Index lists are identical. Replace
13006 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
13007 // %C = extractvalue { i32, { i32 } } %B, 1, 0
13008 // with "i32 42"
13009 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
13010 if (exti == exte) {
13011 // The extract list is a prefix of the insert list. i.e. replace
13012 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
13013 // %E = extractvalue { i32, { i32 } } %I, 1
13014 // with
13015 // %X = extractvalue { i32, { i32 } } %A, 1
13016 // %E = insertvalue { i32 } %X, i32 42, 0
13017 // by switching the order of the insert and extract (though the
13018 // insertvalue should be left in, since it may have other uses).
Chris Lattnerad7516a2009-08-30 18:50:58 +000013019 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
13020 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000013021 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
13022 insi, inse);
13023 }
13024 if (insi == inse)
13025 // The insert list is a prefix of the extract list
13026 // We can simply remove the common indices from the extract and make it
13027 // operate on the inserted value instead of the insertvalue result.
13028 // i.e., replace
13029 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
13030 // %E = extractvalue { i32, { i32 } } %I, 1, 0
13031 // with
13032 // %E extractvalue { i32 } { i32 42 }, 0
13033 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
13034 exti, exte);
13035 }
Chris Lattner69a70752009-11-09 07:07:56 +000013036 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
13037 // We're extracting from an intrinsic, see if we're the only user, which
13038 // allows us to simplify multiple result intrinsics to simpler things that
13039 // just get one value..
13040 if (II->hasOneUse()) {
13041 // Check if we're grabbing the overflow bit or the result of a 'with
13042 // overflow' intrinsic. If it's the latter we can remove the intrinsic
13043 // and replace it with a traditional binary instruction.
13044 switch (II->getIntrinsicID()) {
13045 case Intrinsic::uadd_with_overflow:
13046 case Intrinsic::sadd_with_overflow:
13047 if (*EV.idx_begin() == 0) { // Normal result.
13048 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13049 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13050 EraseInstFromFunction(*II);
13051 return BinaryOperator::CreateAdd(LHS, RHS);
13052 }
13053 break;
13054 case Intrinsic::usub_with_overflow:
13055 case Intrinsic::ssub_with_overflow:
13056 if (*EV.idx_begin() == 0) { // Normal result.
13057 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13058 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13059 EraseInstFromFunction(*II);
13060 return BinaryOperator::CreateSub(LHS, RHS);
13061 }
13062 break;
13063 case Intrinsic::umul_with_overflow:
13064 case Intrinsic::smul_with_overflow:
13065 if (*EV.idx_begin() == 0) { // Normal result.
13066 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13067 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13068 EraseInstFromFunction(*II);
13069 return BinaryOperator::CreateMul(LHS, RHS);
13070 }
13071 break;
13072 default:
13073 break;
13074 }
13075 }
13076 }
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000013077 // Can't simplify extracts from other values. Note that nested extracts are
13078 // already simplified implicitely by the above (extract ( extract (insert) )
13079 // will be translated into extract ( insert ( extract ) ) first and then just
13080 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000013081 return 0;
13082}
13083
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013084/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
13085/// is to leave as a vector operation.
13086static bool CheapToScalarize(Value *V, bool isConstant) {
13087 if (isa<ConstantAggregateZero>(V))
13088 return true;
13089 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
13090 if (isConstant) return true;
13091 // If all elts are the same, we can extract.
13092 Constant *Op0 = C->getOperand(0);
13093 for (unsigned i = 1; i < C->getNumOperands(); ++i)
13094 if (C->getOperand(i) != Op0)
13095 return false;
13096 return true;
13097 }
13098 Instruction *I = dyn_cast<Instruction>(V);
13099 if (!I) return false;
13100
13101 // Insert element gets simplified to the inserted element or is deleted if
13102 // this is constant idx extract element and its a constant idx insertelt.
13103 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
13104 isa<ConstantInt>(I->getOperand(2)))
13105 return true;
13106 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
13107 return true;
13108 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
13109 if (BO->hasOneUse() &&
13110 (CheapToScalarize(BO->getOperand(0), isConstant) ||
13111 CheapToScalarize(BO->getOperand(1), isConstant)))
13112 return true;
13113 if (CmpInst *CI = dyn_cast<CmpInst>(I))
13114 if (CI->hasOneUse() &&
13115 (CheapToScalarize(CI->getOperand(0), isConstant) ||
13116 CheapToScalarize(CI->getOperand(1), isConstant)))
13117 return true;
13118
13119 return false;
13120}
13121
13122/// Read and decode a shufflevector mask.
13123///
13124/// It turns undef elements into values that are larger than the number of
13125/// elements in the input.
13126static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
13127 unsigned NElts = SVI->getType()->getNumElements();
13128 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
13129 return std::vector<unsigned>(NElts, 0);
13130 if (isa<UndefValue>(SVI->getOperand(2)))
13131 return std::vector<unsigned>(NElts, 2*NElts);
13132
13133 std::vector<unsigned> Result;
13134 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000013135 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
13136 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013137 Result.push_back(NElts*2); // undef -> 8
13138 else
Gabor Greif17396002008-06-12 21:37:33 +000013139 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013140 return Result;
13141}
13142
13143/// FindScalarElement - Given a vector and an element number, see if the scalar
13144/// value is already around as a register, for example if it were inserted then
13145/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000013146static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000013147 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013148 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
13149 const VectorType *PTy = cast<VectorType>(V->getType());
13150 unsigned Width = PTy->getNumElements();
13151 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +000013152 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013153
13154 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +000013155 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013156 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +000013157 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013158 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
13159 return CP->getOperand(EltNo);
13160 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
13161 // If this is an insert to a variable element, we don't know what it is.
13162 if (!isa<ConstantInt>(III->getOperand(2)))
13163 return 0;
13164 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
13165
13166 // If this is an insert to the element we are looking for, return the
13167 // inserted value.
13168 if (EltNo == IIElt)
13169 return III->getOperand(1);
13170
13171 // Otherwise, the insertelement doesn't modify the value, recurse on its
13172 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000013173 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013174 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013175 unsigned LHSWidth =
13176 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013177 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013178 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000013179 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013180 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000013181 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013182 else
Owen Andersonb99ecca2009-07-30 23:03:37 +000013183 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013184 }
13185
13186 // Otherwise, we don't know.
13187 return 0;
13188}
13189
13190Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013191 // If vector val is undef, replace extract with scalar undef.
13192 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000013193 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013194
13195 // If vector val is constant 0, replace extract with scalar 0.
13196 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +000013197 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013198
13199 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000013200 // If vector val is constant with all elements the same, replace EI with
13201 // that element. When the elements are not identical, we cannot replace yet
13202 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013203 Constant *op0 = C->getOperand(0);
Chris Lattner1ba36b72009-09-08 03:44:51 +000013204 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013205 if (C->getOperand(i) != op0) {
13206 op0 = 0;
13207 break;
13208 }
13209 if (op0)
13210 return ReplaceInstUsesWith(EI, op0);
13211 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000013212
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013213 // If extracting a specified index from the vector, see if we can recursively
13214 // find a previously computed scalar that was inserted into the vector.
13215 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13216 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner1ba36b72009-09-08 03:44:51 +000013217 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013218
13219 // If this is extracting an invalid index, turn this into undef, to avoid
13220 // crashing the code below.
13221 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +000013222 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013223
13224 // This instruction only demands the single element from the input vector.
13225 // If the input vector has a single use, simplify it based on this use
13226 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000013227 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000013228 APInt UndefElts(VectorWidth, 0);
13229 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013230 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000013231 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013232 EI.setOperand(0, V);
13233 return &EI;
13234 }
13235 }
13236
Owen Anderson24be4c12009-07-03 00:17:18 +000013237 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013238 return ReplaceInstUsesWith(EI, Elt);
13239
13240 // If the this extractelement is directly using a bitcast from a vector of
13241 // the same number of elements, see if we can find the source element from
13242 // it. In this case, we will end up needing to bitcast the scalars.
13243 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
13244 if (const VectorType *VT =
13245 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
13246 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000013247 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
13248 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013249 return new BitCastInst(Elt, EI.getType());
13250 }
13251 }
13252
13253 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattnera97bc602009-09-08 18:48:01 +000013254 // Push extractelement into predecessor operation if legal and
13255 // profitable to do so
13256 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
13257 if (I->hasOneUse() &&
13258 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
13259 Value *newEI0 =
13260 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
13261 EI.getName()+".lhs");
13262 Value *newEI1 =
13263 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
13264 EI.getName()+".rhs");
13265 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013266 }
Chris Lattnera97bc602009-09-08 18:48:01 +000013267 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013268 // Extracting the inserted element?
13269 if (IE->getOperand(2) == EI.getOperand(1))
13270 return ReplaceInstUsesWith(EI, IE->getOperand(1));
13271 // If the inserted and extracted elements are constants, they must not
13272 // be the same value, extract from the pre-inserted value instead.
Chris Lattner78628292009-08-30 19:47:22 +000013273 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +000013274 Worklist.AddValue(EI.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013275 EI.setOperand(0, IE->getOperand(0));
13276 return &EI;
13277 }
13278 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
13279 // If this is extracting an element from a shufflevector, figure out where
13280 // it came from and extract from the appropriate input element instead.
13281 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13282 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
13283 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013284 unsigned LHSWidth =
13285 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13286
13287 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013288 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013289 else if (SrcIdx < LHSWidth*2) {
13290 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013291 Src = SVI->getOperand(1);
13292 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000013293 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013294 }
Eric Christopher1ba36872009-07-25 02:28:41 +000013295 return ExtractElementInst::Create(Src,
Chris Lattner78628292009-08-30 19:47:22 +000013296 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
13297 false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013298 }
13299 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000013300 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013301 }
13302 return 0;
13303}
13304
13305/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
13306/// elements from either LHS or RHS, return the shuffle mask and true.
13307/// Otherwise, return false.
13308static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000013309 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000013310 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013311 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
13312 "Invalid CollectSingleShuffleElements");
13313 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
13314
13315 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000013316 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013317 return true;
13318 } else if (V == LHS) {
13319 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000013320 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013321 return true;
13322 } else if (V == RHS) {
13323 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000013324 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013325 return true;
13326 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13327 // If this is an insert of an extract from some other vector, include it.
13328 Value *VecOp = IEI->getOperand(0);
13329 Value *ScalarOp = IEI->getOperand(1);
13330 Value *IdxOp = IEI->getOperand(2);
13331
13332 if (!isa<ConstantInt>(IdxOp))
13333 return false;
13334 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13335
13336 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
13337 // Okay, we can handle this if the vector we are insertinting into is
13338 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000013339 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013340 // If so, update the mask to reflect the inserted undef.
Owen Anderson35b47072009-08-13 21:58:54 +000013341 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013342 return true;
13343 }
13344 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
13345 if (isa<ConstantInt>(EI->getOperand(1)) &&
13346 EI->getOperand(0)->getType() == V->getType()) {
13347 unsigned ExtractedIdx =
13348 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13349
13350 // This must be extracting from either LHS or RHS.
13351 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
13352 // Okay, we can handle this if the vector we are insertinting into is
13353 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000013354 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013355 // If so, update the mask to reflect the inserted value.
13356 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000013357 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000013358 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013359 } else {
13360 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000013361 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000013362 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013363
13364 }
13365 return true;
13366 }
13367 }
13368 }
13369 }
13370 }
13371 // TODO: Handle shufflevector here!
13372
13373 return false;
13374}
13375
13376/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13377/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
13378/// that computes V and the LHS value of the shuffle.
13379static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000013380 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013381 assert(isa<VectorType>(V->getType()) &&
13382 (RHS == 0 || V->getType() == RHS->getType()) &&
13383 "Invalid shuffle!");
13384 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
13385
13386 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000013387 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013388 return V;
13389 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000013390 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013391 return V;
13392 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13393 // If this is an insert of an extract from some other vector, include it.
13394 Value *VecOp = IEI->getOperand(0);
13395 Value *ScalarOp = IEI->getOperand(1);
13396 Value *IdxOp = IEI->getOperand(2);
13397
13398 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13399 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13400 EI->getOperand(0)->getType() == V->getType()) {
13401 unsigned ExtractedIdx =
13402 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13403 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13404
13405 // Either the extracted from or inserted into vector must be RHSVec,
13406 // otherwise we'd end up with a shuffle of three inputs.
13407 if (EI->getOperand(0) == RHS || RHS == 0) {
13408 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000013409 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000013410 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000013411 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013412 return V;
13413 }
13414
13415 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000013416 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
13417 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013418 // Everything but the extracted element is replaced with the RHS.
13419 for (unsigned i = 0; i != NumElts; ++i) {
13420 if (i != InsertedIdx)
Owen Anderson35b47072009-08-13 21:58:54 +000013421 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013422 }
13423 return V;
13424 }
13425
13426 // If this insertelement is a chain that comes from exactly these two
13427 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000013428 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
13429 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013430 return EI->getOperand(0);
13431
13432 }
13433 }
13434 }
13435 // TODO: Handle shufflevector here!
13436
13437 // Otherwise, can't do anything fancy. Return an identity vector.
13438 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000013439 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013440 return V;
13441}
13442
13443Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13444 Value *VecOp = IE.getOperand(0);
13445 Value *ScalarOp = IE.getOperand(1);
13446 Value *IdxOp = IE.getOperand(2);
13447
13448 // Inserting an undef or into an undefined place, remove this.
13449 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13450 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000013451
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013452 // If the inserted element was extracted from some other vector, and if the
13453 // indexes are constant, try to turn this into a shufflevector operation.
13454 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13455 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13456 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000013457 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013458 unsigned ExtractedIdx =
13459 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13460 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13461
13462 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13463 return ReplaceInstUsesWith(IE, VecOp);
13464
13465 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +000013466 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013467
13468 // If we are extracting a value from a vector, then inserting it right
13469 // back into the same place, just use the input vector.
13470 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13471 return ReplaceInstUsesWith(IE, VecOp);
13472
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013473 // If this insertelement isn't used by some other insertelement, turn it
13474 // (and any insertelements it points to), into one big shuffle.
13475 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13476 std::vector<Constant*> Mask;
13477 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000013478 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Andersonb99ecca2009-07-30 23:03:37 +000013479 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013480 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000013481 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +000013482 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013483 }
13484 }
13485 }
13486
Eli Friedmanbefee262009-06-06 20:08:03 +000013487 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13488 APInt UndefElts(VWidth, 0);
13489 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13490 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13491 return &IE;
13492
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013493 return 0;
13494}
13495
13496
13497Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13498 Value *LHS = SVI.getOperand(0);
13499 Value *RHS = SVI.getOperand(1);
13500 std::vector<unsigned> Mask = getShuffleMask(&SVI);
13501
13502 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013503
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013504 // Undefined shuffle mask -> undefined value.
13505 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000013506 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000013507
Dan Gohmanda93bbe2008-09-09 18:11:14 +000013508 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000013509
13510 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13511 return 0;
13512
Evan Cheng63295ab2009-02-03 10:05:09 +000013513 APInt UndefElts(VWidth, 0);
13514 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13515 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000013516 LHS = SVI.getOperand(0);
13517 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000013518 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000013519 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013520
13521 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
13522 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13523 if (LHS == RHS || isa<UndefValue>(LHS)) {
13524 if (isa<UndefValue>(LHS) && LHS == RHS) {
13525 // shuffle(undef,undef,mask) -> undef.
13526 return ReplaceInstUsesWith(SVI, LHS);
13527 }
13528
13529 // Remap any references to RHS to use LHS.
13530 std::vector<Constant*> Elts;
13531 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13532 if (Mask[i] >= 2*e)
Owen Anderson35b47072009-08-13 21:58:54 +000013533 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013534 else {
13535 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000013536 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013537 Mask[i] = 2*e; // Turn into undef.
Owen Anderson35b47072009-08-13 21:58:54 +000013538 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanbba96b92008-08-06 18:17:32 +000013539 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000013540 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson35b47072009-08-13 21:58:54 +000013541 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000013542 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013543 }
13544 }
13545 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +000013546 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +000013547 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013548 LHS = SVI.getOperand(0);
13549 RHS = SVI.getOperand(1);
13550 MadeChange = true;
13551 }
13552
13553 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
13554 bool isLHSID = true, isRHSID = true;
13555
13556 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13557 if (Mask[i] >= e*2) continue; // Ignore undef values.
13558 // Is this an identity shuffle of the LHS value?
13559 isLHSID &= (Mask[i] == i);
13560
13561 // Is this an identity shuffle of the RHS value?
13562 isRHSID &= (Mask[i]-e == i);
13563 }
13564
13565 // Eliminate identity shuffles.
13566 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13567 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
13568
13569 // If the LHS is a shufflevector itself, see if we can combine it with this
13570 // one without producing an unusual shuffle. Here we are really conservative:
13571 // we are absolutely afraid of producing a shuffle mask not in the input
13572 // program, because the code gen may not be smart enough to turn a merged
13573 // shuffle into two specific shuffles: it may produce worse code. As such,
13574 // we only merge two shuffles if the result is one of the two input shuffle
13575 // masks. In this case, merging the shuffles just removes one instruction,
13576 // which we know is safe. This is good for things like turning:
13577 // (splat(splat)) -> splat.
13578 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13579 if (isa<UndefValue>(RHS)) {
13580 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13581
David Greeneb736b5d2009-11-16 21:52:23 +000013582 if (LHSMask.size() == Mask.size()) {
13583 std::vector<unsigned> NewMask;
13584 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sandse7f89b02009-11-20 13:19:51 +000013585 if (Mask[i] >= e)
David Greeneb736b5d2009-11-16 21:52:23 +000013586 NewMask.push_back(2*e);
13587 else
13588 NewMask.push_back(LHSMask[Mask[i]]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013589
David Greeneb736b5d2009-11-16 21:52:23 +000013590 // If the result mask is equal to the src shuffle or this
13591 // shuffle mask, do the replacement.
13592 if (NewMask == LHSMask || NewMask == Mask) {
13593 unsigned LHSInNElts =
13594 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13595 getNumElements();
13596 std::vector<Constant*> Elts;
13597 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13598 if (NewMask[i] >= LHSInNElts*2) {
13599 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13600 } else {
13601 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13602 NewMask[i]));
13603 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013604 }
David Greeneb736b5d2009-11-16 21:52:23 +000013605 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13606 LHSSVI->getOperand(1),
13607 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013608 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013609 }
13610 }
13611 }
13612
13613 return MadeChange ? &SVI : 0;
13614}
13615
13616
13617
13618
13619/// TryToSinkInstruction - Try to move the specified instruction from its
13620/// current block into the beginning of DestBlock, which can only happen if it's
13621/// safe to move the instruction past all of the instructions between it and the
13622/// end of its block.
13623static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13624 assert(I->hasOneUse() && "Invariants didn't hold!");
13625
13626 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000013627 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000013628 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013629
13630 // Do not sink alloca instructions out of the entry block.
13631 if (isa<AllocaInst>(I) && I->getParent() ==
13632 &DestBlock->getParent()->getEntryBlock())
13633 return false;
13634
13635 // We can only sink load instructions if there is nothing between the load and
13636 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000013637 if (I->mayReadFromMemory()) {
13638 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013639 Scan != E; ++Scan)
13640 if (Scan->mayWriteToMemory())
13641 return false;
13642 }
13643
Dan Gohman514277c2008-05-23 21:05:58 +000013644 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013645
Dale Johannesen24339f12009-03-03 01:09:07 +000013646 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013647 I->moveBefore(InsertPos);
13648 ++NumSunkInst;
13649 return true;
13650}
13651
13652
13653/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13654/// all reachable code to the worklist.
13655///
13656/// This has a couple of tricks to make the code faster and more powerful. In
13657/// particular, we constant fold and DCE instructions as we go, to avoid adding
13658/// them to the worklist (this significantly speeds up instcombine on code where
13659/// many instructions are dead or constant). Additionally, if we find a branch
13660/// whose condition is a known constant, we only visit the reachable successors.
13661///
Chris Lattnerc4269e52009-10-15 04:59:28 +000013662static bool AddReachableCodeToWorklist(BasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013663 SmallPtrSet<BasicBlock*, 64> &Visited,
13664 InstCombiner &IC,
13665 const TargetData *TD) {
Chris Lattnerc4269e52009-10-15 04:59:28 +000013666 bool MadeIRChange = false;
Chris Lattnera06291a2008-08-15 04:03:01 +000013667 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013668 Worklist.push_back(BB);
Chris Lattnerb5663c72009-10-12 03:58:40 +000013669
13670 std::vector<Instruction*> InstrsForInstCombineWorklist;
13671 InstrsForInstCombineWorklist.reserve(128);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013672
Chris Lattnerc4269e52009-10-15 04:59:28 +000013673 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13674
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013675 while (!Worklist.empty()) {
13676 BB = Worklist.back();
13677 Worklist.pop_back();
13678
13679 // We have now visited this block! If we've already been here, ignore it.
13680 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000013681
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013682 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13683 Instruction *Inst = BBI++;
13684
13685 // DCE instruction if trivially dead.
13686 if (isInstructionTriviallyDead(Inst)) {
13687 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +000013688 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013689 Inst->eraseFromParent();
13690 continue;
13691 }
13692
13693 // ConstantProp instruction if trivially constant.
Chris Lattneree5839b2009-10-15 04:13:44 +000013694 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +000013695 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +000013696 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13697 << *Inst << '\n');
13698 Inst->replaceAllUsesWith(C);
13699 ++NumConstProp;
13700 Inst->eraseFromParent();
13701 continue;
13702 }
Chris Lattnerc4269e52009-10-15 04:59:28 +000013703
13704
13705
13706 if (TD) {
13707 // See if we can constant fold its operands.
13708 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13709 i != e; ++i) {
13710 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13711 if (CE == 0) continue;
13712
13713 // If we already folded this constant, don't try again.
13714 if (!FoldedConstants.insert(CE))
13715 continue;
13716
Chris Lattner6070c012009-11-06 04:27:31 +000013717 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattnerc4269e52009-10-15 04:59:28 +000013718 if (NewC && NewC != CE) {
13719 *i = NewC;
13720 MadeIRChange = true;
13721 }
13722 }
13723 }
13724
Devang Patel794140c2008-11-19 18:56:50 +000013725
Chris Lattnerb5663c72009-10-12 03:58:40 +000013726 InstrsForInstCombineWorklist.push_back(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013727 }
13728
13729 // Recursively visit successors. If this is a branch or switch on a
13730 // constant, only visit the reachable successor.
13731 TerminatorInst *TI = BB->getTerminator();
13732 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13733 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13734 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000013735 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000013736 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013737 continue;
13738 }
13739 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13740 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13741 // See if this is an explicit destination.
13742 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13743 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000013744 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000013745 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013746 continue;
13747 }
13748
13749 // Otherwise it is the default destination.
13750 Worklist.push_back(SI->getSuccessor(0));
13751 continue;
13752 }
13753 }
13754
13755 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13756 Worklist.push_back(TI->getSuccessor(i));
13757 }
Chris Lattnerb5663c72009-10-12 03:58:40 +000013758
13759 // Once we've found all of the instructions to add to instcombine's worklist,
13760 // add them in reverse order. This way instcombine will visit from the top
13761 // of the function down. This jives well with the way that it adds all uses
13762 // of instructions to the worklist after doing a transformation, thus avoiding
13763 // some N^2 behavior in pathological cases.
13764 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13765 InstrsForInstCombineWorklist.size());
Chris Lattnerc4269e52009-10-15 04:59:28 +000013766
13767 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013768}
13769
13770bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner21d79e22009-08-31 06:57:37 +000013771 MadeIRChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013772
Daniel Dunbar005975c2009-07-25 00:23:56 +000013773 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13774 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013775
13776 {
13777 // Do a depth-first traversal of the function, populate the worklist with
13778 // the reachable instructions. Ignore blocks that are not reachable. Keep
13779 // track of which blocks we visit.
13780 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerc4269e52009-10-15 04:59:28 +000013781 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013782
13783 // Do a quick scan over the function. If we find any blocks that are
13784 // unreachable, remove any instructions inside of them. This prevents
13785 // the instcombine code from having to deal with some bad special cases.
13786 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13787 if (!Visited.count(BB)) {
13788 Instruction *Term = BB->getTerminator();
13789 while (Term != BB->begin()) { // Remove instrs bottom-up
13790 BasicBlock::iterator I = Term; --I;
13791
Chris Lattner8a6411c2009-08-23 04:37:46 +000013792 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +000013793 // A debug intrinsic shouldn't force another iteration if we weren't
13794 // going to do one without it.
13795 if (!isa<DbgInfoIntrinsic>(I)) {
13796 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000013797 MadeIRChange = true;
Dale Johannesendf356c62009-03-10 21:19:49 +000013798 }
Devang Patele3829c82009-10-13 22:56:32 +000013799
Devang Patele3829c82009-10-13 22:56:32 +000013800 // If I is not void type then replaceAllUsesWith undef.
13801 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000013802 if (!I->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000013803 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013804 I->eraseFromParent();
13805 }
13806 }
13807 }
13808
Chris Lattner5119c702009-08-30 05:55:36 +000013809 while (!Worklist.isEmpty()) {
13810 Instruction *I = Worklist.RemoveOne();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013811 if (I == 0) continue; // skip null values.
13812
13813 // Check to see if we can DCE the instruction.
13814 if (isInstructionTriviallyDead(I)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000013815 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner3183fb62009-08-30 06:13:40 +000013816 EraseInstFromFunction(*I);
13817 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000013818 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013819 continue;
13820 }
13821
13822 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattneree5839b2009-10-15 04:13:44 +000013823 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +000013824 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +000013825 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013826
Chris Lattneree5839b2009-10-15 04:13:44 +000013827 // Add operands to the worklist.
13828 ReplaceInstUsesWith(*I, C);
13829 ++NumConstProp;
13830 EraseInstFromFunction(*I);
13831 MadeIRChange = true;
13832 continue;
13833 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013834
13835 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000013836 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013837 BasicBlock *BB = I->getParent();
Chris Lattnerf27a0432009-10-14 15:21:58 +000013838 Instruction *UserInst = cast<Instruction>(I->use_back());
13839 BasicBlock *UserParent;
13840
13841 // Get the block the use occurs in.
13842 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13843 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13844 else
13845 UserParent = UserInst->getParent();
13846
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013847 if (UserParent != BB) {
13848 bool UserIsSuccessor = false;
13849 // See if the user is one of our successors.
13850 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13851 if (*SI == UserParent) {
13852 UserIsSuccessor = true;
13853 break;
13854 }
13855
13856 // If the user is one of our immediate successors, and if that successor
13857 // only has us as a predecessors (we'd have to split the critical edge
13858 // otherwise), we can keep going.
Chris Lattnerf27a0432009-10-14 15:21:58 +000013859 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013860 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattner21d79e22009-08-31 06:57:37 +000013861 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013862 }
13863 }
13864
Chris Lattnerc7694852009-08-30 07:44:24 +000013865 // Now that we have an instruction, try combining it to simplify it.
13866 Builder->SetInsertPoint(I->getParent(), I);
13867
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013868#ifndef NDEBUG
13869 std::string OrigI;
13870#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +000013871 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000013872 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13873
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013874 if (Instruction *Result = visit(*I)) {
13875 ++NumCombined;
13876 // Should we replace the old instruction with a new one?
13877 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000013878 DEBUG(errs() << "IC: Old = " << *I << '\n'
13879 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013880
13881 // Everything uses the new instruction now.
13882 I->replaceAllUsesWith(Result);
13883
13884 // Push the new instruction and any users onto the worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +000013885 Worklist.Add(Result);
Chris Lattner4796b622009-08-30 06:22:51 +000013886 Worklist.AddUsersToWorkList(*Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013887
13888 // Move the name to the new instruction first.
13889 Result->takeName(I);
13890
13891 // Insert the new instruction into the basic block...
13892 BasicBlock *InstParent = I->getParent();
13893 BasicBlock::iterator InsertPos = I;
13894
13895 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13896 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13897 ++InsertPos;
13898
13899 InstParent->getInstList().insert(InsertPos, Result);
13900
Chris Lattner3183fb62009-08-30 06:13:40 +000013901 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013902 } else {
13903#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +000013904 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13905 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013906#endif
13907
13908 // If the instruction was modified, it's possible that it is now dead.
13909 // if so, remove it.
13910 if (isInstructionTriviallyDead(I)) {
Chris Lattner3183fb62009-08-30 06:13:40 +000013911 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013912 } else {
Chris Lattner3183fb62009-08-30 06:13:40 +000013913 Worklist.Add(I);
Chris Lattner4796b622009-08-30 06:22:51 +000013914 Worklist.AddUsersToWorkList(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013915 }
13916 }
Chris Lattner21d79e22009-08-31 06:57:37 +000013917 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013918 }
13919 }
13920
Chris Lattner5119c702009-08-30 05:55:36 +000013921 Worklist.Zap();
Chris Lattner21d79e22009-08-31 06:57:37 +000013922 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013923}
13924
13925
13926bool InstCombiner::runOnFunction(Function &F) {
13927 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000013928 Context = &F.getContext();
Chris Lattneree5839b2009-10-15 04:13:44 +000013929 TD = getAnalysisIfAvailable<TargetData>();
13930
Chris Lattnerc7694852009-08-30 07:44:24 +000013931
13932 /// Builder - This is an IRBuilder that automatically inserts new
13933 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +000013934 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattner002e65d2009-11-06 05:59:53 +000013935 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattnerc7694852009-08-30 07:44:24 +000013936 InstCombineIRInserter(Worklist));
13937 Builder = &TheBuilder;
13938
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013939 bool EverMadeChange = false;
13940
13941 // Iterate while there is work to do.
13942 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000013943 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013944 EverMadeChange = true;
Chris Lattnerc7694852009-08-30 07:44:24 +000013945
13946 Builder = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013947 return EverMadeChange;
13948}
13949
13950FunctionPass *llvm::createInstructionCombiningPass() {
13951 return new InstCombiner();
13952}