blob: 59293be4c6706f0404e9a0306b3203a411f86c65 [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
78namespace {
Chris Lattner5119c702009-08-30 05:55:36 +000079 /// InstCombineWorklist - This is the worklist management logic for
80 /// InstCombine.
81 class InstCombineWorklist {
82 SmallVector<Instruction*, 256> Worklist;
83 DenseMap<Instruction*, unsigned> WorklistMap;
84
85 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
86 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
87 public:
88 InstCombineWorklist() {}
89
90 bool isEmpty() const { return Worklist.empty(); }
91
92 /// Add - Add the specified instruction to the worklist if it isn't already
93 /// in it.
94 void Add(Instruction *I) {
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000095 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
96 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner5119c702009-08-30 05:55:36 +000097 Worklist.push_back(I);
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000098 }
Chris Lattner5119c702009-08-30 05:55:36 +000099 }
100
Chris Lattnerc5ad98f2009-08-30 06:27:41 +0000101 void AddValue(Value *V) {
102 if (Instruction *I = dyn_cast<Instruction>(V))
103 Add(I);
104 }
105
Chris Lattnerb5663c72009-10-12 03:58:40 +0000106 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
107 /// which should only be done when the worklist is empty and when the group
108 /// has no duplicates.
109 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
110 assert(Worklist.empty() && "Worklist must be empty to add initial group");
111 Worklist.reserve(NumEntries+16);
112 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
113 for (; NumEntries; --NumEntries) {
114 Instruction *I = List[NumEntries-1];
115 WorklistMap.insert(std::make_pair(I, Worklist.size()));
116 Worklist.push_back(I);
117 }
118 }
119
Chris Lattner3183fb62009-08-30 06:13:40 +0000120 // Remove - remove I from the worklist if it exists.
Chris Lattner5119c702009-08-30 05:55:36 +0000121 void Remove(Instruction *I) {
122 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
123 if (It == WorklistMap.end()) return; // Not in worklist.
124
125 // Don't bother moving everything down, just null out the slot.
126 Worklist[It->second] = 0;
127
128 WorklistMap.erase(It);
129 }
130
131 Instruction *RemoveOne() {
132 Instruction *I = Worklist.back();
133 Worklist.pop_back();
134 WorklistMap.erase(I);
135 return I;
136 }
137
Chris Lattner4796b622009-08-30 06:22:51 +0000138 /// AddUsersToWorkList - When an instruction is simplified, add all users of
139 /// the instruction to the work lists because they might get more simplified
140 /// now.
141 ///
142 void AddUsersToWorkList(Instruction &I) {
143 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
144 UI != UE; ++UI)
145 Add(cast<Instruction>(*UI));
146 }
147
Chris Lattner5119c702009-08-30 05:55:36 +0000148
149 /// Zap - check that the worklist is empty and nuke the backing store for
150 /// the map if it is large.
151 void Zap() {
152 assert(WorklistMap.empty() && "Worklist empty, but map not?");
153
154 // Do an explicit clear, this shrinks the map if needed.
155 WorklistMap.clear();
156 }
157 };
158} // end anonymous namespace.
159
160
161namespace {
Chris Lattnerc7694852009-08-30 07:44:24 +0000162 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
163 /// just like the normal insertion helper, but also adds any new instructions
164 /// to the instcombine worklist.
165 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
166 InstCombineWorklist &Worklist;
167 public:
168 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
169
170 void InsertHelper(Instruction *I, const Twine &Name,
171 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
172 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
173 Worklist.Add(I);
174 }
175 };
176} // end anonymous namespace
177
178
179namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000180 class InstCombiner : public FunctionPass,
181 public InstVisitor<InstCombiner, Instruction*> {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182 TargetData *TD;
183 bool MustPreserveLCSSA;
Chris Lattner21d79e22009-08-31 06:57:37 +0000184 bool MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 public:
Chris Lattner36ec3b42009-08-30 17:53:59 +0000186 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner3183fb62009-08-30 06:13:40 +0000187 InstCombineWorklist Worklist;
188
Chris Lattnerc7694852009-08-30 07:44:24 +0000189 /// Builder - This is an IRBuilder that automatically inserts new
190 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +0000191 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerad7516a2009-08-30 18:50:58 +0000192 BuilderTy *Builder;
Chris Lattnerc7694852009-08-30 07:44:24 +0000193
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194 static char ID; // Pass identification, replacement for typeid
Chris Lattnerc7694852009-08-30 07:44:24 +0000195 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196
Owen Anderson175b6542009-07-22 00:24:57 +0000197 LLVMContext *Context;
198 LLVMContext *getContext() const { return Context; }
Owen Anderson24be4c12009-07-03 00:17:18 +0000199
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200 public:
201 virtual bool runOnFunction(Function &F);
202
203 bool DoOneIteration(Function &F, unsigned ItNum);
204
205 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206 AU.addPreservedID(LCSSAID);
207 AU.setPreservesCFG();
208 }
209
Dan Gohmana80e2712009-07-21 23:21:54 +0000210 TargetData *getTargetData() const { return TD; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211
212 // Visitation implementation - Implement instruction combining for different
213 // instruction types. The semantics are as follows:
214 // Return Value:
215 // null - No change was made
216 // I - Change was made, I is still valid, I may be dead though
217 // otherwise - Change was made, replace I with returned instruction
218 //
219 Instruction *visitAdd(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000220 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner93e6ff92009-11-04 08:05:20 +0000221 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000223 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000225 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000226 Instruction *visitURem(BinaryOperator &I);
227 Instruction *visitSRem(BinaryOperator &I);
228 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000229 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 Instruction *commonRemTransforms(BinaryOperator &I);
231 Instruction *commonIRemTransforms(BinaryOperator &I);
232 Instruction *commonDivTransforms(BinaryOperator &I);
233 Instruction *commonIDivTransforms(BinaryOperator &I);
234 Instruction *visitUDiv(BinaryOperator &I);
235 Instruction *visitSDiv(BinaryOperator &I);
236 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000237 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +0000238 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000240 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner57e66fa2009-07-23 05:46:22 +0000241 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000242 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000243 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244 Instruction *visitOr (BinaryOperator &I);
245 Instruction *visitXor(BinaryOperator &I);
246 Instruction *visitShl(BinaryOperator &I);
247 Instruction *visitAShr(BinaryOperator &I);
248 Instruction *visitLShr(BinaryOperator &I);
249 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000250 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
251 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 Instruction *visitFCmpInst(FCmpInst &I);
253 Instruction *visitICmpInst(ICmpInst &I);
254 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
255 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
256 Instruction *LHS,
257 ConstantInt *RHS);
258 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
259 ConstantInt *DivRHS);
260
Dan Gohman17f46f72009-07-28 01:40:03 +0000261 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 ICmpInst::Predicate Cond, Instruction &I);
263 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
264 BinaryOperator &I);
265 Instruction *commonCastTransforms(CastInst &CI);
266 Instruction *commonIntCastTransforms(CastInst &CI);
267 Instruction *commonPointerCastTransforms(CastInst &CI);
268 Instruction *visitTrunc(TruncInst &CI);
269 Instruction *visitZExt(ZExtInst &CI);
270 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000271 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000273 Instruction *visitFPToUI(FPToUIInst &FI);
274 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275 Instruction *visitUIToFP(CastInst &CI);
276 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000277 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000278 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000279 Instruction *visitBitCast(BitCastInst &CI);
280 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
281 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000282 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman58c09632008-09-16 18:46:06 +0000283 Instruction *visitSelectInst(SelectInst &SI);
284 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000285 Instruction *visitCallInst(CallInst &CI);
286 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner1cd526b2009-11-08 19:23:30 +0000287
288 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 Instruction *visitPHINode(PHINode &PN);
290 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandezb1687302009-10-23 21:09:37 +0000291 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez93946082009-10-24 04:23:03 +0000292 Instruction *visitFree(Instruction &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293 Instruction *visitLoadInst(LoadInst &LI);
294 Instruction *visitStoreInst(StoreInst &SI);
295 Instruction *visitBranchInst(BranchInst &BI);
296 Instruction *visitSwitchInst(SwitchInst &SI);
297 Instruction *visitInsertElementInst(InsertElementInst &IE);
298 Instruction *visitExtractElementInst(ExtractElementInst &EI);
299 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000300 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000301
302 // visitInstruction - Specify what to return for unhandled instructions...
303 Instruction *visitInstruction(Instruction &I) { return 0; }
304
305 private:
306 Instruction *visitCallSite(CallSite CS);
307 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000308 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000309 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
310 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000311 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000312 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
313
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314
315 public:
316 // InsertNewInstBefore - insert an instruction New before instruction Old
317 // in the program. Add the new instruction to the worklist.
318 //
319 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
320 assert(New && New->getParent() == 0 &&
321 "New instruction already inserted into a basic block!");
322 BasicBlock *BB = Old.getParent();
323 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner3183fb62009-08-30 06:13:40 +0000324 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325 return New;
326 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000327
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000328 // ReplaceInstUsesWith - This method is to be used when an instruction is
329 // found to be dead, replacable with another preexisting expression. Here
330 // we add all uses of I to the worklist, replace all uses of I with the new
331 // value, then return I, so that the inst combiner will know that I was
332 // modified.
333 //
334 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner4796b622009-08-30 06:22:51 +0000335 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +0000336
337 // If we are replacing the instruction with itself, this must be in a
338 // segment of unreachable code, so just clobber the instruction.
339 if (&I == V)
340 V = UndefValue::get(I.getType());
341
342 I.replaceAllUsesWith(V);
343 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 }
345
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 // EraseInstFromFunction - When dealing with an instruction that has side
347 // effects or produces a void value, we can't rely on DCE to delete the
348 // instruction. Instead, visit methods should return the value returned by
349 // this function.
350 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez48c3c542009-09-18 22:35:49 +0000351 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner26b7f942009-08-31 05:17:58 +0000352
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000353 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner3183fb62009-08-30 06:13:40 +0000354 // Make sure that we reprocess all operands now that we reduced their
355 // use counts.
Chris Lattnerc5ad98f2009-08-30 06:27:41 +0000356 if (I.getNumOperands() < 8) {
357 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
358 if (Instruction *Op = dyn_cast<Instruction>(*i))
359 Worklist.Add(Op);
360 }
Chris Lattner3183fb62009-08-30 06:13:40 +0000361 Worklist.Remove(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000362 I.eraseFromParent();
Chris Lattner21d79e22009-08-31 06:57:37 +0000363 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000364 return 0; // Don't do anything with FI
365 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000366
367 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
368 APInt &KnownOne, unsigned Depth = 0) const {
369 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
370 }
371
372 bool MaskedValueIsZero(Value *V, const APInt &Mask,
373 unsigned Depth = 0) const {
374 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
375 }
376 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
377 return llvm::ComputeNumSignBits(Op, TD, Depth);
378 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000379
380 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000381
382 /// SimplifyCommutative - This performs a few simplifications for
383 /// commutative operators.
384 bool SimplifyCommutative(BinaryOperator &I);
385
386 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
387 /// most-complex to least-complex order.
388 bool SimplifyCompare(CmpInst &I);
389
Chris Lattner676c78e2009-01-31 08:15:18 +0000390 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
391 /// based on the demanded bits.
392 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
393 APInt& KnownZero, APInt& KnownOne,
394 unsigned Depth);
395 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000397 unsigned Depth=0);
398
399 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
400 /// SimplifyDemandedBits knows about. See if the instruction has any
401 /// properties that allow us to simplify its operands.
402 bool SimplifyDemandedInstructionBits(Instruction &Inst);
403
Evan Cheng63295ab2009-02-03 10:05:09 +0000404 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
405 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000406
Chris Lattnerf7843b72009-09-27 19:57:57 +0000407 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
408 // which has a PHI node as operand #0, see if we can fold the instruction
409 // into the PHI (which is only possible if all operands to the PHI are
410 // constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +0000411 //
412 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
413 // that would normally be unprofitable because they strongly encourage jump
414 // threading.
415 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000416
417 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
418 // operator and they all are only used by the PHI, PHI together their
419 // inputs, and do the operation once, to the result of the PHI.
420 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
421 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000422 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner38751f82009-11-01 20:04:24 +0000423 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000424
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425
426 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
427 ConstantInt *AndRHS, BinaryOperator &TheAnd);
428
429 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
430 bool isSub, Instruction &I);
431 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
432 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandezb1687302009-10-23 21:09:37 +0000433 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434 Instruction *MatchBSwap(BinaryOperator &I);
435 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000436 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000437 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000438
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439
440 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000441
Dan Gohman8fd520a2009-06-15 22:12:54 +0000442 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000443 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000444 unsigned GetOrEnforceKnownAlignment(Value *V,
445 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000446
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000447 };
Chris Lattner5119c702009-08-30 05:55:36 +0000448} // end anonymous namespace
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000449
Dan Gohman089efff2008-05-13 00:00:25 +0000450char InstCombiner::ID = 0;
451static RegisterPass<InstCombiner>
452X("instcombine", "Combine redundant instructions");
453
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454// getComplexity: Assign a complexity or rank value to LLVM Values...
455// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman5d138f92009-08-29 23:39:38 +0000456static unsigned getComplexity(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000457 if (isa<Instruction>(V)) {
Owen Anderson76f49252009-07-13 22:18:28 +0000458 if (BinaryOperator::isNeg(V) ||
459 BinaryOperator::isFNeg(V) ||
Dan Gohman7ce405e2009-06-04 22:49:04 +0000460 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000461 return 3;
462 return 4;
463 }
464 if (isa<Argument>(V)) return 3;
465 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
466}
467
468// isOnlyUse - Return true if this instruction will be deleted if we stop using
469// it.
470static bool isOnlyUse(Value *V) {
471 return V->hasOneUse() || isa<Constant>(V);
472}
473
474// getPromotedType - Return the specified type promoted as it would be to pass
475// though a va_arg area...
476static const Type *getPromotedType(const Type *Ty) {
477 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
478 if (ITy->getBitWidth() < 32)
Owen Anderson35b47072009-08-13 21:58:54 +0000479 return Type::getInt32Ty(Ty->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000480 }
481 return Ty;
482}
483
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000484/// getBitCastOperand - If the specified operand is a CastInst, a constant
485/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
486/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000487static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000488 if (Operator *O = dyn_cast<Operator>(V)) {
489 if (O->getOpcode() == Instruction::BitCast)
490 return O->getOperand(0);
491 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
492 if (GEP->hasAllZeroIndices())
493 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000494 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000495 return 0;
496}
497
498/// This function is a wrapper around CastInst::isEliminableCastPair. It
499/// simply extracts arguments and returns what that function returns.
500static Instruction::CastOps
501isEliminableCastPair(
502 const CastInst *CI, ///< The first cast instruction
503 unsigned opcode, ///< The opcode of the second cast instruction
504 const Type *DstTy, ///< The target type for the second cast instruction
505 TargetData *TD ///< The target data for pointer size
506) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000507
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000508 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
509 const Type *MidTy = CI->getType(); // B from above
510
511 // Get the opcodes of the two Cast instructions
512 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
513 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
514
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000515 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmana80e2712009-07-21 23:21:54 +0000516 DstTy,
Owen Anderson35b47072009-08-13 21:58:54 +0000517 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000518
519 // We don't want to form an inttoptr or ptrtoint that converts to an integer
520 // type that differs from the pointer size.
Owen Anderson35b47072009-08-13 21:58:54 +0000521 if ((Res == Instruction::IntToPtr &&
Dan Gohman033445f2009-08-19 23:38:22 +0000522 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson35b47072009-08-13 21:58:54 +0000523 (Res == Instruction::PtrToInt &&
Dan Gohman033445f2009-08-19 23:38:22 +0000524 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000525 Res = 0;
526
527 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528}
529
530/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
531/// in any code being generated. It does not require codegen if V is simple
532/// enough or if the cast can be folded into other casts.
533static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
534 const Type *Ty, TargetData *TD) {
535 if (V->getType() == Ty || isa<Constant>(V)) return false;
536
537 // If this is another cast that can be eliminated, it isn't codegen either.
538 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000539 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000540 return false;
541 return true;
542}
543
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000544// SimplifyCommutative - This performs a few simplifications for commutative
545// operators:
546//
547// 1. Order operands such that they are listed from right (least complex) to
548// left (most complex). This puts constants before unary operators before
549// binary operators.
550//
551// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
552// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
553//
554bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
555 bool Changed = false;
Dan Gohman5d138f92009-08-29 23:39:38 +0000556 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000557 Changed = !I.swapOperands();
558
559 if (!I.isAssociative()) return Changed;
560 Instruction::BinaryOps Opcode = I.getOpcode();
561 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
562 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
563 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000564 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565 cast<Constant>(I.getOperand(1)),
566 cast<Constant>(Op->getOperand(1)));
567 I.setOperand(0, Op->getOperand(0));
568 I.setOperand(1, Folded);
569 return true;
570 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
571 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
572 isOnlyUse(Op) && isOnlyUse(Op1)) {
573 Constant *C1 = cast<Constant>(Op->getOperand(1));
574 Constant *C2 = cast<Constant>(Op1->getOperand(1));
575
576 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000577 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000578 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 Op1->getOperand(0),
580 Op1->getName(), &I);
Chris Lattner3183fb62009-08-30 06:13:40 +0000581 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000582 I.setOperand(0, New);
583 I.setOperand(1, Folded);
584 return true;
585 }
586 }
587 return Changed;
588}
589
590/// SimplifyCompare - For a CmpInst this function just orders the operands
591/// so that theyare listed from right (least complex) to left (most complex).
592/// This puts constants before unary operators before binary operators.
593bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman5d138f92009-08-29 23:39:38 +0000594 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000595 return false;
596 I.swapOperands();
597 // Compare instructions are not associative so there's nothing else we can do.
598 return true;
599}
600
601// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
602// if the LHS is a constant zero (which is the 'negate' form).
603//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000604static inline Value *dyn_castNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000605 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 return BinaryOperator::getNegArgument(V);
607
608 // Constants can be considered to be negated values if they can be folded.
609 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000610 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000611
612 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
613 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000614 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000615
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616 return 0;
617}
618
Dan Gohman7ce405e2009-06-04 22:49:04 +0000619// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
620// instruction if the LHS is a constant negative zero (which is the 'negate'
621// form).
622//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000623static inline Value *dyn_castFNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000624 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000625 return BinaryOperator::getFNegArgument(V);
626
627 // Constants can be considered to be negated values if they can be folded.
628 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000629 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000630
631 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
632 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000633 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000634
635 return 0;
636}
637
Chris Lattner6e060db2009-10-26 15:40:07 +0000638/// isFreeToInvert - Return true if the specified value is free to invert (apply
639/// ~ to). This happens in cases where the ~ can be eliminated.
640static inline bool isFreeToInvert(Value *V) {
641 // ~(~(X)) -> X.
Evan Cheng5d4a07e2009-10-26 03:51:32 +0000642 if (BinaryOperator::isNot(V))
Chris Lattner6e060db2009-10-26 15:40:07 +0000643 return true;
644
645 // Constants can be considered to be not'ed values.
646 if (isa<ConstantInt>(V))
647 return true;
648
649 // Compares can be inverted if they have a single use.
650 if (CmpInst *CI = dyn_cast<CmpInst>(V))
651 return CI->hasOneUse();
652
653 return false;
654}
655
656static inline Value *dyn_castNotVal(Value *V) {
657 // If this is not(not(x)) don't return that this is a not: we want the two
658 // not's to be folded first.
659 if (BinaryOperator::isNot(V)) {
660 Value *Operand = BinaryOperator::getNotArgument(V);
661 if (!isFreeToInvert(Operand))
662 return Operand;
663 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664
665 // Constants can be considered to be not'ed values...
666 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000667 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000668 return 0;
669}
670
Chris Lattner6e060db2009-10-26 15:40:07 +0000671
672
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673// dyn_castFoldableMul - If this value is a multiply that can be folded into
674// other computations (because it has a constant operand), return the
675// non-constant operand of the multiply, and set CST to point to the multiplier.
676// Otherwise, return null.
677//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000678static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000679 if (V->hasOneUse() && V->getType()->isInteger())
680 if (Instruction *I = dyn_cast<Instruction>(V)) {
681 if (I->getOpcode() == Instruction::Mul)
682 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
683 return I->getOperand(0);
684 if (I->getOpcode() == Instruction::Shl)
685 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
686 // The multiplier is really 1 << CST.
687 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
688 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000689 CST = ConstantInt::get(V->getType()->getContext(),
690 APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691 return I->getOperand(0);
692 }
693 }
694 return 0;
695}
696
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000697/// AddOne - Add one to a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000698static Constant *AddOne(Constant *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000699 return ConstantExpr::getAdd(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000700 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000701}
702/// SubOne - Subtract one from a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000703static Constant *SubOne(ConstantInt *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000704 return ConstantExpr::getSub(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000705 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000707/// MultiplyOverflows - True if the multiply can not be expressed in an int
708/// this size.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000709static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000710 uint32_t W = C1->getBitWidth();
711 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
712 if (sign) {
713 LHSExt.sext(W * 2);
714 RHSExt.sext(W * 2);
715 } else {
716 LHSExt.zext(W * 2);
717 RHSExt.zext(W * 2);
718 }
719
720 APInt MulExt = LHSExt * RHSExt;
721
722 if (sign) {
723 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
724 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
725 return MulExt.slt(Min) || MulExt.sgt(Max);
726 } else
727 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
728}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000729
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000730
731/// ShrinkDemandedConstant - Check to see if the specified operand of the
732/// specified instruction is a constant integer. If so, check to see if there
733/// are any bits set in the constant that are not demanded. If so, shrink the
734/// constant and return true.
735static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000736 APInt Demanded) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000737 assert(I && "No instruction?");
738 assert(OpNo < I->getNumOperands() && "Operand index too large");
739
740 // If the operand is not a constant integer, nothing to do.
741 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
742 if (!OpC) return false;
743
744 // If there are no bits set that aren't demanded, nothing to do.
745 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
746 if ((~Demanded & OpC->getValue()) == 0)
747 return false;
748
749 // This instruction is producing bits that are not demanded. Shrink the RHS.
750 Demanded &= OpC->getValue();
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000751 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752 return true;
753}
754
755// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
756// set of known zero and one bits, compute the maximum and minimum values that
757// could have the specified known zero and known one bits, returning them in
758// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000759static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000760 const APInt& KnownOne,
761 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000762 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
763 KnownZero.getBitWidth() == Min.getBitWidth() &&
764 KnownZero.getBitWidth() == Max.getBitWidth() &&
765 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000766 APInt UnknownBits = ~(KnownZero|KnownOne);
767
768 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
769 // bit if it is unknown.
770 Min = KnownOne;
771 Max = KnownOne|UnknownBits;
772
Dan Gohman7934d592009-04-25 17:12:48 +0000773 if (UnknownBits.isNegative()) { // Sign bit is unknown
774 Min.set(Min.getBitWidth()-1);
775 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000776 }
777}
778
779// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
780// a set of known zero and one bits, compute the maximum and minimum values that
781// could have the specified known zero and known one bits, returning them in
782// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000783static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000784 const APInt &KnownOne,
785 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000786 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
787 KnownZero.getBitWidth() == Min.getBitWidth() &&
788 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000789 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
790 APInt UnknownBits = ~(KnownZero|KnownOne);
791
792 // The minimum value is when the unknown bits are all zeros.
793 Min = KnownOne;
794 // The maximum value is when the unknown bits are all ones.
795 Max = KnownOne|UnknownBits;
796}
797
Chris Lattner676c78e2009-01-31 08:15:18 +0000798/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
799/// SimplifyDemandedBits knows about. See if the instruction has any
800/// properties that allow us to simplify its operands.
801bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000802 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000803 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
804 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
805
806 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
807 KnownZero, KnownOne, 0);
808 if (V == 0) return false;
809 if (V == &Inst) return true;
810 ReplaceInstUsesWith(Inst, V);
811 return true;
812}
813
814/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
815/// specified instruction operand if possible, updating it in place. It returns
816/// true if it made any change and false otherwise.
817bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
818 APInt &KnownZero, APInt &KnownOne,
819 unsigned Depth) {
820 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
821 KnownZero, KnownOne, Depth);
822 if (NewVal == 0) return false;
Dan Gohman3af2d412009-10-05 16:31:55 +0000823 U = NewVal;
Chris Lattner676c78e2009-01-31 08:15:18 +0000824 return true;
825}
826
827
828/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
829/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000830/// that only the bits set in DemandedMask of the result of V are ever used
831/// downstream. Consequently, depending on the mask and V, it may be possible
832/// to replace V with a constant or one of its operands. In such cases, this
833/// function does the replacement and returns true. In all other cases, it
834/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000835/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836/// to be zero in the expression. These are provided to potentially allow the
837/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
838/// the expression. KnownOne and KnownZero always follow the invariant that
839/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
840/// the bits in KnownOne and KnownZero may only be accurate for those bits set
841/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
842/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000843///
844/// This returns null if it did not change anything and it permits no
845/// simplification. This returns V itself if it did some simplification of V's
846/// operands based on the information about what bits are demanded. This returns
847/// some other non-null value if it found out that V is equal to another value
848/// in the context where the specified bits are demanded, but not for all users.
849Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
850 APInt &KnownZero, APInt &KnownOne,
851 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000852 assert(V != 0 && "Null pointer of Value???");
853 assert(Depth <= 6 && "Limit Search Depth");
854 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000855 const Type *VTy = V->getType();
856 assert((TD || !isa<PointerType>(VTy)) &&
857 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000858 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
859 (!VTy->isIntOrIntVector() ||
860 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000861 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000863 "Value *V, DemandedMask, KnownZero and KnownOne "
864 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
866 // We know all of the bits for a constant!
867 KnownOne = CI->getValue() & DemandedMask;
868 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000869 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000870 }
Dan Gohman7934d592009-04-25 17:12:48 +0000871 if (isa<ConstantPointerNull>(V)) {
872 // We know all of the bits for a constant!
873 KnownOne.clear();
874 KnownZero = DemandedMask;
875 return 0;
876 }
877
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000878 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000879 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000880 if (DemandedMask == 0) { // Not demanding any bits from V.
881 if (isa<UndefValue>(V))
882 return 0;
Owen Andersonb99ecca2009-07-30 23:03:37 +0000883 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884 }
885
Chris Lattner08817332009-01-31 08:24:16 +0000886 if (Depth == 6) // Limit search depth.
887 return 0;
888
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000889 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
890 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
891
Dan Gohman7934d592009-04-25 17:12:48 +0000892 Instruction *I = dyn_cast<Instruction>(V);
893 if (!I) {
894 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
895 return 0; // Only analyze instructions.
896 }
897
Chris Lattner08817332009-01-31 08:24:16 +0000898 // If there are multiple uses of this value and we aren't at the root, then
899 // we can't do any simplifications of the operands, because DemandedMask
900 // only reflects the bits demanded by *one* of the users.
901 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000902 // Despite the fact that we can't simplify this instruction in all User's
903 // context, we can at least compute the knownzero/knownone bits, and we can
904 // do simplifications that apply to *just* the one user if we know that
905 // this instruction has a simpler value in that context.
906 if (I->getOpcode() == Instruction::And) {
907 // If either the LHS or the RHS are Zero, the result is zero.
908 ComputeMaskedBits(I->getOperand(1), DemandedMask,
909 RHSKnownZero, RHSKnownOne, Depth+1);
910 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
911 LHSKnownZero, LHSKnownOne, Depth+1);
912
913 // If all of the demanded bits are known 1 on one side, return the other.
914 // These bits cannot contribute to the result of the 'and' in this
915 // context.
916 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
917 (DemandedMask & ~LHSKnownZero))
918 return I->getOperand(0);
919 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
920 (DemandedMask & ~RHSKnownZero))
921 return I->getOperand(1);
922
923 // If all of the demanded bits in the inputs are known zeros, return zero.
924 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000925 return Constant::getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000926
927 } else if (I->getOpcode() == Instruction::Or) {
928 // We can simplify (X|Y) -> X or Y in the user's context if we know that
929 // only bits from X or Y are demanded.
930
931 // If either the LHS or the RHS are One, the result is One.
932 ComputeMaskedBits(I->getOperand(1), DemandedMask,
933 RHSKnownZero, RHSKnownOne, Depth+1);
934 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
935 LHSKnownZero, LHSKnownOne, Depth+1);
936
937 // If all of the demanded bits are known zero on one side, return the
938 // other. These bits cannot contribute to the result of the 'or' in this
939 // context.
940 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
941 (DemandedMask & ~LHSKnownOne))
942 return I->getOperand(0);
943 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
944 (DemandedMask & ~RHSKnownOne))
945 return I->getOperand(1);
946
947 // If all of the potentially set bits on one side are known to be set on
948 // the other side, just use the 'other' side.
949 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
950 (DemandedMask & (~RHSKnownZero)))
951 return I->getOperand(0);
952 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
953 (DemandedMask & (~LHSKnownZero)))
954 return I->getOperand(1);
955 }
956
Chris Lattner08817332009-01-31 08:24:16 +0000957 // Compute the KnownZero/KnownOne bits to simplify things downstream.
958 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
959 return 0;
960 }
961
962 // If this is the root being simplified, allow it to have multiple uses,
963 // just set the DemandedMask to all bits so that we can try to simplify the
964 // operands. This allows visitTruncInst (for example) to simplify the
965 // operand of a trunc without duplicating all the logic below.
966 if (Depth == 0 && !V->hasOneUse())
967 DemandedMask = APInt::getAllOnesValue(BitWidth);
968
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000969 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000970 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000971 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000972 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000973 case Instruction::And:
974 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000975 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
976 RHSKnownZero, RHSKnownOne, Depth+1) ||
977 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000978 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000979 return I;
980 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
981 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982
983 // If all of the demanded bits are known 1 on one side, return the other.
984 // These bits cannot contribute to the result of the 'and'.
985 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
986 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000987 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000988 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
989 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000990 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991
992 // If all of the demanded bits in the inputs are known zeros, return zero.
993 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000994 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000995
996 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000997 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000998 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000999
1000 // Output known-1 bits are only known if set in both the LHS & RHS.
1001 RHSKnownOne &= LHSKnownOne;
1002 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1003 RHSKnownZero |= LHSKnownZero;
1004 break;
1005 case Instruction::Or:
1006 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +00001007 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1008 RHSKnownZero, RHSKnownOne, Depth+1) ||
1009 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001010 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001011 return I;
1012 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1013 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014
1015 // If all of the demanded bits are known zero on one side, return the other.
1016 // These bits cannot contribute to the result of the 'or'.
1017 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1018 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +00001019 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1021 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +00001022 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001023
1024 // If all of the potentially set bits on one side are known to be set on
1025 // the other side, just use the 'other' side.
1026 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1027 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +00001028 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1030 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +00001031 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001032
1033 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001034 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001035 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001036
1037 // Output known-0 bits are only known if clear in both the LHS & RHS.
1038 RHSKnownZero &= LHSKnownZero;
1039 // Output known-1 are known to be set if set in either the LHS | RHS.
1040 RHSKnownOne |= LHSKnownOne;
1041 break;
1042 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +00001043 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1044 RHSKnownZero, RHSKnownOne, Depth+1) ||
1045 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001047 return I;
1048 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1049 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050
1051 // If all of the demanded bits are known zero on one side, return the other.
1052 // These bits cannot contribute to the result of the 'xor'.
1053 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001054 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001055 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001056 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057
1058 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1059 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1060 (RHSKnownOne & LHSKnownOne);
1061 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1062 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1063 (RHSKnownOne & LHSKnownZero);
1064
1065 // If all of the demanded bits are known to be zero on one side or the
1066 // other, turn this into an *inclusive* or.
1067 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneradba7ea2009-08-31 04:36:22 +00001068 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1069 Instruction *Or =
1070 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1071 I->getName());
1072 return InsertNewInstBefore(Or, *I);
1073 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001074
1075 // If all of the demanded bits on one side are known, and all of the set
1076 // bits on that side are also known to be set on the other side, turn this
1077 // into an AND, as we know the bits will be cleared.
1078 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1079 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1080 // all known
1081 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohmancf2c9982009-08-03 22:07:33 +00001082 Constant *AndC = Constant::getIntegerValue(VTy,
1083 ~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001084 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001085 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001086 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087 }
1088 }
1089
1090 // If the RHS is a constant, see if we can simplify it.
1091 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001092 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001093 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094
Chris Lattnereefa89c2009-10-11 22:22:13 +00001095 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1096 // are flipping are known to be set, then the xor is just resetting those
1097 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1098 // simplifying both of them.
1099 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1100 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1101 isa<ConstantInt>(I->getOperand(1)) &&
1102 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1103 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1104 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1105 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1106 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1107
1108 Constant *AndC =
1109 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1110 Instruction *NewAnd =
1111 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1112 InsertNewInstBefore(NewAnd, *I);
1113
1114 Constant *XorC =
1115 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1116 Instruction *NewXor =
1117 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1118 return InsertNewInstBefore(NewXor, *I);
1119 }
1120
1121
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001122 RHSKnownZero = KnownZeroOut;
1123 RHSKnownOne = KnownOneOut;
1124 break;
1125 }
1126 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001127 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1128 RHSKnownZero, RHSKnownOne, Depth+1) ||
1129 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001131 return I;
1132 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1133 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001134
1135 // If the operands are constants, see if we can simplify them.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001136 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1137 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001138 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001139
1140 // Only known if known in both the LHS and RHS.
1141 RHSKnownOne &= LHSKnownOne;
1142 RHSKnownZero &= LHSKnownZero;
1143 break;
1144 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001145 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 DemandedMask.zext(truncBf);
1147 RHSKnownZero.zext(truncBf);
1148 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001149 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001150 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001151 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001152 DemandedMask.trunc(BitWidth);
1153 RHSKnownZero.trunc(BitWidth);
1154 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001155 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001156 break;
1157 }
1158 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001159 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001160 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001161
1162 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1163 if (const VectorType *SrcVTy =
1164 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1165 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1166 // Don't touch a bitcast between vectors of different element counts.
1167 return false;
1168 } else
1169 // Don't touch a scalar-to-vector bitcast.
1170 return false;
1171 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1172 // Don't touch a vector-to-scalar bitcast.
1173 return false;
1174
Chris Lattner676c78e2009-01-31 08:15:18 +00001175 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001176 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001177 return I;
1178 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001179 break;
1180 case Instruction::ZExt: {
1181 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001182 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001183
1184 DemandedMask.trunc(SrcBitWidth);
1185 RHSKnownZero.trunc(SrcBitWidth);
1186 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001187 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001188 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001189 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001190 DemandedMask.zext(BitWidth);
1191 RHSKnownZero.zext(BitWidth);
1192 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001193 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194 // The top bits are known to be zero.
1195 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1196 break;
1197 }
1198 case Instruction::SExt: {
1199 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001200 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201
1202 APInt InputDemandedBits = DemandedMask &
1203 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1204
1205 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1206 // If any of the sign extended bits are demanded, we know that the sign
1207 // bit is demanded.
1208 if ((NewBits & DemandedMask) != 0)
1209 InputDemandedBits.set(SrcBitWidth-1);
1210
1211 InputDemandedBits.trunc(SrcBitWidth);
1212 RHSKnownZero.trunc(SrcBitWidth);
1213 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001214 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001215 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001216 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001217 InputDemandedBits.zext(BitWidth);
1218 RHSKnownZero.zext(BitWidth);
1219 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001220 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001221
1222 // If the sign bit of the input is known set or clear, then we know the
1223 // top bits of the result.
1224
1225 // If the input sign bit is known zero, or if the NewBits are not demanded
1226 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001227 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001228 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001229 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1230 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001231 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1232 RHSKnownOne |= NewBits;
1233 }
1234 break;
1235 }
1236 case Instruction::Add: {
1237 // Figure out what the input bits are. If the top bits of the and result
1238 // are not demanded, then the add doesn't demand them from its input
1239 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001240 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001241
1242 // If there is a constant on the RHS, there are a variety of xformations
1243 // we can do.
1244 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1245 // If null, this should be simplified elsewhere. Some of the xforms here
1246 // won't work if the RHS is zero.
1247 if (RHS->isZero())
1248 break;
1249
1250 // If the top bit of the output is demanded, demand everything from the
1251 // input. Otherwise, we demand all the input bits except NLZ top bits.
1252 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1253
1254 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001255 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001257 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258
1259 // If the RHS of the add has bits set that can't affect the input, reduce
1260 // the constant.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001261 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001262 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001263
1264 // Avoid excess work.
1265 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1266 break;
1267
1268 // Turn it into OR if input bits are zero.
1269 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1270 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001271 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001272 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001273 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 }
1275
1276 // We can say something about the output known-zero and known-one bits,
1277 // depending on potential carries from the input constant and the
1278 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1279 // bits set and the RHS constant is 0x01001, then we know we have a known
1280 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1281
1282 // To compute this, we first compute the potential carry bits. These are
1283 // the bits which may be modified. I'm not aware of a better way to do
1284 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001285 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001286 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1287
1288 // Now that we know which bits have carries, compute the known-1/0 sets.
1289
1290 // Bits are known one if they are known zero in one operand and one in the
1291 // other, and there is no input carry.
1292 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1293 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1294
1295 // Bits are known zero if they are known zero in both operands and there
1296 // is no input carry.
1297 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1298 } else {
1299 // If the high-bits of this ADD are not demanded, then it does not demand
1300 // the high bits of its LHS or RHS.
1301 if (DemandedMask[BitWidth-1] == 0) {
1302 // Right fill the mask of bits for this ADD to demand the most
1303 // significant bit and all those below it.
1304 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001305 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1306 LHSKnownZero, LHSKnownOne, Depth+1) ||
1307 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001308 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001309 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001310 }
1311 }
1312 break;
1313 }
1314 case Instruction::Sub:
1315 // If the high-bits of this SUB are not demanded, then it does not demand
1316 // the high bits of its LHS or RHS.
1317 if (DemandedMask[BitWidth-1] == 0) {
1318 // Right fill the mask of bits for this SUB to demand the most
1319 // significant bit and all those below it.
1320 uint32_t NLZ = DemandedMask.countLeadingZeros();
1321 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001322 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1323 LHSKnownZero, LHSKnownOne, Depth+1) ||
1324 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001326 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001327 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001328 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1329 // the known zeros and ones.
1330 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001331 break;
1332 case Instruction::Shl:
1333 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1334 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1335 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001336 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001337 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001338 return I;
1339 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340 RHSKnownZero <<= ShiftAmt;
1341 RHSKnownOne <<= ShiftAmt;
1342 // low bits known zero.
1343 if (ShiftAmt)
1344 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1345 }
1346 break;
1347 case Instruction::LShr:
1348 // For a logical shift right
1349 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1350 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1351
1352 // Unsigned shift right.
1353 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001354 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001356 return I;
1357 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001358 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1359 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1360 if (ShiftAmt) {
1361 // Compute the new bits that are at the top now.
1362 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1363 RHSKnownZero |= HighBits; // high bits known zero.
1364 }
1365 }
1366 break;
1367 case Instruction::AShr:
1368 // If this is an arithmetic shift right and only the low-bit is set, we can
1369 // always convert this into a logical shr, even if the shift amount is
1370 // variable. The low bit of the shift cannot be an input sign bit unless
1371 // the shift amount is >= the size of the datatype, which is undefined.
1372 if (DemandedMask == 1) {
1373 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001374 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001375 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001376 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001377 }
1378
1379 // If the sign bit is the only bit demanded by this ashr, then there is no
1380 // need to do it, the shift doesn't change the high bit.
1381 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001382 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383
1384 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1385 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1386
1387 // Signed shift right.
1388 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1389 // If any of the "high bits" are demanded, we should set the sign bit as
1390 // demanded.
1391 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1392 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001393 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001394 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001395 return I;
1396 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001397 // Compute the new bits that are at the top now.
1398 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1399 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1400 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1401
1402 // Handle the sign bits.
1403 APInt SignBit(APInt::getSignBit(BitWidth));
1404 // Adjust to where it is now in the mask.
1405 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1406
1407 // If the input sign bit is known to be zero, or if none of the top bits
1408 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001409 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001410 (HighBits & ~DemandedMask) == HighBits) {
1411 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001412 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001413 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001414 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001415 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1416 RHSKnownOne |= HighBits;
1417 }
1418 }
1419 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001420 case Instruction::SRem:
1421 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001422 APInt RA = Rem->getValue().abs();
1423 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001424 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001425 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001426
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001427 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001428 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001429 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001430 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001431 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001432
1433 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1434 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001435
1436 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001437
Chris Lattner676c78e2009-01-31 08:15:18 +00001438 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001439 }
1440 }
1441 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001442 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001443 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1444 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001445 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1446 KnownZero2, KnownOne2, Depth+1) ||
1447 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001448 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001449 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001450
Chris Lattneree5417c2009-01-21 18:09:24 +00001451 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001452 Leaders = std::max(Leaders,
1453 KnownZero2.countLeadingOnes());
1454 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001455 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001456 }
Chris Lattner989ba312008-06-18 04:33:20 +00001457 case Instruction::Call:
1458 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1459 switch (II->getIntrinsicID()) {
1460 default: break;
1461 case Intrinsic::bswap: {
1462 // If the only bits demanded come from one byte of the bswap result,
1463 // just shift the input byte into position to eliminate the bswap.
1464 unsigned NLZ = DemandedMask.countLeadingZeros();
1465 unsigned NTZ = DemandedMask.countTrailingZeros();
1466
1467 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1468 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1469 // have 14 leading zeros, round to 8.
1470 NLZ &= ~7;
1471 NTZ &= ~7;
1472 // If we need exactly one byte, we can do this transformation.
1473 if (BitWidth-NLZ-NTZ == 8) {
1474 unsigned ResultBit = NTZ;
1475 unsigned InputBit = BitWidth-NTZ-8;
1476
1477 // Replace this with either a left or right shift to get the byte into
1478 // the right place.
1479 Instruction *NewVal;
1480 if (InputBit > ResultBit)
1481 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001482 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001483 else
1484 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001485 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001486 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001487 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001488 }
1489
1490 // TODO: Could compute known zero/one bits based on the input.
1491 break;
1492 }
1493 }
1494 }
Chris Lattner4946e222008-06-18 18:11:55 +00001495 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001496 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001497 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001498
1499 // If the client is only demanding bits that we know, return the known
1500 // constant.
Dan Gohmancf2c9982009-08-03 22:07:33 +00001501 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1502 return Constant::getIntegerValue(VTy, RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001503 return false;
1504}
1505
1506
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001507/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001508/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001509/// actually used by the caller. This method analyzes which elements of the
1510/// operand are undef and returns that information in UndefElts.
1511///
1512/// If the information about demanded elements can be used to simplify the
1513/// operation, the operation is simplified, then the resultant value is
1514/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001515Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1516 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001517 unsigned Depth) {
1518 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001519 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001520 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521
1522 if (isa<UndefValue>(V)) {
1523 // If the entire vector is undefined, just return this info.
1524 UndefElts = EltMask;
1525 return 0;
1526 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1527 UndefElts = EltMask;
Owen Andersonb99ecca2009-07-30 23:03:37 +00001528 return UndefValue::get(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001529 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001530
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001531 UndefElts = 0;
1532 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1533 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb99ecca2009-07-30 23:03:37 +00001534 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001535
1536 std::vector<Constant*> Elts;
1537 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001538 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001539 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001540 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001541 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1542 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001543 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001544 } else { // Otherwise, defined.
1545 Elts.push_back(CP->getOperand(i));
1546 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001547
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001548 // If we changed the constant, return it.
Owen Anderson2f422e02009-07-28 21:19:26 +00001549 Constant *NewCP = ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001550 return NewCP != CP ? NewCP : 0;
1551 } else if (isa<ConstantAggregateZero>(V)) {
1552 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1553 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001554
1555 // Check if this is identity. If so, return 0 since we are not simplifying
1556 // anything.
1557 if (DemandedElts == ((1ULL << VWidth) -1))
1558 return 0;
1559
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001560 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonaac28372009-07-31 20:28:14 +00001561 Constant *Zero = Constant::getNullValue(EltTy);
Owen Andersonb99ecca2009-07-30 23:03:37 +00001562 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001563 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001564 for (unsigned i = 0; i != VWidth; ++i) {
1565 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1566 Elts.push_back(Elt);
1567 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001568 UndefElts = DemandedElts ^ EltMask;
Owen Anderson2f422e02009-07-28 21:19:26 +00001569 return ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001570 }
1571
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001572 // Limit search depth.
1573 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001574 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001575
1576 // If multiple users are using the root value, procede with
1577 // simplification conservatively assuming that all elements
1578 // are needed.
1579 if (!V->hasOneUse()) {
1580 // Quit if we find multiple users of a non-root value though.
1581 // They'll be handled when it's their turn to be visited by
1582 // the main instcombine process.
1583 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001584 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001585 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001586
1587 // Conservatively assume that all elements are needed.
1588 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001589 }
1590
1591 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001592 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001593
1594 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001595 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001596 Value *TmpV;
1597 switch (I->getOpcode()) {
1598 default: break;
1599
1600 case Instruction::InsertElement: {
1601 // If this is a variable index, we don't know which element it overwrites.
1602 // demand exactly the same input as we produce.
1603 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1604 if (Idx == 0) {
1605 // Note that we can't propagate undef elt info, because we don't know
1606 // which elt is getting updated.
1607 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1608 UndefElts2, Depth+1);
1609 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1610 break;
1611 }
1612
1613 // If this is inserting an element that isn't demanded, remove this
1614 // insertelement.
1615 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner059cfc72009-08-30 06:20:05 +00001616 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1617 Worklist.Add(I);
1618 return I->getOperand(0);
1619 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001620
1621 // Otherwise, the element inserted overwrites whatever was there, so the
1622 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001623 APInt DemandedElts2 = DemandedElts;
1624 DemandedElts2.clear(IdxNo);
1625 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001626 UndefElts, Depth+1);
1627 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1628
1629 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001630 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001631 break;
1632 }
1633 case Instruction::ShuffleVector: {
1634 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001635 uint64_t LHSVWidth =
1636 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001637 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001638 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001639 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001640 unsigned MaskVal = Shuffle->getMaskValue(i);
1641 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001642 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001643 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001644 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001645 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001646 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001647 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001648 }
1649 }
1650 }
1651
Nate Begemanb4d176f2009-02-11 22:36:25 +00001652 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001653 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001654 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001655 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1656
Nate Begemanb4d176f2009-02-11 22:36:25 +00001657 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001658 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1659 UndefElts3, Depth+1);
1660 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1661
1662 bool NewUndefElts = false;
1663 for (unsigned i = 0; i < VWidth; i++) {
1664 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001665 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001666 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001667 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001668 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001669 NewUndefElts = true;
1670 UndefElts.set(i);
1671 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001672 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001673 if (UndefElts3[MaskVal - LHSVWidth]) {
1674 NewUndefElts = true;
1675 UndefElts.set(i);
1676 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001677 }
1678 }
1679
1680 if (NewUndefElts) {
1681 // Add additional discovered undefs.
1682 std::vector<Constant*> Elts;
1683 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001684 if (UndefElts[i])
Owen Anderson35b47072009-08-13 21:58:54 +00001685 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001686 else
Owen Anderson35b47072009-08-13 21:58:54 +00001687 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001688 Shuffle->getMaskValue(i)));
1689 }
Owen Anderson2f422e02009-07-28 21:19:26 +00001690 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001691 MadeChange = true;
1692 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001693 break;
1694 }
1695 case Instruction::BitCast: {
1696 // Vector->vector casts only.
1697 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1698 if (!VTy) break;
1699 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001700 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001701 unsigned Ratio;
1702
1703 if (VWidth == InVWidth) {
1704 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1705 // elements as are demanded of us.
1706 Ratio = 1;
1707 InputDemandedElts = DemandedElts;
1708 } else if (VWidth > InVWidth) {
1709 // Untested so far.
1710 break;
1711
1712 // If there are more elements in the result than there are in the source,
1713 // then an input element is live if any of the corresponding output
1714 // elements are live.
1715 Ratio = VWidth/InVWidth;
1716 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001717 if (DemandedElts[OutIdx])
1718 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001719 }
1720 } else {
1721 // Untested so far.
1722 break;
1723
1724 // If there are more elements in the source than there are in the result,
1725 // then an input element is live if the corresponding output element is
1726 // live.
1727 Ratio = InVWidth/VWidth;
1728 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001729 if (DemandedElts[InIdx/Ratio])
1730 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001731 }
1732
1733 // div/rem demand all inputs, because they don't want divide by zero.
1734 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1735 UndefElts2, Depth+1);
1736 if (TmpV) {
1737 I->setOperand(0, TmpV);
1738 MadeChange = true;
1739 }
1740
1741 UndefElts = UndefElts2;
1742 if (VWidth > InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001743 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001744 // If there are more elements in the result than there are in the source,
1745 // then an output element is undef if the corresponding input element is
1746 // undef.
1747 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001748 if (UndefElts2[OutIdx/Ratio])
1749 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001750 } else if (VWidth < InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001751 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001752 // If there are more elements in the source than there are in the result,
1753 // then a result element is undef if all of the corresponding input
1754 // elements are undef.
1755 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1756 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001757 if (!UndefElts2[InIdx]) // Not undef?
1758 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001759 }
1760 break;
1761 }
1762 case Instruction::And:
1763 case Instruction::Or:
1764 case Instruction::Xor:
1765 case Instruction::Add:
1766 case Instruction::Sub:
1767 case Instruction::Mul:
1768 // div/rem demand all inputs, because they don't want divide by zero.
1769 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1770 UndefElts, Depth+1);
1771 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1772 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1773 UndefElts2, Depth+1);
1774 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1775
1776 // Output elements are undefined if both are undefined. Consider things
1777 // like undef&0. The result is known zero, not undef.
1778 UndefElts &= UndefElts2;
1779 break;
1780
1781 case Instruction::Call: {
1782 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1783 if (!II) break;
1784 switch (II->getIntrinsicID()) {
1785 default: break;
1786
1787 // Binary vector operations that work column-wise. A dest element is a
1788 // function of the corresponding input elements from the two inputs.
1789 case Intrinsic::x86_sse_sub_ss:
1790 case Intrinsic::x86_sse_mul_ss:
1791 case Intrinsic::x86_sse_min_ss:
1792 case Intrinsic::x86_sse_max_ss:
1793 case Intrinsic::x86_sse2_sub_sd:
1794 case Intrinsic::x86_sse2_mul_sd:
1795 case Intrinsic::x86_sse2_min_sd:
1796 case Intrinsic::x86_sse2_max_sd:
1797 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1798 UndefElts, Depth+1);
1799 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1800 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1801 UndefElts2, Depth+1);
1802 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1803
1804 // If only the low elt is demanded and this is a scalarizable intrinsic,
1805 // scalarize it now.
1806 if (DemandedElts == 1) {
1807 switch (II->getIntrinsicID()) {
1808 default: break;
1809 case Intrinsic::x86_sse_sub_ss:
1810 case Intrinsic::x86_sse_mul_ss:
1811 case Intrinsic::x86_sse2_sub_sd:
1812 case Intrinsic::x86_sse2_mul_sd:
1813 // TODO: Lower MIN/MAX/ABS/etc
1814 Value *LHS = II->getOperand(1);
1815 Value *RHS = II->getOperand(2);
1816 // Extract the element as scalars.
Eric Christopher1ba36872009-07-25 02:28:41 +00001817 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001818 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christopher1ba36872009-07-25 02:28:41 +00001819 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001820 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001821
1822 switch (II->getIntrinsicID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001823 default: llvm_unreachable("Case stmts out of sync!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001824 case Intrinsic::x86_sse_sub_ss:
1825 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001826 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001827 II->getName()), *II);
1828 break;
1829 case Intrinsic::x86_sse_mul_ss:
1830 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001831 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001832 II->getName()), *II);
1833 break;
1834 }
1835
1836 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001837 InsertElementInst::Create(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001838 UndefValue::get(II->getType()), TmpV,
Owen Anderson35b47072009-08-13 21:58:54 +00001839 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001840 InsertNewInstBefore(New, *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001841 return New;
1842 }
1843 }
1844
1845 // Output elements are undefined if both are undefined. Consider things
1846 // like undef&0. The result is known zero, not undef.
1847 UndefElts &= UndefElts2;
1848 break;
1849 }
1850 break;
1851 }
1852 }
1853 return MadeChange ? I : 0;
1854}
1855
Dan Gohman5d56fd42008-05-19 22:14:15 +00001856
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001857/// AssociativeOpt - Perform an optimization on an associative operator. This
1858/// function is designed to check a chain of associative operators for a
1859/// potential to apply a certain optimization. Since the optimization may be
1860/// applicable if the expression was reassociated, this checks the chain, then
1861/// reassociates the expression as necessary to expose the optimization
1862/// opportunity. This makes use of a special Functor, which must define
1863/// 'shouldApply' and 'apply' methods.
1864///
1865template<typename Functor>
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001866static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001867 unsigned Opcode = Root.getOpcode();
1868 Value *LHS = Root.getOperand(0);
1869
1870 // Quick check, see if the immediate LHS matches...
1871 if (F.shouldApply(LHS))
1872 return F.apply(Root);
1873
1874 // Otherwise, if the LHS is not of the same opcode as the root, return.
1875 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1876 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1877 // Should we apply this transform to the RHS?
1878 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1879
1880 // If not to the RHS, check to see if we should apply to the LHS...
1881 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1882 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1883 ShouldApply = true;
1884 }
1885
1886 // If the functor wants to apply the optimization to the RHS of LHSI,
1887 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1888 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001889 // Now all of the instructions are in the current basic block, go ahead
1890 // and perform the reassociation.
1891 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1892
1893 // First move the selected RHS to the LHS of the root...
1894 Root.setOperand(0, LHSI->getOperand(1));
1895
1896 // Make what used to be the LHS of the root be the user of the root...
1897 Value *ExtraOperand = TmpLHSI->getOperand(1);
1898 if (&Root == TmpLHSI) {
Owen Andersonaac28372009-07-31 20:28:14 +00001899 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001900 return 0;
1901 }
1902 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1903 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001904 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001905 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001906 ARI = Root;
1907
1908 // Now propagate the ExtraOperand down the chain of instructions until we
1909 // get to LHSI.
1910 while (TmpLHSI != LHSI) {
1911 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1912 // Move the instruction to immediately before the chain we are
1913 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001914 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001915 ARI = NextLHSI;
1916
1917 Value *NextOp = NextLHSI->getOperand(1);
1918 NextLHSI->setOperand(1, ExtraOperand);
1919 TmpLHSI = NextLHSI;
1920 ExtraOperand = NextOp;
1921 }
1922
1923 // Now that the instructions are reassociated, have the functor perform
1924 // the transformation...
1925 return F.apply(Root);
1926 }
1927
1928 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1929 }
1930 return 0;
1931}
1932
Dan Gohman089efff2008-05-13 00:00:25 +00001933namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001934
Nick Lewycky27f6c132008-05-23 04:34:58 +00001935// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001936struct AddRHS {
1937 Value *RHS;
Dan Gohmancdff2122009-08-12 16:23:25 +00001938 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001939 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1940 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001941 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001942 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001943 }
1944};
1945
1946// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1947// iff C1&C2 == 0
1948struct AddMaskingAnd {
1949 Constant *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00001950 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001951 bool shouldApply(Value *LHS) const {
1952 ConstantInt *C1;
Dan Gohmancdff2122009-08-12 16:23:25 +00001953 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Anderson02b48c32009-07-29 18:55:55 +00001954 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001955 }
1956 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001957 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001958 }
1959};
1960
Dan Gohman089efff2008-05-13 00:00:25 +00001961}
1962
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001963static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1964 InstCombiner *IC) {
Chris Lattner78628292009-08-30 19:47:22 +00001965 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattnerd6164c22009-08-30 20:01:10 +00001966 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001967
1968 // Figure out if the constant is the left or the right argument.
1969 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1970 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1971
1972 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1973 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +00001974 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1975 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001976 }
1977
1978 Value *Op0 = SO, *Op1 = ConstOperand;
1979 if (!ConstIsRHS)
1980 std::swap(Op0, Op1);
Chris Lattnerc7694852009-08-30 07:44:24 +00001981
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001982 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattnerc7694852009-08-30 07:44:24 +00001983 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1984 SO->getName()+".op");
1985 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1986 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1987 SO->getName()+".cmp");
1988 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1989 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1990 SO->getName()+".cmp");
1991 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001992}
1993
1994// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1995// constant as the other operand, try to fold the binary operator into the
1996// select arguments. This also works for Cast instructions, which obviously do
1997// not have a second operand.
1998static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1999 InstCombiner *IC) {
2000 // Don't modify shared select instructions
2001 if (!SI->hasOneUse()) return 0;
2002 Value *TV = SI->getOperand(1);
2003 Value *FV = SI->getOperand(2);
2004
2005 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2006 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson35b47072009-08-13 21:58:54 +00002007 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002008
2009 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2010 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2011
Gabor Greifd6da1d02008-04-06 20:25:17 +00002012 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2013 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002014 }
2015 return 0;
2016}
2017
2018
Chris Lattnerf7843b72009-09-27 19:57:57 +00002019/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2020/// has a PHI node as operand #0, see if we can fold the instruction into the
2021/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +00002022///
2023/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2024/// that would normally be unprofitable because they strongly encourage jump
2025/// threading.
2026Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2027 bool AllowAggressive) {
2028 AllowAggressive = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002029 PHINode *PN = cast<PHINode>(I.getOperand(0));
2030 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner9b61abd2009-09-27 20:46:36 +00002031 if (NumPHIValues == 0 ||
2032 // We normally only transform phis with a single use, unless we're trying
2033 // hard to make jump threading happen.
2034 (!PN->hasOneUse() && !AllowAggressive))
2035 return 0;
2036
2037
Chris Lattnerf7843b72009-09-27 19:57:57 +00002038 // Check to see if all of the operands of the PHI are simple constants
2039 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002040 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2041 // bail out. We don't do arbitrary constant expressions here because moving
2042 // their computation can be expensive without a cost model.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002043 BasicBlock *NonConstBB = 0;
2044 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattnerf7843b72009-09-27 19:57:57 +00002045 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2046 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002047 if (NonConstBB) return 0; // More than one non-const value.
2048 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2049 NonConstBB = PN->getIncomingBlock(i);
2050
2051 // If the incoming non-constant value is in I's block, we have an infinite
2052 // loop.
2053 if (NonConstBB == I.getParent())
2054 return 0;
2055 }
2056
2057 // If there is exactly one non-constant value, we can insert a copy of the
2058 // operation in that block. However, if this is a critical edge, we would be
2059 // inserting the computation one some other paths (e.g. inside a loop). Only
2060 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9b61abd2009-09-27 20:46:36 +00002061 if (NonConstBB != 0 && !AllowAggressive) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002062 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2063 if (!BI || !BI->isUnconditional()) return 0;
2064 }
2065
2066 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002067 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002068 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner3980f9b2009-10-21 23:41:58 +00002069 InsertNewInstBefore(NewPN, *PN);
2070 NewPN->takeName(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002071
2072 // Next, add all of the operands to the PHI.
Chris Lattnerf7843b72009-09-27 19:57:57 +00002073 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2074 // We only currently try to fold the condition of a select when it is a phi,
2075 // not the true/false values.
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002076 Value *TrueV = SI->getTrueValue();
2077 Value *FalseV = SI->getFalseValue();
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002078 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerf7843b72009-09-27 19:57:57 +00002079 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002080 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002081 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2082 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002083 Value *InV = 0;
2084 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002085 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerf7843b72009-09-27 19:57:57 +00002086 } else {
2087 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002088 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2089 FalseVInPred,
Chris Lattnerf7843b72009-09-27 19:57:57 +00002090 "phitmp", NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +00002091 Worklist.Add(cast<Instruction>(InV));
Chris Lattnerf7843b72009-09-27 19:57:57 +00002092 }
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002093 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002094 }
2095 } else if (I.getNumOperands() == 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002096 Constant *C = cast<Constant>(I.getOperand(1));
2097 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002098 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002099 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2100 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +00002101 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002102 else
Owen Anderson02b48c32009-07-29 18:55:55 +00002103 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002104 } else {
2105 assert(PN->getIncomingBlock(i) == NonConstBB);
2106 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002107 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002108 PN->getIncomingValue(i), C, "phitmp",
2109 NonConstBB->getTerminator());
2110 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +00002111 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002112 CI->getPredicate(),
2113 PN->getIncomingValue(i), C, "phitmp",
2114 NonConstBB->getTerminator());
2115 else
Edwin Törökbd448e32009-07-14 16:55:14 +00002116 llvm_unreachable("Unknown binop!");
Chris Lattner3980f9b2009-10-21 23:41:58 +00002117
2118 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002119 }
2120 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2121 }
2122 } else {
2123 CastInst *CI = cast<CastInst>(&I);
2124 const Type *RetTy = CI->getType();
2125 for (unsigned i = 0; i != NumPHIValues; ++i) {
2126 Value *InV;
2127 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002128 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002129 } else {
2130 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002131 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002132 I.getType(), "phitmp",
2133 NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +00002134 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002135 }
2136 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2137 }
2138 }
2139 return ReplaceInstUsesWith(I, NewPN);
2140}
2141
Chris Lattner55476162008-01-29 06:52:45 +00002142
Chris Lattner3554f972008-05-20 05:46:13 +00002143/// WillNotOverflowSignedAdd - Return true if we can prove that:
2144/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2145/// This basically requires proving that the add in the original type would not
2146/// overflow to change the sign bit or have a carry out.
2147bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2148 // There are different heuristics we can use for this. Here are some simple
2149 // ones.
2150
2151 // Add has the property that adding any two 2's complement numbers can only
2152 // have one carry bit which can change a sign. As such, if LHS and RHS each
2153 // have at least two sign bits, we know that the addition of the two values will
2154 // sign extend fine.
2155 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2156 return true;
2157
2158
2159 // If one of the operands only has one non-zero bit, and if the other operand
2160 // has a known-zero bit in a more significant place than it (not including the
2161 // sign bit) the ripple may go up to and fill the zero, but won't change the
2162 // sign. For example, (X & ~4) + 1.
2163
2164 // TODO: Implement.
2165
2166 return false;
2167}
2168
Chris Lattner55476162008-01-29 06:52:45 +00002169
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002170Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2171 bool Changed = SimplifyCommutative(I);
2172 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2173
2174 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2175 // X + undef -> undef
2176 if (isa<UndefValue>(RHS))
2177 return ReplaceInstUsesWith(I, RHS);
2178
2179 // X + 0 --> X
Dan Gohman7ce405e2009-06-04 22:49:04 +00002180 if (RHSC->isNullValue())
2181 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002182
2183 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2184 // X + (signbit) --> X ^ signbit
2185 const APInt& Val = CI->getValue();
2186 uint32_t BitWidth = Val.getBitWidth();
2187 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002188 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002189
2190 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2191 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002192 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002193 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002194
Eli Friedmana21526d2009-07-13 22:27:52 +00002195 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +00002196 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson35b47072009-08-13 21:58:54 +00002197 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002198 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002199 }
2200
2201 if (isa<PHINode>(LHS))
2202 if (Instruction *NV = FoldOpIntoPhi(I))
2203 return NV;
2204
2205 ConstantInt *XorRHS = 0;
2206 Value *XorLHS = 0;
2207 if (isa<ConstantInt>(RHSC) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002208 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002209 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002210 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2211
2212 uint32_t Size = TySizeBits / 2;
2213 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2214 APInt CFF80Val(-C0080Val);
2215 do {
2216 if (TySizeBits > Size) {
2217 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2218 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2219 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2220 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2221 // This is a sign extend if the top bits are known zero.
2222 if (!MaskedValueIsZero(XorLHS,
2223 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2224 Size = 0; // Not a sign ext, but can't be any others either.
2225 break;
2226 }
2227 }
2228 Size >>= 1;
2229 C0080Val = APIntOps::lshr(C0080Val, Size);
2230 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2231 } while (Size >= 1);
2232
2233 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002234 // with funny bit widths then this switch statement should be removed. It
2235 // is just here to get the size of the "middle" type back up to something
2236 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002237 const Type *MiddleType = 0;
2238 switch (Size) {
2239 default: break;
Owen Anderson35b47072009-08-13 21:58:54 +00002240 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2241 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2242 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002243 }
2244 if (MiddleType) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002245 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002246 return new SExtInst(NewTrunc, I.getType(), I.getName());
2247 }
2248 }
2249 }
2250
Owen Anderson35b47072009-08-13 21:58:54 +00002251 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002252 return BinaryOperator::CreateXor(LHS, RHS);
2253
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002254 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002255 if (I.getType()->isInteger()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00002256 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Anderson24be4c12009-07-03 00:17:18 +00002257 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002258
2259 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2260 if (RHSI->getOpcode() == Instruction::Sub)
2261 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2262 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2263 }
2264 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2265 if (LHSI->getOpcode() == Instruction::Sub)
2266 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2267 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2268 }
2269 }
2270
2271 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002272 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002273 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002274 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002275 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002276 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohmancdff2122009-08-12 16:23:25 +00002277 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002278 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002279 }
2280
Gabor Greifa645dd32008-05-16 19:29:10 +00002281 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002282 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002283
2284 // A + -B --> A - B
2285 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002286 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002287 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002288
2289
2290 ConstantInt *C2;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002291 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002292 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002293 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002294
2295 // X*C1 + X*C2 --> X * (C1+C2)
2296 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002297 if (X == dyn_castFoldableMul(RHS, C1))
Owen Anderson02b48c32009-07-29 18:55:55 +00002298 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002299 }
2300
2301 // X + X*C --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002302 if (dyn_castFoldableMul(RHS, C2) == LHS)
2303 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002304
2305 // X + ~X --> -1 since ~X = -X-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002306 if (dyn_castNotVal(LHS) == RHS ||
2307 dyn_castNotVal(RHS) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +00002308 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002309
2310
2311 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00002312 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2313 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002314 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002315
2316 // A+B --> A|B iff A and B have no bits set in common.
2317 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2318 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2319 APInt LHSKnownOne(IT->getBitWidth(), 0);
2320 APInt LHSKnownZero(IT->getBitWidth(), 0);
2321 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2322 if (LHSKnownZero != 0) {
2323 APInt RHSKnownOne(IT->getBitWidth(), 0);
2324 APInt RHSKnownZero(IT->getBitWidth(), 0);
2325 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2326
2327 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002328 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002329 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002330 }
2331 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002332
Nick Lewycky83598a72008-02-03 07:42:09 +00002333 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002334 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002335 Value *W, *X, *Y, *Z;
Dan Gohmancdff2122009-08-12 16:23:25 +00002336 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2337 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002338 if (W != Y) {
2339 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002340 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002341 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002342 std::swap(W, X);
2343 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002344 std::swap(Y, Z);
2345 std::swap(W, X);
2346 }
2347 }
2348
2349 if (W == Y) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002350 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002351 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002352 }
2353 }
2354 }
2355
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002356 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2357 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002358 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002359 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002360
2361 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002362 if (LHS->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002363 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002364 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002365 if (Anded == CRHS) {
2366 // See if all bits from the first bit set in the Add RHS up are included
2367 // in the mask. First, get the rightmost bit.
2368 const APInt& AddRHSV = CRHS->getValue();
2369
2370 // Form a mask of all bits from the lowest bit added through the top.
2371 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2372
2373 // See if the and mask includes all of these bits.
2374 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2375
2376 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2377 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattnerc7694852009-08-30 07:44:24 +00002378 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002379 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002380 }
2381 }
2382 }
2383
2384 // Try to fold constant add into select arguments.
2385 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2386 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2387 return R;
2388 }
2389
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002390 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002391 {
2392 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002393 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002394 if (!SI) {
2395 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002396 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002397 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002398 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002399 Value *TV = SI->getTrueValue();
2400 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002401 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002402
2403 // Can we fold the add into the argument of the select?
2404 // We check both true and false select arguments for a matching subtract.
Dan Gohmancdff2122009-08-12 16:23:25 +00002405 if (match(FV, m_Zero()) &&
2406 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002407 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002408 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohmancdff2122009-08-12 16:23:25 +00002409 if (match(TV, m_Zero()) &&
2410 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002411 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002412 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002413 }
2414 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002415
Chris Lattner3554f972008-05-20 05:46:13 +00002416 // Check for (add (sext x), y), see if we can merge this into an
2417 // integer add followed by a sext.
2418 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2419 // (add (sext x), cst) --> (sext (add x, cst'))
2420 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2421 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002422 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002423 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002424 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002425 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2426 // Insert the new, smaller add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002427 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2428 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002429 return new SExtInst(NewAdd, I.getType());
2430 }
2431 }
2432
2433 // (add (sext x), (sext y)) --> (sext (add int x, y))
2434 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2435 // Only do this if x/y have the same type, if at last one of them has a
2436 // single use (so we don't increase the number of sexts), and if the
2437 // integer add will not overflow.
2438 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2439 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2440 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2441 RHSConv->getOperand(0))) {
2442 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002443 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2444 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002445 return new SExtInst(NewAdd, I.getType());
2446 }
2447 }
2448 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002449
2450 return Changed ? &I : 0;
2451}
2452
2453Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2454 bool Changed = SimplifyCommutative(I);
2455 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2456
2457 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2458 // X + 0 --> X
2459 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +00002460 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002461 (I.getType())->getValueAPF()))
2462 return ReplaceInstUsesWith(I, LHS);
2463 }
2464
2465 if (isa<PHINode>(LHS))
2466 if (Instruction *NV = FoldOpIntoPhi(I))
2467 return NV;
2468 }
2469
2470 // -A + B --> B - A
2471 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002472 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002473 return BinaryOperator::CreateFSub(RHS, LHSV);
2474
2475 // A + -B --> A - B
2476 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002477 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002478 return BinaryOperator::CreateFSub(LHS, V);
2479
2480 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2481 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2482 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2483 return ReplaceInstUsesWith(I, LHS);
2484
Chris Lattner3554f972008-05-20 05:46:13 +00002485 // Check for (add double (sitofp x), y), see if we can merge this into an
2486 // integer add followed by a promotion.
2487 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2488 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2489 // ... if the constant fits in the integer value. This is useful for things
2490 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2491 // requires a constant pool load, and generally allows the add to be better
2492 // instcombined.
2493 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2494 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002495 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002496 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002497 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002498 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2499 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002500 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2501 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002502 return new SIToFPInst(NewAdd, I.getType());
2503 }
2504 }
2505
2506 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2507 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2508 // Only do this if x/y have the same type, if at last one of them has a
2509 // single use (so we don't increase the number of int->fp conversions),
2510 // and if the integer add will not overflow.
2511 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2512 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2513 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2514 RHSConv->getOperand(0))) {
2515 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002516 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner93e6ff92009-11-04 08:05:20 +00002517 RHSConv->getOperand(0),"addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002518 return new SIToFPInst(NewAdd, I.getType());
2519 }
2520 }
2521 }
2522
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002523 return Changed ? &I : 0;
2524}
2525
Chris Lattner93e6ff92009-11-04 08:05:20 +00002526
2527/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2528/// code necessary to compute the offset from the base pointer (without adding
2529/// in the base pointer). Return the result as a signed integer of intptr size.
2530static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2531 TargetData &TD = *IC.getTargetData();
2532 gep_type_iterator GTI = gep_type_begin(GEP);
2533 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2534 Value *Result = Constant::getNullValue(IntPtrTy);
2535
2536 // Build a mask for high order bits.
2537 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2538 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2539
2540 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2541 ++i, ++GTI) {
2542 Value *Op = *i;
2543 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2544 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2545 if (OpC->isZero()) continue;
2546
2547 // Handle a struct index, which adds its field offset to the pointer.
2548 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2549 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2550
2551 Result = IC.Builder->CreateAdd(Result,
2552 ConstantInt::get(IntPtrTy, Size),
2553 GEP->getName()+".offs");
2554 continue;
2555 }
2556
2557 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2558 Constant *OC =
2559 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2560 Scale = ConstantExpr::getMul(OC, Scale);
2561 // Emit an add instruction.
2562 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2563 continue;
2564 }
2565 // Convert to correct type.
2566 if (Op->getType() != IntPtrTy)
2567 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2568 if (Size != 1) {
2569 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2570 // We'll let instcombine(mul) convert this to a shl if possible.
2571 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2572 }
2573
2574 // Emit an add instruction.
2575 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2576 }
2577 return Result;
2578}
2579
2580
2581/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2582/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2583/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2584/// be complex, and scales are involved. The above expression would also be
2585/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2586/// This later form is less amenable to optimization though, and we are allowed
2587/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2588///
2589/// If we can't emit an optimized form for this expression, this returns null.
2590///
2591static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2592 InstCombiner &IC) {
2593 TargetData &TD = *IC.getTargetData();
2594 gep_type_iterator GTI = gep_type_begin(GEP);
2595
2596 // Check to see if this gep only has a single variable index. If so, and if
2597 // any constant indices are a multiple of its scale, then we can compute this
2598 // in terms of the scale of the variable index. For example, if the GEP
2599 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2600 // because the expression will cross zero at the same point.
2601 unsigned i, e = GEP->getNumOperands();
2602 int64_t Offset = 0;
2603 for (i = 1; i != e; ++i, ++GTI) {
2604 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2605 // Compute the aggregate offset of constant indices.
2606 if (CI->isZero()) continue;
2607
2608 // Handle a struct index, which adds its field offset to the pointer.
2609 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2610 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2611 } else {
2612 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2613 Offset += Size*CI->getSExtValue();
2614 }
2615 } else {
2616 // Found our variable index.
2617 break;
2618 }
2619 }
2620
2621 // If there are no variable indices, we must have a constant offset, just
2622 // evaluate it the general way.
2623 if (i == e) return 0;
2624
2625 Value *VariableIdx = GEP->getOperand(i);
2626 // Determine the scale factor of the variable element. For example, this is
2627 // 4 if the variable index is into an array of i32.
2628 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2629
2630 // Verify that there are no other variable indices. If so, emit the hard way.
2631 for (++i, ++GTI; i != e; ++i, ++GTI) {
2632 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2633 if (!CI) return 0;
2634
2635 // Compute the aggregate offset of constant indices.
2636 if (CI->isZero()) continue;
2637
2638 // Handle a struct index, which adds its field offset to the pointer.
2639 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2640 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2641 } else {
2642 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2643 Offset += Size*CI->getSExtValue();
2644 }
2645 }
2646
2647 // Okay, we know we have a single variable index, which must be a
2648 // pointer/array/vector index. If there is no offset, life is simple, return
2649 // the index.
2650 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2651 if (Offset == 0) {
2652 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2653 // we don't need to bother extending: the extension won't affect where the
2654 // computation crosses zero.
2655 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2656 VariableIdx = new TruncInst(VariableIdx,
2657 TD.getIntPtrType(VariableIdx->getContext()),
2658 VariableIdx->getName(), &I);
2659 return VariableIdx;
2660 }
2661
2662 // Otherwise, there is an index. The computation we will do will be modulo
2663 // the pointer size, so get it.
2664 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2665
2666 Offset &= PtrSizeMask;
2667 VariableScale &= PtrSizeMask;
2668
2669 // To do this transformation, any constant index must be a multiple of the
2670 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2671 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2672 // multiple of the variable scale.
2673 int64_t NewOffs = Offset / (int64_t)VariableScale;
2674 if (Offset != NewOffs*(int64_t)VariableScale)
2675 return 0;
2676
2677 // Okay, we can do this evaluation. Start by converting the index to intptr.
2678 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2679 if (VariableIdx->getType() != IntPtrTy)
2680 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2681 true /*SExt*/,
2682 VariableIdx->getName(), &I);
2683 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2684 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2685}
2686
2687
2688/// Optimize pointer differences into the same array into a size. Consider:
2689/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2690/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2691///
2692Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2693 const Type *Ty) {
2694 assert(TD && "Must have target data info for this");
2695
2696 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2697 // this.
2698 bool Swapped;
2699 GetElementPtrInst *GEP;
2700
2701 if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2702 GEP->getOperand(0) == RHS)
2703 Swapped = false;
2704 else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2705 GEP->getOperand(0) == LHS)
2706 Swapped = true;
2707 else
2708 return 0;
2709
2710 // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2711
2712 // Emit the offset of the GEP and an intptr_t.
2713 Value *Result = EmitGEPOffset(GEP, *this);
2714
2715 // If we have p - gep(p, ...) then we have to negate the result.
2716 if (Swapped)
2717 Result = Builder->CreateNeg(Result, "diff.neg");
2718
2719 return Builder->CreateIntCast(Result, Ty, true);
2720}
2721
2722
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002723Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2724 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2725
Dan Gohman7ce405e2009-06-04 22:49:04 +00002726 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002727 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002728
Chris Lattner93e6ff92009-11-04 08:05:20 +00002729 // If this is a 'B = x-(-A)', change to B = x+A.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002730 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002731 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002732
2733 if (isa<UndefValue>(Op0))
2734 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2735 if (isa<UndefValue>(Op1))
2736 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner93e6ff92009-11-04 08:05:20 +00002737 if (I.getType() == Type::getInt1Ty(*Context))
2738 return BinaryOperator::CreateXor(Op0, Op1);
2739
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002740 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner93e6ff92009-11-04 08:05:20 +00002741 // Replace (-1 - A) with (~A).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002742 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00002743 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002744
2745 // C - ~X == X + (1+C)
2746 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002747 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002748 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002749
2750 // -(X >>u 31) -> (X >>s 31)
2751 // -(X >>s 31) -> (X >>u 31)
2752 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002753 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002754 if (SI->getOpcode() == Instruction::LShr) {
2755 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2756 // Check to see if we are shifting out everything but the sign bit.
2757 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2758 SI->getType()->getPrimitiveSizeInBits()-1) {
2759 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002760 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002761 SI->getOperand(0), CU, SI->getName());
2762 }
2763 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00002764 } else if (SI->getOpcode() == Instruction::AShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002765 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2766 // Check to see if we are shifting out everything but the sign bit.
2767 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2768 SI->getType()->getPrimitiveSizeInBits()-1) {
2769 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002770 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002771 SI->getOperand(0), CU, SI->getName());
2772 }
2773 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002774 }
2775 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002776 }
2777
2778 // Try to fold constant sub into select arguments.
2779 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2780 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2781 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002782
2783 // C - zext(bool) -> bool ? C - 1 : C
2784 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson35b47072009-08-13 21:58:54 +00002785 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002786 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002787 }
2788
2789 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002790 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002791 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002792 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002793 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002794 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002795 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002796 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002797 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2798 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2799 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002800 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002801 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002802 }
2803 }
2804
2805 if (Op1I->hasOneUse()) {
2806 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2807 // is not used by anyone else...
2808 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002809 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002810 // Swap the two operands of the subexpr...
2811 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2812 Op1I->setOperand(0, IIOp1);
2813 Op1I->setOperand(1, IIOp0);
2814
2815 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002816 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002817 }
2818
2819 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2820 //
2821 if (Op1I->getOpcode() == Instruction::And &&
2822 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2823 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2824
Chris Lattnerc7694852009-08-30 07:44:24 +00002825 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greifa645dd32008-05-16 19:29:10 +00002826 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002827 }
2828
2829 // 0 - (X sdiv C) -> (X sdiv -C)
2830 if (Op1I->getOpcode() == Instruction::SDiv)
2831 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2832 if (CSI->isZero())
2833 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002834 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002835 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002836
2837 // X - X*C --> X * (1-C)
2838 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002839 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002840 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00002841 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002842 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002843 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002844 }
2845 }
2846 }
2847
Dan Gohman7ce405e2009-06-04 22:49:04 +00002848 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2849 if (Op0I->getOpcode() == Instruction::Add) {
2850 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2851 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2852 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2853 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2854 } else if (Op0I->getOpcode() == Instruction::Sub) {
2855 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002856 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002857 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002858 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002859 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002860
2861 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002862 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002863 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002864 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002865
2866 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002867 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00002868 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002869 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00002870
2871 // Optimize pointer differences into the same array into a size. Consider:
2872 // &A[10] - &A[0]: we should compile this to "10".
2873 if (TD) {
2874 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2875 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2876 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2877 RHS->getOperand(0),
2878 I.getType()))
2879 return ReplaceInstUsesWith(I, Res);
2880
2881 // trunc(p)-trunc(q) -> trunc(p-q)
2882 if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2883 if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2884 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2885 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2886 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2887 RHS->getOperand(0),
2888 I.getType()))
2889 return ReplaceInstUsesWith(I, Res);
2890 }
2891
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002892 return 0;
2893}
2894
Dan Gohman7ce405e2009-06-04 22:49:04 +00002895Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2896 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2897
2898 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002899 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002900 return BinaryOperator::CreateFAdd(Op0, V);
2901
2902 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2903 if (Op1I->getOpcode() == Instruction::FAdd) {
2904 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002905 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002906 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002907 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002908 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002909 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002910 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002911 }
2912
2913 return 0;
2914}
2915
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002916/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2917/// comparison only checks the sign bit. If it only checks the sign bit, set
2918/// TrueIfSigned if the result of the comparison is true when the input value is
2919/// signed.
2920static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2921 bool &TrueIfSigned) {
2922 switch (pred) {
2923 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2924 TrueIfSigned = true;
2925 return RHS->isZero();
2926 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2927 TrueIfSigned = true;
2928 return RHS->isAllOnesValue();
2929 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2930 TrueIfSigned = false;
2931 return RHS->isAllOnesValue();
2932 case ICmpInst::ICMP_UGT:
2933 // True if LHS u> RHS and RHS == high-bit-mask - 1
2934 TrueIfSigned = true;
2935 return RHS->getValue() ==
2936 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2937 case ICmpInst::ICMP_UGE:
2938 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2939 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002940 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002941 default:
2942 return false;
2943 }
2944}
2945
2946Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2947 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00002948 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002949
Chris Lattner3508c5c2009-10-11 21:36:10 +00002950 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002951 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002952
Chris Lattner6438c582009-10-11 07:53:15 +00002953 // Simplify mul instructions with a constant RHS.
Chris Lattner3508c5c2009-10-11 21:36:10 +00002954 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2955 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002956
2957 // ((X << C1)*C2) == (X * (C2 << C1))
2958 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2959 if (SI->getOpcode() == Instruction::Shl)
2960 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002961 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002962 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002963
2964 if (CI->isZero())
Chris Lattner3508c5c2009-10-11 21:36:10 +00002965 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002966 if (CI->equalsInt(1)) // X * 1 == X
2967 return ReplaceInstUsesWith(I, Op0);
2968 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002969 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002970
2971 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2972 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002973 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002974 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002975 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00002976 } else if (isa<VectorType>(Op1C->getType())) {
2977 if (Op1C->isNullValue())
2978 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky94418732008-11-27 20:21:08 +00002979
Chris Lattner3508c5c2009-10-11 21:36:10 +00002980 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky94418732008-11-27 20:21:08 +00002981 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002982 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00002983
2984 // As above, vector X*splat(1.0) -> X in all defined cases.
2985 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002986 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2987 if (CI->equalsInt(1))
2988 return ReplaceInstUsesWith(I, Op0);
2989 }
2990 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002991 }
2992
2993 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2994 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00002995 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002996 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner3508c5c2009-10-11 21:36:10 +00002997 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2998 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greifa645dd32008-05-16 19:29:10 +00002999 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003000
3001 }
3002
3003 // Try to fold constant mul into select arguments.
3004 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3005 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3006 return R;
3007
3008 if (isa<PHINode>(Op0))
3009 if (Instruction *NV = FoldOpIntoPhi(I))
3010 return NV;
3011 }
3012
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003013 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00003014 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00003015 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003016
Nick Lewycky1c246402008-11-21 07:33:58 +00003017 // (X / Y) * Y = X - (X % Y)
3018 // (X / Y) * -Y = (X % Y) - X
3019 {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003020 Value *Op1C = Op1;
Nick Lewycky1c246402008-11-21 07:33:58 +00003021 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3022 if (!BO ||
3023 (BO->getOpcode() != Instruction::UDiv &&
3024 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003025 Op1C = Op0;
3026 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00003027 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00003028 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky1c246402008-11-21 07:33:58 +00003029 if (BO && BO->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00003030 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky1c246402008-11-21 07:33:58 +00003031 (BO->getOpcode() == Instruction::UDiv ||
3032 BO->getOpcode() == Instruction::SDiv)) {
3033 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3034
Dan Gohman07878902009-08-12 16:33:09 +00003035 // If the division is exact, X % Y is zero.
3036 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3037 if (SDiv->isExact()) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003038 if (Op1BO == Op1C)
Dan Gohman07878902009-08-12 16:33:09 +00003039 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattner3508c5c2009-10-11 21:36:10 +00003040 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohman07878902009-08-12 16:33:09 +00003041 }
3042
Chris Lattnerc7694852009-08-30 07:44:24 +00003043 Value *Rem;
Nick Lewycky1c246402008-11-21 07:33:58 +00003044 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattnerc7694852009-08-30 07:44:24 +00003045 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003046 else
Chris Lattnerc7694852009-08-30 07:44:24 +00003047 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003048 Rem->takeName(BO);
3049
Chris Lattner3508c5c2009-10-11 21:36:10 +00003050 if (Op1BO == Op1C)
Nick Lewycky1c246402008-11-21 07:33:58 +00003051 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattnerc7694852009-08-30 07:44:24 +00003052 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003053 }
3054 }
3055
Chris Lattner6438c582009-10-11 07:53:15 +00003056 /// i1 mul -> i1 and.
Owen Anderson35b47072009-08-13 21:58:54 +00003057 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003058 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003059
Chris Lattner6438c582009-10-11 07:53:15 +00003060 // X*(1 << Y) --> X << Y
3061 // (1 << Y)*X --> X << Y
3062 {
3063 Value *Y;
3064 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003065 return BinaryOperator::CreateShl(Op1, Y);
3066 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner6438c582009-10-11 07:53:15 +00003067 return BinaryOperator::CreateShl(Op0, Y);
3068 }
3069
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003070 // If one of the operands of the multiply is a cast from a boolean value, then
3071 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattner4ca76f72009-10-11 21:29:45 +00003072 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3073 if (!isa<VectorType>(I.getType())) {
3074 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenb5887062009-10-12 18:45:32 +00003075 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner291872e2009-10-11 21:22:21 +00003076
Chris Lattner4ca76f72009-10-11 21:29:45 +00003077 Value *BoolCast = 0, *OtherOp = 0;
3078 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003079 BoolCast = Op0, OtherOp = Op1;
3080 else if (MaskedValueIsZero(Op1, Negative2))
3081 BoolCast = Op1, OtherOp = Op0;
Chris Lattner4ca76f72009-10-11 21:29:45 +00003082
Chris Lattner291872e2009-10-11 21:22:21 +00003083 if (BoolCast) {
Chris Lattner291872e2009-10-11 21:22:21 +00003084 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3085 BoolCast, "tmp");
3086 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003087 }
3088 }
3089
3090 return Changed ? &I : 0;
3091}
3092
Dan Gohman7ce405e2009-06-04 22:49:04 +00003093Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3094 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00003095 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohman7ce405e2009-06-04 22:49:04 +00003096
3097 // Simplify mul instructions with a constant RHS...
Chris Lattner3508c5c2009-10-11 21:36:10 +00003098 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3099 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00003100 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3101 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3102 if (Op1F->isExactlyValue(1.0))
3103 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattner3508c5c2009-10-11 21:36:10 +00003104 } else if (isa<VectorType>(Op1C->getType())) {
3105 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00003106 // As above, vector X*splat(1.0) -> X in all defined cases.
3107 if (Constant *Splat = Op1V->getSplatValue()) {
3108 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3109 if (F->isExactlyValue(1.0))
3110 return ReplaceInstUsesWith(I, Op0);
3111 }
3112 }
3113 }
3114
3115 // Try to fold constant mul into select arguments.
3116 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3117 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3118 return R;
3119
3120 if (isa<PHINode>(Op0))
3121 if (Instruction *NV = FoldOpIntoPhi(I))
3122 return NV;
3123 }
3124
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003125 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00003126 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00003127 return BinaryOperator::CreateFMul(Op0v, Op1v);
3128
3129 return Changed ? &I : 0;
3130}
3131
Chris Lattner76972db2008-07-14 00:15:52 +00003132/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3133/// instruction.
3134bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3135 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3136
3137 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3138 int NonNullOperand = -1;
3139 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3140 if (ST->isNullValue())
3141 NonNullOperand = 2;
3142 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3143 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3144 if (ST->isNullValue())
3145 NonNullOperand = 1;
3146
3147 if (NonNullOperand == -1)
3148 return false;
3149
3150 Value *SelectCond = SI->getOperand(0);
3151
3152 // Change the div/rem to use 'Y' instead of the select.
3153 I.setOperand(1, SI->getOperand(NonNullOperand));
3154
3155 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3156 // problem. However, the select, or the condition of the select may have
3157 // multiple uses. Based on our knowledge that the operand must be non-zero,
3158 // propagate the known value for the select into other uses of it, and
3159 // propagate a known value of the condition into its other users.
3160
3161 // If the select and condition only have a single use, don't bother with this,
3162 // early exit.
3163 if (SI->use_empty() && SelectCond->hasOneUse())
3164 return true;
3165
3166 // Scan the current block backward, looking for other uses of SI.
3167 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3168
3169 while (BBI != BBFront) {
3170 --BBI;
3171 // If we found a call to a function, we can't assume it will return, so
3172 // information from below it cannot be propagated above it.
3173 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3174 break;
3175
3176 // Replace uses of the select or its condition with the known values.
3177 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3178 I != E; ++I) {
3179 if (*I == SI) {
3180 *I = SI->getOperand(NonNullOperand);
Chris Lattner3183fb62009-08-30 06:13:40 +00003181 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00003182 } else if (*I == SelectCond) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00003183 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3184 ConstantInt::getFalse(*Context);
Chris Lattner3183fb62009-08-30 06:13:40 +00003185 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00003186 }
3187 }
3188
3189 // If we past the instruction, quit looking for it.
3190 if (&*BBI == SI)
3191 SI = 0;
3192 if (&*BBI == SelectCond)
3193 SelectCond = 0;
3194
3195 // If we ran out of things to eliminate, break out of the loop.
3196 if (SelectCond == 0 && SI == 0)
3197 break;
3198
3199 }
3200 return true;
3201}
3202
3203
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003204/// This function implements the transforms on div instructions that work
3205/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3206/// used by the visitors to those instructions.
3207/// @brief Transforms common to all three div instructions
3208Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3209 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3210
Chris Lattner653ef3c2008-02-19 06:12:18 +00003211 // undef / X -> 0 for integer.
3212 // undef / X -> undef for FP (the undef could be a snan).
3213 if (isa<UndefValue>(Op0)) {
3214 if (Op0->getType()->isFPOrFPVector())
3215 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00003216 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003217 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003218
3219 // X / undef -> undef
3220 if (isa<UndefValue>(Op1))
3221 return ReplaceInstUsesWith(I, Op1);
3222
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003223 return 0;
3224}
3225
3226/// This function implements the transforms common to both integer division
3227/// instructions (udiv and sdiv). It is called by the visitors to those integer
3228/// division instructions.
3229/// @brief Common integer divide transforms
3230Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3231 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3232
Chris Lattnercefb36c2008-05-16 02:59:42 +00003233 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00003234 if (Op0 == Op1) {
3235 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00003236 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00003237 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00003238 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00003239 }
3240
Owen Andersoneacb44d2009-07-24 23:12:02 +00003241 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00003242 return ReplaceInstUsesWith(I, CI);
3243 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00003244
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003245 if (Instruction *Common = commonDivTransforms(I))
3246 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00003247
3248 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3249 // This does not apply for fdiv.
3250 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3251 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003252
3253 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3254 // div X, 1 == X
3255 if (RHS->equalsInt(1))
3256 return ReplaceInstUsesWith(I, Op0);
3257
3258 // (X / C1) / C2 -> X / (C1*C2)
3259 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3260 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3261 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00003262 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003263 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00003264 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00003265 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003266 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00003267 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003268 }
3269
3270 if (!RHS->isZero()) { // avoid X udiv 0
3271 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3272 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3273 return R;
3274 if (isa<PHINode>(Op0))
3275 if (Instruction *NV = FoldOpIntoPhi(I))
3276 return NV;
3277 }
3278 }
3279
3280 // 0 / X == 0, we don't need to preserve faults!
3281 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3282 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00003283 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003284
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003285 // It can't be division by zero, hence it must be division by one.
Owen Anderson35b47072009-08-13 21:58:54 +00003286 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003287 return ReplaceInstUsesWith(I, Op0);
3288
Nick Lewycky94418732008-11-27 20:21:08 +00003289 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3290 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3291 // div X, 1 == X
3292 if (X->isOne())
3293 return ReplaceInstUsesWith(I, Op0);
3294 }
3295
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003296 return 0;
3297}
3298
3299Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3300 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3301
3302 // Handle the integer div common cases
3303 if (Instruction *Common = commonIDivTransforms(I))
3304 return Common;
3305
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003306 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00003307 // X udiv C^2 -> X >> C
3308 // Check to see if this is an unsigned division with an exact power of 2,
3309 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003310 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003311 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003312 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003313
3314 // X udiv C, where C >= signbit
3315 if (C->getValue().isNegative()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003316 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersonaac28372009-07-31 20:28:14 +00003317 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003318 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003319 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003320 }
3321
3322 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3323 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3324 if (RHSI->getOpcode() == Instruction::Shl &&
3325 isa<ConstantInt>(RHSI->getOperand(0))) {
3326 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3327 if (C1.isPowerOf2()) {
3328 Value *N = RHSI->getOperand(1);
3329 const Type *NTy = N->getType();
Chris Lattnerc7694852009-08-30 07:44:24 +00003330 if (uint32_t C2 = C1.logBase2())
3331 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003332 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003333 }
3334 }
3335 }
3336
3337 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3338 // where C1&C2 are powers of two.
3339 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3340 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3341 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3342 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3343 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3344 // Compute the shift amounts
3345 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3346 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003347 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003348 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003349
3350 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003351 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003352 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003353
3354 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003355 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003356 }
3357 }
3358 return 0;
3359}
3360
3361Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3362 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3363
3364 // Handle the integer div common cases
3365 if (Instruction *Common = commonIDivTransforms(I))
3366 return Common;
3367
3368 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3369 // sdiv X, -1 == -X
3370 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00003371 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00003372
Dan Gohman07878902009-08-12 16:33:09 +00003373 // sdiv X, C --> ashr X, log2(C)
Dan Gohman31b6b132009-08-11 20:47:47 +00003374 if (cast<SDivOperator>(&I)->isExact() &&
3375 RHS->getValue().isNonNegative() &&
3376 RHS->getValue().isPowerOf2()) {
3377 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3378 RHS->getValue().exactLogBase2());
3379 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3380 }
Dan Gohman5ce93b32009-08-12 16:37:02 +00003381
3382 // -X/C --> X/-C provided the negation doesn't overflow.
3383 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3384 if (isa<Constant>(Sub->getOperand(0)) &&
3385 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohmanb5ed4492009-08-20 17:11:38 +00003386 Sub->hasNoSignedWrap())
Dan Gohman5ce93b32009-08-12 16:37:02 +00003387 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3388 ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003389 }
3390
3391 // If the sign bits of both operands are zero (i.e. we can prove they are
3392 // unsigned inputs), turn this into a udiv.
3393 if (I.getType()->isInteger()) {
3394 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003395 if (MaskedValueIsZero(Op0, Mask)) {
3396 if (MaskedValueIsZero(Op1, Mask)) {
3397 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3398 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3399 }
3400 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00003401 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00003402 ShiftedInt->getValue().isPowerOf2()) {
3403 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3404 // Safe because the only negative value (1 << Y) can take on is
3405 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3406 // the sign bit set.
3407 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3408 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003409 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003410 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003411
3412 return 0;
3413}
3414
3415Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3416 return commonDivTransforms(I);
3417}
3418
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003419/// This function implements the transforms on rem instructions that work
3420/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3421/// is used by the visitors to those instructions.
3422/// @brief Transforms common to all three rem instructions
3423Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3424 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3425
Chris Lattner653ef3c2008-02-19 06:12:18 +00003426 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3427 if (I.getType()->isFPOrFPVector())
3428 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00003429 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003430 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003431 if (isa<UndefValue>(Op1))
3432 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3433
3434 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003435 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3436 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003437
3438 return 0;
3439}
3440
3441/// This function implements the transforms common to both integer remainder
3442/// instructions (urem and srem). It is called by the visitors to those integer
3443/// remainder instructions.
3444/// @brief Common integer remainder transforms
3445Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3446 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3447
3448 if (Instruction *common = commonRemTransforms(I))
3449 return common;
3450
Dale Johannesena51f7372009-01-21 00:35:19 +00003451 // 0 % X == 0 for integer, we don't need to preserve faults!
3452 if (Constant *LHS = dyn_cast<Constant>(Op0))
3453 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00003454 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003455
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003456 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3457 // X % 0 == undef, we don't need to preserve faults!
3458 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003459 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003460
3461 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003462 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003463
3464 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3465 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3466 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3467 return R;
3468 } else if (isa<PHINode>(Op0I)) {
3469 if (Instruction *NV = FoldOpIntoPhi(I))
3470 return NV;
3471 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003472
3473 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003474 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003475 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003476 }
3477 }
3478
3479 return 0;
3480}
3481
3482Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3483 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3484
3485 if (Instruction *common = commonIRemTransforms(I))
3486 return common;
3487
3488 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3489 // X urem C^2 -> X and C
3490 // Check to see if this is an unsigned remainder with an exact power of 2,
3491 // if so, convert to a bitwise and.
3492 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3493 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003494 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003495 }
3496
3497 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3498 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3499 if (RHSI->getOpcode() == Instruction::Shl &&
3500 isa<ConstantInt>(RHSI->getOperand(0))) {
3501 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00003502 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00003503 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003504 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003505 }
3506 }
3507 }
3508
3509 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3510 // where C1&C2 are powers of two.
3511 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3512 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3513 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3514 // STO == 0 and SFO == 0 handled above.
3515 if ((STO->getValue().isPowerOf2()) &&
3516 (SFO->getValue().isPowerOf2())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003517 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3518 SI->getName()+".t");
3519 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3520 SI->getName()+".f");
Gabor Greifd6da1d02008-04-06 20:25:17 +00003521 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003522 }
3523 }
3524 }
3525
3526 return 0;
3527}
3528
3529Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3530 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3531
Dan Gohmandb3dd962007-11-05 23:16:33 +00003532 // Handle the integer rem common cases
Chris Lattner4796b622009-08-30 06:22:51 +00003533 if (Instruction *Common = commonIRemTransforms(I))
3534 return Common;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003535
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003536 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003537 if (!isa<Constant>(RHSNeg) ||
3538 (isa<ConstantInt>(RHSNeg) &&
3539 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003540 // X % -Y -> X % Y
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003541 Worklist.AddValue(I.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003542 I.setOperand(1, RHSNeg);
3543 return &I;
3544 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003545
Dan Gohmandb3dd962007-11-05 23:16:33 +00003546 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003547 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003548 if (I.getType()->isInteger()) {
3549 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3550 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3551 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003552 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003553 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003554 }
3555
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003556 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003557 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3558 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003559
Nick Lewyckyfd746832008-12-20 16:48:00 +00003560 bool hasNegative = false;
3561 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3562 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3563 if (RHS->getValue().isNegative())
3564 hasNegative = true;
3565
3566 if (hasNegative) {
3567 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003568 for (unsigned i = 0; i != VWidth; ++i) {
3569 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3570 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00003571 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003572 else
3573 Elts[i] = RHS;
3574 }
3575 }
3576
Owen Anderson2f422e02009-07-28 21:19:26 +00003577 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003578 if (NewRHSV != RHSV) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003579 Worklist.AddValue(I.getOperand(1));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003580 I.setOperand(1, NewRHSV);
3581 return &I;
3582 }
3583 }
3584 }
3585
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003586 return 0;
3587}
3588
3589Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3590 return commonRemTransforms(I);
3591}
3592
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003593// isOneBitSet - Return true if there is exactly one bit set in the specified
3594// constant.
3595static bool isOneBitSet(const ConstantInt *CI) {
3596 return CI->getValue().isPowerOf2();
3597}
3598
3599// isHighOnes - Return true if the constant is of the form 1+0+.
3600// This is the same as lowones(~X).
3601static bool isHighOnes(const ConstantInt *CI) {
3602 return (~CI->getValue() + 1).isPowerOf2();
3603}
3604
3605/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3606/// are carefully arranged to allow folding of expressions such as:
3607///
3608/// (A < B) | (A > B) --> (A != B)
3609///
3610/// Note that this is only valid if the first and second predicates have the
3611/// same sign. Is illegal to do: (A u< B) | (A s> B)
3612///
3613/// Three bits are used to represent the condition, as follows:
3614/// 0 A > B
3615/// 1 A == B
3616/// 2 A < B
3617///
3618/// <=> Value Definition
3619/// 000 0 Always false
3620/// 001 1 A > B
3621/// 010 2 A == B
3622/// 011 3 A >= B
3623/// 100 4 A < B
3624/// 101 5 A != B
3625/// 110 6 A <= B
3626/// 111 7 Always true
3627///
3628static unsigned getICmpCode(const ICmpInst *ICI) {
3629 switch (ICI->getPredicate()) {
3630 // False -> 0
3631 case ICmpInst::ICMP_UGT: return 1; // 001
3632 case ICmpInst::ICMP_SGT: return 1; // 001
3633 case ICmpInst::ICMP_EQ: return 2; // 010
3634 case ICmpInst::ICMP_UGE: return 3; // 011
3635 case ICmpInst::ICMP_SGE: return 3; // 011
3636 case ICmpInst::ICMP_ULT: return 4; // 100
3637 case ICmpInst::ICMP_SLT: return 4; // 100
3638 case ICmpInst::ICMP_NE: return 5; // 101
3639 case ICmpInst::ICMP_ULE: return 6; // 110
3640 case ICmpInst::ICMP_SLE: return 6; // 110
3641 // True -> 7
3642 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003643 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003644 return 0;
3645 }
3646}
3647
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003648/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3649/// predicate into a three bit mask. It also returns whether it is an ordered
3650/// predicate by reference.
3651static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3652 isOrdered = false;
3653 switch (CC) {
3654 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3655 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003656 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3657 case FCmpInst::FCMP_UGT: return 1; // 001
3658 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3659 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003660 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3661 case FCmpInst::FCMP_UGE: return 3; // 011
3662 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3663 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003664 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3665 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003666 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3667 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003668 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003669 default:
3670 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003671 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003672 return 0;
3673 }
3674}
3675
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003676/// getICmpValue - This is the complement of getICmpCode, which turns an
3677/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003678/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003679/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003680static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003681 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003682 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003683 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson4f720fa2009-07-31 17:39:07 +00003684 case 0: return ConstantInt::getFalse(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003685 case 1:
3686 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003687 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003688 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003689 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3690 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003691 case 3:
3692 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003693 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003694 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003695 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003696 case 4:
3697 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003698 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003699 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003700 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3701 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003702 case 6:
3703 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003704 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003705 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003706 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003707 case 7: return ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003708 }
3709}
3710
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003711/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3712/// opcode and two operands into either a FCmp instruction. isordered is passed
3713/// in to determine which kind of predicate to use in the new fcmp instruction.
3714static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003715 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003716 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003717 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003718 case 0:
3719 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003720 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003721 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003722 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003723 case 1:
3724 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003725 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003726 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003727 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003728 case 2:
3729 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003730 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003731 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003732 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003733 case 3:
3734 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003735 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003736 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003737 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003738 case 4:
3739 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003740 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003741 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003742 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003743 case 5:
3744 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003745 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003746 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003747 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003748 case 6:
3749 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003750 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003751 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003752 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003753 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003754 }
3755}
3756
Chris Lattner2972b822008-11-16 04:55:20 +00003757/// PredicatesFoldable - Return true if both predicates match sign or if at
3758/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003759static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003760 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3761 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3762 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003763}
3764
3765namespace {
3766// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3767struct FoldICmpLogical {
3768 InstCombiner &IC;
3769 Value *LHS, *RHS;
3770 ICmpInst::Predicate pred;
3771 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3772 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3773 pred(ICI->getPredicate()) {}
3774 bool shouldApply(Value *V) const {
3775 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3776 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003777 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3778 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003779 return false;
3780 }
3781 Instruction *apply(Instruction &Log) const {
3782 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3783 if (ICI->getOperand(0) != LHS) {
3784 assert(ICI->getOperand(1) == LHS);
3785 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3786 }
3787
3788 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3789 unsigned LHSCode = getICmpCode(ICI);
3790 unsigned RHSCode = getICmpCode(RHSICI);
3791 unsigned Code;
3792 switch (Log.getOpcode()) {
3793 case Instruction::And: Code = LHSCode & RHSCode; break;
3794 case Instruction::Or: Code = LHSCode | RHSCode; break;
3795 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003796 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003797 }
3798
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003799 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Anderson24be4c12009-07-03 00:17:18 +00003800 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003801 if (Instruction *I = dyn_cast<Instruction>(RV))
3802 return I;
3803 // Otherwise, it's a constant boolean value...
3804 return IC.ReplaceInstUsesWith(Log, RV);
3805 }
3806};
3807} // end anonymous namespace
3808
3809// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3810// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3811// guaranteed to be a binary operator.
3812Instruction *InstCombiner::OptAndOp(Instruction *Op,
3813 ConstantInt *OpRHS,
3814 ConstantInt *AndRHS,
3815 BinaryOperator &TheAnd) {
3816 Value *X = Op->getOperand(0);
3817 Constant *Together = 0;
3818 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00003819 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003820
3821 switch (Op->getOpcode()) {
3822 case Instruction::Xor:
3823 if (Op->hasOneUse()) {
3824 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattnerc7694852009-08-30 07:44:24 +00003825 Value *And = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003826 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003827 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003828 }
3829 break;
3830 case Instruction::Or:
3831 if (Together == AndRHS) // (X | C) & C --> C
3832 return ReplaceInstUsesWith(TheAnd, AndRHS);
3833
3834 if (Op->hasOneUse() && Together != OpRHS) {
3835 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattnerc7694852009-08-30 07:44:24 +00003836 Value *Or = Builder->CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003837 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003838 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003839 }
3840 break;
3841 case Instruction::Add:
3842 if (Op->hasOneUse()) {
3843 // Adding a one to a single bit bit-field should be turned into an XOR
3844 // of the bit. First thing to check is to see if this AND is with a
3845 // single bit constant.
3846 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3847
3848 // If there is only one bit set...
3849 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3850 // Ok, at this point, we know that we are masking the result of the
3851 // ADD down to exactly one bit. If the constant we are adding has
3852 // no bits set below this bit, then we can eliminate the ADD.
3853 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3854
3855 // Check to see if any bits below the one bit set in AndRHSV are set.
3856 if ((AddRHS & (AndRHSV-1)) == 0) {
3857 // If not, the only thing that can effect the output of the AND is
3858 // the bit specified by AndRHSV. If that bit is set, the effect of
3859 // the XOR is to toggle the bit. If it is clear, then the ADD has
3860 // no effect.
3861 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3862 TheAnd.setOperand(0, X);
3863 return &TheAnd;
3864 } else {
3865 // Pull the XOR out of the AND.
Chris Lattnerc7694852009-08-30 07:44:24 +00003866 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003867 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003868 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003869 }
3870 }
3871 }
3872 }
3873 break;
3874
3875 case Instruction::Shl: {
3876 // We know that the AND will not produce any of the bits shifted in, so if
3877 // the anded constant includes them, clear them now!
3878 //
3879 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3880 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3881 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003882 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003883
3884 if (CI->getValue() == ShlMask) {
3885 // Masking out bits that the shift already masks
3886 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3887 } else if (CI != AndRHS) { // Reducing bits set in and.
3888 TheAnd.setOperand(1, CI);
3889 return &TheAnd;
3890 }
3891 break;
3892 }
3893 case Instruction::LShr:
3894 {
3895 // We know that the AND will not produce any of the bits shifted in, so if
3896 // the anded constant includes them, clear them now! This only applies to
3897 // unsigned shifts, because a signed shr may bring in set bits!
3898 //
3899 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3900 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3901 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003902 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003903
3904 if (CI->getValue() == ShrMask) {
3905 // Masking out bits that the shift already masks.
3906 return ReplaceInstUsesWith(TheAnd, Op);
3907 } else if (CI != AndRHS) {
3908 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3909 return &TheAnd;
3910 }
3911 break;
3912 }
3913 case Instruction::AShr:
3914 // Signed shr.
3915 // See if this is shifting in some sign extension, then masking it out
3916 // with an and.
3917 if (Op->hasOneUse()) {
3918 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3919 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3920 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003921 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003922 if (C == AndRHS) { // Masking out bits shifted in.
3923 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3924 // Make the argument unsigned.
3925 Value *ShVal = Op->getOperand(0);
Chris Lattnerc7694852009-08-30 07:44:24 +00003926 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003927 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003928 }
3929 }
3930 break;
3931 }
3932 return 0;
3933}
3934
3935
3936/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3937/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3938/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3939/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3940/// insert new instructions.
3941Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3942 bool isSigned, bool Inside,
3943 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003944 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003945 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3946 "Lo is not <= Hi in range emission code!");
3947
3948 if (Inside) {
3949 if (Lo == Hi) // Trivially false.
Dan Gohmane6803b82009-08-25 23:17:54 +00003950 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003951
3952 // V >= Min && V < Hi --> V < Hi
3953 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3954 ICmpInst::Predicate pred = (isSigned ?
3955 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003956 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003957 }
3958
3959 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00003960 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattnerc7694852009-08-30 07:44:24 +00003961 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003962 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003963 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003964 }
3965
3966 if (Lo == Hi) // Trivially true.
Dan Gohmane6803b82009-08-25 23:17:54 +00003967 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003968
3969 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003970 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003971 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3972 ICmpInst::Predicate pred = (isSigned ?
3973 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003974 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003975 }
3976
3977 // Emit V-Lo >u Hi-1-Lo
3978 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00003979 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattnerc7694852009-08-30 07:44:24 +00003980 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003981 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003982 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003983}
3984
3985// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3986// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3987// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3988// not, since all 1s are not contiguous.
3989static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3990 const APInt& V = Val->getValue();
3991 uint32_t BitWidth = Val->getType()->getBitWidth();
3992 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3993
3994 // look for the first zero bit after the run of ones
3995 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3996 // look for the first non-zero bit
3997 ME = V.getActiveBits();
3998 return true;
3999}
4000
4001/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4002/// where isSub determines whether the operator is a sub. If we can fold one of
4003/// the following xforms:
4004///
4005/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4006/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4007/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4008///
4009/// return (A +/- B).
4010///
4011Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
4012 ConstantInt *Mask, bool isSub,
4013 Instruction &I) {
4014 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4015 if (!LHSI || LHSI->getNumOperands() != 2 ||
4016 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4017
4018 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4019
4020 switch (LHSI->getOpcode()) {
4021 default: return 0;
4022 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00004023 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004024 // If the AndRHS is a power of two minus one (0+1+), this is simple.
4025 if ((Mask->getValue().countLeadingZeros() +
4026 Mask->getValue().countPopulation()) ==
4027 Mask->getValue().getBitWidth())
4028 break;
4029
4030 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4031 // part, we don't need any explicit masks to take them out of A. If that
4032 // is all N is, ignore it.
4033 uint32_t MB = 0, ME = 0;
4034 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
4035 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4036 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4037 if (MaskedValueIsZero(RHS, Mask))
4038 break;
4039 }
4040 }
4041 return 0;
4042 case Instruction::Or:
4043 case Instruction::Xor:
4044 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4045 if ((Mask->getValue().countLeadingZeros() +
4046 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00004047 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004048 break;
4049 return 0;
4050 }
4051
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004052 if (isSub)
Chris Lattnerc7694852009-08-30 07:44:24 +00004053 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4054 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004055}
4056
Chris Lattner0631ea72008-11-16 05:06:21 +00004057/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4058Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4059 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00004060 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00004061 ConstantInt *LHSCst, *RHSCst;
4062 ICmpInst::Predicate LHSCC, RHSCC;
4063
Chris Lattnerf3803482008-11-16 05:10:52 +00004064 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004065 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004066 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004067 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004068 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00004069 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00004070
4071 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4072 // where C is a power of 2
4073 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
4074 LHSCst->getValue().isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004075 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohmane6803b82009-08-25 23:17:54 +00004076 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerf3803482008-11-16 05:10:52 +00004077 }
4078
4079 // From here on, we only handle:
4080 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4081 if (Val != Val2) return 0;
4082
Chris Lattner0631ea72008-11-16 05:06:21 +00004083 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4084 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4085 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4086 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4087 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4088 return 0;
4089
4090 // We can't fold (ugt x, C) & (sgt x, C2).
4091 if (!PredicatesFoldable(LHSCC, RHSCC))
4092 return 0;
4093
4094 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00004095 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004096 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0631ea72008-11-16 05:06:21 +00004097 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004098 CmpInst::isSigned(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00004099 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00004100 else
Chris Lattner665298f2008-11-16 05:14:43 +00004101 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4102
4103 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00004104 std::swap(LHS, RHS);
4105 std::swap(LHSCst, RHSCst);
4106 std::swap(LHSCC, RHSCC);
4107 }
4108
4109 // At this point, we know we have have two icmp instructions
4110 // comparing a value against two constants and and'ing the result
4111 // together. Because of the above check, we know that we only have
4112 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4113 // (from the FoldICmpLogical check above), that the two constants
4114 // are not equal and that the larger constant is on the RHS
4115 assert(LHSCst != RHSCst && "Compares not folded above?");
4116
4117 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004118 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004119 case ICmpInst::ICMP_EQ:
4120 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004121 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004122 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4123 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4124 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004125 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004126 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4127 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4128 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4129 return ReplaceInstUsesWith(I, LHS);
4130 }
4131 case ICmpInst::ICMP_NE:
4132 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004133 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004134 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004135 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00004136 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004137 break; // (X != 13 & X u< 15) -> no change
4138 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004139 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00004140 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004141 break; // (X != 13 & X s< 15) -> no change
4142 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4143 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4144 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4145 return ReplaceInstUsesWith(I, RHS);
4146 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004147 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00004148 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004149 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmane6803b82009-08-25 23:17:54 +00004150 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004151 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00004152 }
4153 break; // (X != 13 & X != 15) -> no change
4154 }
4155 break;
4156 case ICmpInst::ICMP_ULT:
4157 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004158 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004159 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4160 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004161 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004162 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4163 break;
4164 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4165 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4166 return ReplaceInstUsesWith(I, LHS);
4167 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4168 break;
4169 }
4170 break;
4171 case ICmpInst::ICMP_SLT:
4172 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004173 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004174 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4175 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004176 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004177 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4178 break;
4179 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4180 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4181 return ReplaceInstUsesWith(I, LHS);
4182 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4183 break;
4184 }
4185 break;
4186 case ICmpInst::ICMP_UGT:
4187 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004188 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004189 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4190 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4191 return ReplaceInstUsesWith(I, RHS);
4192 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4193 break;
4194 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004195 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00004196 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004197 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00004198 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004199 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004200 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00004201 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4202 break;
4203 }
4204 break;
4205 case ICmpInst::ICMP_SGT:
4206 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004207 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004208 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4209 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4210 return ReplaceInstUsesWith(I, RHS);
4211 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4212 break;
4213 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004214 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00004215 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004216 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00004217 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004218 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004219 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00004220 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4221 break;
4222 }
4223 break;
4224 }
Chris Lattner0631ea72008-11-16 05:06:21 +00004225
4226 return 0;
4227}
4228
Chris Lattner93a359a2009-07-23 05:14:02 +00004229Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4230 FCmpInst *RHS) {
4231
4232 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4233 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4234 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4235 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4236 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4237 // If either of the constants are nans, then the whole thing returns
4238 // false.
4239 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004240 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00004241 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner93a359a2009-07-23 05:14:02 +00004242 LHS->getOperand(0), RHS->getOperand(0));
4243 }
Chris Lattnercf373552009-07-23 05:32:17 +00004244
4245 // Handle vector zeros. This occurs because the canonical form of
4246 // "fcmp ord x,x" is "fcmp ord x, 0".
4247 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4248 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004249 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnercf373552009-07-23 05:32:17 +00004250 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00004251 return 0;
4252 }
4253
4254 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4255 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4256 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4257
4258
4259 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4260 // Swap RHS operands to match LHS.
4261 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4262 std::swap(Op1LHS, Op1RHS);
4263 }
4264
4265 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4266 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4267 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004268 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +00004269
4270 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004271 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004272 if (Op0CC == FCmpInst::FCMP_TRUE)
4273 return ReplaceInstUsesWith(I, RHS);
4274 if (Op1CC == FCmpInst::FCMP_TRUE)
4275 return ReplaceInstUsesWith(I, LHS);
4276
4277 bool Op0Ordered;
4278 bool Op1Ordered;
4279 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4280 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4281 if (Op1Pred == 0) {
4282 std::swap(LHS, RHS);
4283 std::swap(Op0Pred, Op1Pred);
4284 std::swap(Op0Ordered, Op1Ordered);
4285 }
4286 if (Op0Pred == 0) {
4287 // uno && ueq -> uno && (uno || eq) -> ueq
4288 // ord && olt -> ord && (ord && lt) -> olt
4289 if (Op0Ordered == Op1Ordered)
4290 return ReplaceInstUsesWith(I, RHS);
4291
4292 // uno && oeq -> uno && (ord && eq) -> false
4293 // uno && ord -> false
4294 if (!Op0Ordered)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004295 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004296 // ord && ueq -> ord && (uno || eq) -> oeq
4297 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4298 Op0LHS, Op0RHS, Context));
4299 }
4300 }
4301
4302 return 0;
4303}
4304
Chris Lattner0631ea72008-11-16 05:06:21 +00004305
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004306Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4307 bool Changed = SimplifyCommutative(I);
4308 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4309
4310 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00004311 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004312
4313 // and X, X = X
4314 if (Op0 == Op1)
4315 return ReplaceInstUsesWith(I, Op1);
4316
4317 // See if we can simplify any instructions used by the instruction whose sole
4318 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004319 if (SimplifyDemandedInstructionBits(I))
4320 return &I;
4321 if (isa<VectorType>(I.getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004322 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4323 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4324 return ReplaceInstUsesWith(I, I.getOperand(0));
4325 } else if (isa<ConstantAggregateZero>(Op1)) {
4326 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4327 }
4328 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00004329
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004330 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00004331 const APInt &AndRHSMask = AndRHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004332 APInt NotAndRHS(~AndRHSMask);
4333
4334 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner4580d452009-10-11 22:00:32 +00004335 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004336 Value *Op0LHS = Op0I->getOperand(0);
4337 Value *Op0RHS = Op0I->getOperand(1);
4338 switch (Op0I->getOpcode()) {
Chris Lattner4580d452009-10-11 22:00:32 +00004339 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004340 case Instruction::Xor:
4341 case Instruction::Or:
4342 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner4580d452009-10-11 22:00:32 +00004343 if (!Op0I->hasOneUse()) break;
4344
4345 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4346 // Not masking anything out for the LHS, move to RHS.
4347 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4348 Op0RHS->getName()+".masked");
4349 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4350 }
4351 if (!isa<Constant>(Op0RHS) &&
4352 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4353 // Not masking anything out for the RHS, move to LHS.
4354 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4355 Op0LHS->getName()+".masked");
4356 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004357 }
4358
4359 break;
4360 case Instruction::Add:
4361 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4362 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4363 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4364 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004365 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004366 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004367 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004368 break;
4369
4370 case Instruction::Sub:
4371 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4372 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4373 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4374 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004375 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004376
Nick Lewyckya349ba42008-07-10 05:51:40 +00004377 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4378 // has 1's for all bits that the subtraction with A might affect.
4379 if (Op0I->hasOneUse()) {
4380 uint32_t BitWidth = AndRHSMask.getBitWidth();
4381 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4382 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4383
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004384 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004385 if (!(A && A->isZero()) && // avoid infinite recursion.
4386 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004387 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004388 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4389 }
4390 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004391 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004392
4393 case Instruction::Shl:
4394 case Instruction::LShr:
4395 // (1 << x) & 1 --> zext(x == 0)
4396 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004397 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004398 Value *NewICmp =
4399 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004400 return new ZExtInst(NewICmp, I.getType());
4401 }
4402 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004403 }
4404
4405 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4406 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4407 return Res;
4408 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4409 // If this is an integer truncation or change from signed-to-unsigned, and
4410 // if the source is an and/or with immediate, transform it. This
4411 // frequently occurs for bitfield accesses.
4412 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4413 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4414 CastOp->getNumOperands() == 2)
Chris Lattner6e060db2009-10-26 15:40:07 +00004415 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004416 if (CastOp->getOpcode() == Instruction::And) {
4417 // Change: and (cast (and X, C1) to T), C2
4418 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4419 // This will fold the two constants together, which may allow
4420 // other simplifications.
Chris Lattnerc7694852009-08-30 07:44:24 +00004421 Value *NewCast = Builder->CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004422 CastOp->getOperand(0), I.getType(),
4423 CastOp->getName()+".shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004424 // trunc_or_bitcast(C1)&C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004425 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004426 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004427 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004428 } else if (CastOp->getOpcode() == Instruction::Or) {
4429 // Change: and (cast (or X, C1) to T), C2
4430 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004431 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004432 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00004433 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004434 return ReplaceInstUsesWith(I, AndRHS);
4435 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004436 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004437 }
4438 }
4439
4440 // Try to fold constant and into select arguments.
4441 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4442 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4443 return R;
4444 if (isa<PHINode>(Op0))
4445 if (Instruction *NV = FoldOpIntoPhi(I))
4446 return NV;
4447 }
4448
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004449 Value *Op0NotVal = dyn_castNotVal(Op0);
4450 Value *Op1NotVal = dyn_castNotVal(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004451
4452 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersonaac28372009-07-31 20:28:14 +00004453 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004454
4455 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4456 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004457 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4458 I.getName()+".demorgan");
Dan Gohmancdff2122009-08-12 16:23:25 +00004459 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004460 }
4461
4462 {
4463 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004464 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004465 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4466 return ReplaceInstUsesWith(I, Op1);
4467
4468 // (A|B) & ~(A&B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004469 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004470 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004471 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004472 }
4473 }
4474
Dan Gohmancdff2122009-08-12 16:23:25 +00004475 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004476 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4477 return ReplaceInstUsesWith(I, Op0);
4478
4479 // ~(A&B) & (A|B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004480 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004481 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004482 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004483 }
4484 }
4485
4486 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004487 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004488 if (A == Op1) { // (A^B)&A -> A&(A^B)
4489 I.swapOperands(); // Simplify below
4490 std::swap(Op0, Op1);
4491 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4492 cast<BinaryOperator>(Op0)->swapOperands();
4493 I.swapOperands(); // Simplify below
4494 std::swap(Op0, Op1);
4495 }
4496 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004497
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004498 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004499 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004500 if (B == Op0) { // B&(A^B) -> B&(B^A)
4501 cast<BinaryOperator>(Op1)->swapOperands();
4502 std::swap(A, B);
4503 }
Chris Lattnerc7694852009-08-30 07:44:24 +00004504 if (A == Op0) // A&(A^B) -> A & ~B
4505 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004506 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004507
4508 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00004509 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4510 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004511 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004512 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4513 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004514 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004515 }
4516
4517 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4518 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004519 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004520 return R;
4521
Chris Lattner0631ea72008-11-16 05:06:21 +00004522 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4523 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4524 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004525 }
4526
4527 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4528 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4529 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4530 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4531 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004532 if (SrcTy == Op1C->getOperand(0)->getType() &&
4533 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004534 // Only do this if the casts both really cause code to be generated.
4535 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4536 I.getType(), TD) &&
4537 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4538 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004539 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4540 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004541 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004542 }
4543 }
4544
4545 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4546 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4547 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4548 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4549 SI0->getOperand(1) == SI1->getOperand(1) &&
4550 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004551 Value *NewOp =
4552 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4553 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004554 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004555 SI1->getOperand(1));
4556 }
4557 }
4558
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004559 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004560 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004561 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4562 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4563 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004564 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004565
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004566 return Changed ? &I : 0;
4567}
4568
Chris Lattner567f5112008-10-05 02:13:19 +00004569/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4570/// capable of providing pieces of a bswap. The subexpression provides pieces
4571/// of a bswap if it is proven that each of the non-zero bytes in the output of
4572/// the expression came from the corresponding "byte swapped" byte in some other
4573/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4574/// we know that the expression deposits the low byte of %X into the high byte
4575/// of the bswap result and that all other bytes are zero. This expression is
4576/// accepted, the high byte of ByteValues is set to X to indicate a correct
4577/// match.
4578///
4579/// This function returns true if the match was unsuccessful and false if so.
4580/// On entry to the function the "OverallLeftShift" is a signed integer value
4581/// indicating the number of bytes that the subexpression is later shifted. For
4582/// example, if the expression is later right shifted by 16 bits, the
4583/// OverallLeftShift value would be -2 on entry. This is used to specify which
4584/// byte of ByteValues is actually being set.
4585///
4586/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4587/// byte is masked to zero by a user. For example, in (X & 255), X will be
4588/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4589/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4590/// always in the local (OverallLeftShift) coordinate space.
4591///
4592static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4593 SmallVector<Value*, 8> &ByteValues) {
4594 if (Instruction *I = dyn_cast<Instruction>(V)) {
4595 // If this is an or instruction, it may be an inner node of the bswap.
4596 if (I->getOpcode() == Instruction::Or) {
4597 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4598 ByteValues) ||
4599 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4600 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004601 }
Chris Lattner567f5112008-10-05 02:13:19 +00004602
4603 // If this is a logical shift by a constant multiple of 8, recurse with
4604 // OverallLeftShift and ByteMask adjusted.
4605 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4606 unsigned ShAmt =
4607 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4608 // Ensure the shift amount is defined and of a byte value.
4609 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4610 return true;
4611
4612 unsigned ByteShift = ShAmt >> 3;
4613 if (I->getOpcode() == Instruction::Shl) {
4614 // X << 2 -> collect(X, +2)
4615 OverallLeftShift += ByteShift;
4616 ByteMask >>= ByteShift;
4617 } else {
4618 // X >>u 2 -> collect(X, -2)
4619 OverallLeftShift -= ByteShift;
4620 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004621 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004622 }
4623
4624 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4625 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4626
4627 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4628 ByteValues);
4629 }
4630
4631 // If this is a logical 'and' with a mask that clears bytes, clear the
4632 // corresponding bytes in ByteMask.
4633 if (I->getOpcode() == Instruction::And &&
4634 isa<ConstantInt>(I->getOperand(1))) {
4635 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4636 unsigned NumBytes = ByteValues.size();
4637 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4638 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4639
4640 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4641 // If this byte is masked out by a later operation, we don't care what
4642 // the and mask is.
4643 if ((ByteMask & (1 << i)) == 0)
4644 continue;
4645
4646 // If the AndMask is all zeros for this byte, clear the bit.
4647 APInt MaskB = AndMask & Byte;
4648 if (MaskB == 0) {
4649 ByteMask &= ~(1U << i);
4650 continue;
4651 }
4652
4653 // If the AndMask is not all ones for this byte, it's not a bytezap.
4654 if (MaskB != Byte)
4655 return true;
4656
4657 // Otherwise, this byte is kept.
4658 }
4659
4660 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4661 ByteValues);
4662 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004663 }
4664
Chris Lattner567f5112008-10-05 02:13:19 +00004665 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4666 // the input value to the bswap. Some observations: 1) if more than one byte
4667 // is demanded from this input, then it could not be successfully assembled
4668 // into a byteswap. At least one of the two bytes would not be aligned with
4669 // their ultimate destination.
4670 if (!isPowerOf2_32(ByteMask)) return true;
4671 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004672
Chris Lattner567f5112008-10-05 02:13:19 +00004673 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4674 // is demanded, it needs to go into byte 0 of the result. This means that the
4675 // byte needs to be shifted until it lands in the right byte bucket. The
4676 // shift amount depends on the position: if the byte is coming from the high
4677 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4678 // low part, it must be shifted left.
4679 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4680 if (InputByteNo < ByteValues.size()/2) {
4681 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4682 return true;
4683 } else {
4684 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4685 return true;
4686 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004687
4688 // If the destination byte value is already defined, the values are or'd
4689 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004690 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004691 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004692 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004693 return false;
4694}
4695
4696/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4697/// If so, insert the new bswap intrinsic and return it.
4698Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4699 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004700 if (!ITy || ITy->getBitWidth() % 16 ||
4701 // ByteMask only allows up to 32-byte values.
4702 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004703 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4704
4705 /// ByteValues - For each byte of the result, we keep track of which value
4706 /// defines each byte.
4707 SmallVector<Value*, 8> ByteValues;
4708 ByteValues.resize(ITy->getBitWidth()/8);
4709
4710 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004711 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4712 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004713 return 0;
4714
4715 // Check to see if all of the bytes come from the same value.
4716 Value *V = ByteValues[0];
4717 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4718
4719 // Check to make sure that all of the bytes come from the same value.
4720 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4721 if (ByteValues[i] != V)
4722 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004723 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004724 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004725 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004726 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004727}
4728
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004729/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4730/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4731/// we can simplify this expression to "cond ? C : D or B".
4732static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004733 Value *C, Value *D,
4734 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004735 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004736 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004737 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004738 return 0;
4739
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004740 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00004741 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004742 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00004743 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004744 return SelectInst::Create(Cond, C, B);
4745 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00004746 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004747 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00004748 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004749 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004750 return 0;
4751}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004752
Chris Lattner0c678e52008-11-16 05:20:07 +00004753/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4754Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4755 ICmpInst *LHS, ICmpInst *RHS) {
4756 Value *Val, *Val2;
4757 ConstantInt *LHSCst, *RHSCst;
4758 ICmpInst::Predicate LHSCC, RHSCC;
4759
4760 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004761 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004762 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004763 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004764 m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00004765 return 0;
4766
4767 // From here on, we only handle:
4768 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4769 if (Val != Val2) return 0;
4770
4771 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4772 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4773 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4774 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4775 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4776 return 0;
4777
4778 // We can't fold (ugt x, C) | (sgt x, C2).
4779 if (!PredicatesFoldable(LHSCC, RHSCC))
4780 return 0;
4781
4782 // Ensure that the larger constant is on the RHS.
4783 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004784 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0c678e52008-11-16 05:20:07 +00004785 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004786 CmpInst::isSigned(RHSCC)))
Chris Lattner0c678e52008-11-16 05:20:07 +00004787 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4788 else
4789 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4790
4791 if (ShouldSwap) {
4792 std::swap(LHS, RHS);
4793 std::swap(LHSCst, RHSCst);
4794 std::swap(LHSCC, RHSCC);
4795 }
4796
4797 // At this point, we know we have have two icmp instructions
4798 // comparing a value against two constants and or'ing the result
4799 // together. Because of the above check, we know that we only have
4800 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4801 // FoldICmpLogical check above), that the two constants are not
4802 // equal.
4803 assert(LHSCst != RHSCst && "Compares not folded above?");
4804
4805 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004806 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004807 case ICmpInst::ICMP_EQ:
4808 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004809 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004810 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004811 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004812 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00004813 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004814 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004815 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohmane6803b82009-08-25 23:17:54 +00004816 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004817 }
4818 break; // (X == 13 | X == 15) -> no change
4819 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4820 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4821 break;
4822 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4823 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4824 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4825 return ReplaceInstUsesWith(I, RHS);
4826 }
4827 break;
4828 case ICmpInst::ICMP_NE:
4829 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004830 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004831 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4832 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4833 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4834 return ReplaceInstUsesWith(I, LHS);
4835 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4836 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4837 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004838 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004839 }
4840 break;
4841 case ICmpInst::ICMP_ULT:
4842 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004843 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004844 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4845 break;
4846 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4847 // If RHSCst is [us]MAXINT, it is always false. Not handling
4848 // this can cause overflow.
4849 if (RHSCst->isMaxValue(false))
4850 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004851 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004852 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004853 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4854 break;
4855 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4856 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4857 return ReplaceInstUsesWith(I, RHS);
4858 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4859 break;
4860 }
4861 break;
4862 case ICmpInst::ICMP_SLT:
4863 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004864 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004865 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4866 break;
4867 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4868 // If RHSCst is [us]MAXINT, it is always false. Not handling
4869 // this can cause overflow.
4870 if (RHSCst->isMaxValue(true))
4871 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004872 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004873 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004874 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4875 break;
4876 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4877 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4878 return ReplaceInstUsesWith(I, RHS);
4879 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4880 break;
4881 }
4882 break;
4883 case ICmpInst::ICMP_UGT:
4884 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004885 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004886 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4887 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4888 return ReplaceInstUsesWith(I, LHS);
4889 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4890 break;
4891 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4892 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004893 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004894 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4895 break;
4896 }
4897 break;
4898 case ICmpInst::ICMP_SGT:
4899 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004900 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004901 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4902 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4903 return ReplaceInstUsesWith(I, LHS);
4904 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4905 break;
4906 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4907 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004908 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004909 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4910 break;
4911 }
4912 break;
4913 }
4914 return 0;
4915}
4916
Chris Lattner57e66fa2009-07-23 05:46:22 +00004917Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4918 FCmpInst *RHS) {
4919 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4920 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4921 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4922 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4923 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4924 // If either of the constants are nans, then the whole thing returns
4925 // true.
4926 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004927 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004928
4929 // Otherwise, no need to compare the two constants, compare the
4930 // rest.
Dan Gohmane6803b82009-08-25 23:17:54 +00004931 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004932 LHS->getOperand(0), RHS->getOperand(0));
4933 }
4934
4935 // Handle vector zeros. This occurs because the canonical form of
4936 // "fcmp uno x,x" is "fcmp uno x, 0".
4937 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4938 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004939 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004940 LHS->getOperand(0), RHS->getOperand(0));
4941
4942 return 0;
4943 }
4944
4945 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4946 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4947 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4948
4949 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4950 // Swap RHS operands to match LHS.
4951 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4952 std::swap(Op1LHS, Op1RHS);
4953 }
4954 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4955 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4956 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004957 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004958 Op0LHS, Op0RHS);
4959 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004960 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004961 if (Op0CC == FCmpInst::FCMP_FALSE)
4962 return ReplaceInstUsesWith(I, RHS);
4963 if (Op1CC == FCmpInst::FCMP_FALSE)
4964 return ReplaceInstUsesWith(I, LHS);
4965 bool Op0Ordered;
4966 bool Op1Ordered;
4967 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4968 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4969 if (Op0Ordered == Op1Ordered) {
4970 // If both are ordered or unordered, return a new fcmp with
4971 // or'ed predicates.
4972 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4973 Op0LHS, Op0RHS, Context);
4974 if (Instruction *I = dyn_cast<Instruction>(RV))
4975 return I;
4976 // Otherwise, it's a constant boolean value...
4977 return ReplaceInstUsesWith(I, RV);
4978 }
4979 }
4980 return 0;
4981}
4982
Bill Wendlingdae376a2008-12-01 08:23:25 +00004983/// FoldOrWithConstants - This helper function folds:
4984///
Bill Wendling236a1192008-12-02 05:09:00 +00004985/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004986///
4987/// into:
4988///
Bill Wendling236a1192008-12-02 05:09:00 +00004989/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004990///
Bill Wendling236a1192008-12-02 05:09:00 +00004991/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004992Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004993 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004994 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4995 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004996
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004997 Value *V1 = 0;
4998 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004999 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00005000
Bill Wendling86ee3162008-12-02 06:18:11 +00005001 APInt Xor = CI1->getValue() ^ CI2->getValue();
5002 if (!Xor.isAllOnesValue()) return 0;
5003
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00005004 if (V1 == A || V1 == B) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005005 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00005006 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005007 }
5008
5009 return 0;
5010}
5011
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005012Instruction *InstCombiner::visitOr(BinaryOperator &I) {
5013 bool Changed = SimplifyCommutative(I);
5014 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5015
5016 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersonaac28372009-07-31 20:28:14 +00005017 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005018
5019 // or X, X = X
5020 if (Op0 == Op1)
5021 return ReplaceInstUsesWith(I, Op0);
5022
5023 // See if we can simplify any instructions used by the instruction whose sole
5024 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005025 if (SimplifyDemandedInstructionBits(I))
5026 return &I;
5027 if (isa<VectorType>(I.getType())) {
5028 if (isa<ConstantAggregateZero>(Op1)) {
5029 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
5030 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
5031 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
5032 return ReplaceInstUsesWith(I, I.getOperand(1));
5033 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005034 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005035
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005036 // or X, -1 == -1
5037 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5038 ConstantInt *C1 = 0; Value *X = 0;
5039 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00005040 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005041 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005042 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005043 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005044 return BinaryOperator::CreateAnd(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005045 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005046 }
5047
5048 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00005049 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005050 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005051 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005052 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005053 return BinaryOperator::CreateXor(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005054 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005055 }
5056
5057 // Try to fold constant and into select arguments.
5058 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5059 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5060 return R;
5061 if (isa<PHINode>(Op0))
5062 if (Instruction *NV = FoldOpIntoPhi(I))
5063 return NV;
5064 }
5065
5066 Value *A = 0, *B = 0;
5067 ConstantInt *C1 = 0, *C2 = 0;
5068
Dan Gohmancdff2122009-08-12 16:23:25 +00005069 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005070 if (A == Op1 || B == Op1) // (A & ?) | A --> A
5071 return ReplaceInstUsesWith(I, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00005072 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005073 if (A == Op0 || B == Op0) // A | (A & ?) --> A
5074 return ReplaceInstUsesWith(I, Op0);
5075
5076 // (A | B) | C and A | (B | C) -> bswap if possible.
5077 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00005078 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5079 match(Op1, m_Or(m_Value(), m_Value())) ||
5080 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5081 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005082 if (Instruction *BSwap = MatchBSwap(I))
5083 return BSwap;
5084 }
5085
5086 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00005087 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005088 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005089 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005090 Value *NOr = Builder->CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005091 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005092 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005093 }
5094
5095 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00005096 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005097 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005098 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005099 Value *NOr = Builder->CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005100 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005101 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005102 }
5103
5104 // (A & C)|(B & D)
5105 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00005106 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5107 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005108 Value *V1 = 0, *V2 = 0, *V3 = 0;
5109 C1 = dyn_cast<ConstantInt>(C);
5110 C2 = dyn_cast<ConstantInt>(D);
5111 if (C1 && C2) { // (A & C1)|(B & C2)
5112 // If we have: ((V + N) & C1) | (V & C2)
5113 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5114 // replace with V+N.
5115 if (C1->getValue() == ~C2->getValue()) {
5116 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohmancdff2122009-08-12 16:23:25 +00005117 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005118 // Add commutes, try both ways.
5119 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5120 return ReplaceInstUsesWith(I, A);
5121 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5122 return ReplaceInstUsesWith(I, A);
5123 }
5124 // Or commutes, try both ways.
5125 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005126 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005127 // Add commutes, try both ways.
5128 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5129 return ReplaceInstUsesWith(I, B);
5130 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5131 return ReplaceInstUsesWith(I, B);
5132 }
5133 }
5134 V1 = 0; V2 = 0; V3 = 0;
5135 }
5136
5137 // Check to see if we have any common things being and'ed. If so, find the
5138 // terms for V1 & (V2|V3).
5139 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5140 if (A == B) // (A & C)|(A & D) == A & (C|D)
5141 V1 = A, V2 = C, V3 = D;
5142 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5143 V1 = A, V2 = B, V3 = C;
5144 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5145 V1 = C, V2 = A, V3 = D;
5146 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5147 V1 = C, V2 = A, V3 = B;
5148
5149 if (V1) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005150 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00005151 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005152 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005153 }
Dan Gohman279952c2008-10-28 22:38:57 +00005154
Dan Gohman35b76162008-10-30 20:40:10 +00005155 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00005156 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005157 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005158 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005159 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005160 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005161 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005162 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005163 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00005164
Bill Wendling22ca8352008-11-30 13:52:49 +00005165 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005166 if ((match(C, m_Not(m_Specific(D))) &&
5167 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005168 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00005169 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005170 if ((match(A, m_Not(m_Specific(D))) &&
5171 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005172 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00005173 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005174 if ((match(C, m_Not(m_Specific(B))) &&
5175 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005176 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00005177 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005178 if ((match(A, m_Not(m_Specific(B))) &&
5179 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005180 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005181 }
5182
5183 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
5184 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5185 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5186 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
5187 SI0->getOperand(1) == SI1->getOperand(1) &&
5188 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005189 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5190 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005191 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005192 SI1->getOperand(1));
5193 }
5194 }
5195
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005196 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00005197 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5198 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00005199 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005200 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005201 }
5202 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00005203 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5204 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00005205 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005206 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005207 }
5208
Chris Lattner6e060db2009-10-26 15:40:07 +00005209 if ((A = dyn_castNotVal(Op0))) { // ~A | Op1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005210 if (A == Op1) // ~A | A == -1
Owen Andersonaac28372009-07-31 20:28:14 +00005211 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005212 } else {
5213 A = 0;
5214 }
5215 // Note, A is still live here!
Chris Lattner6e060db2009-10-26 15:40:07 +00005216 if ((B = dyn_castNotVal(Op1))) { // Op0 | ~B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005217 if (Op0 == B)
Owen Andersonaac28372009-07-31 20:28:14 +00005218 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005219
5220 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5221 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005222 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohmancdff2122009-08-12 16:23:25 +00005223 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005224 }
5225 }
5226
5227 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5228 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005229 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005230 return R;
5231
Chris Lattner0c678e52008-11-16 05:20:07 +00005232 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5233 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5234 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005235 }
5236
5237 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005238 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005239 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5240 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00005241 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5242 !isa<ICmpInst>(Op1C->getOperand(0))) {
5243 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00005244 if (SrcTy == Op1C->getOperand(0)->getType() &&
5245 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00005246 // Only do this if the casts both really cause code to be
5247 // generated.
5248 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5249 I.getType(), TD) &&
5250 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5251 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005252 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5253 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005254 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00005255 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005256 }
5257 }
Chris Lattner91882432007-10-24 05:38:08 +00005258 }
5259
5260
5261 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5262 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00005263 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5264 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5265 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00005266 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005267
5268 return Changed ? &I : 0;
5269}
5270
Dan Gohman089efff2008-05-13 00:00:25 +00005271namespace {
5272
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005273// XorSelf - Implements: X ^ X --> 0
5274struct XorSelf {
5275 Value *RHS;
5276 XorSelf(Value *rhs) : RHS(rhs) {}
5277 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5278 Instruction *apply(BinaryOperator &Xor) const {
5279 return &Xor;
5280 }
5281};
5282
Dan Gohman089efff2008-05-13 00:00:25 +00005283}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005284
5285Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5286 bool Changed = SimplifyCommutative(I);
5287 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5288
Evan Chenge5cd8032008-03-25 20:07:13 +00005289 if (isa<UndefValue>(Op1)) {
5290 if (isa<UndefValue>(Op0))
5291 // Handle undef ^ undef -> 0 special case. This is a common
5292 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00005293 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005294 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005295 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005296
5297 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005298 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005299 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00005300 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005301 }
5302
5303 // See if we can simplify any instructions used by the instruction whose sole
5304 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005305 if (SimplifyDemandedInstructionBits(I))
5306 return &I;
5307 if (isa<VectorType>(I.getType()))
5308 if (isa<ConstantAggregateZero>(Op1))
5309 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005310
5311 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005312 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005313 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5314 if (Op0I->getOpcode() == Instruction::And ||
5315 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner6e060db2009-10-26 15:40:07 +00005316 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5317 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5318 if (dyn_castNotVal(Op0I->getOperand(1)))
5319 Op0I->swapOperands();
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005320 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005321 Value *NotY =
5322 Builder->CreateNot(Op0I->getOperand(1),
5323 Op0I->getOperand(1)->getName()+".not");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005324 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005325 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattnerc7694852009-08-30 07:44:24 +00005326 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005327 }
Chris Lattner6e060db2009-10-26 15:40:07 +00005328
5329 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5330 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5331 if (isFreeToInvert(Op0I->getOperand(0)) &&
5332 isFreeToInvert(Op0I->getOperand(1))) {
5333 Value *NotX =
5334 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5335 Value *NotY =
5336 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5337 if (Op0I->getOpcode() == Instruction::And)
5338 return BinaryOperator::CreateOr(NotX, NotY);
5339 return BinaryOperator::CreateAnd(NotX, NotY);
5340 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005341 }
5342 }
5343 }
5344
5345
5346 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00005347 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005348 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005349 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005350 return new ICmpInst(ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005351 ICI->getOperand(0), ICI->getOperand(1));
5352
Nick Lewycky1405e922007-08-06 20:04:16 +00005353 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005354 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005355 FCI->getOperand(0), FCI->getOperand(1));
5356 }
5357
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005358 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5359 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5360 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5361 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5362 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattnerc7694852009-08-30 07:44:24 +00005363 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5364 (RHS == ConstantExpr::getCast(Opcode,
5365 ConstantInt::getTrue(*Context),
5366 Op0C->getDestTy()))) {
5367 CI->setPredicate(CI->getInversePredicate());
5368 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005369 }
5370 }
5371 }
5372 }
5373
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005374 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5375 // ~(c-X) == X-c-1 == X+(-c-1)
5376 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5377 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005378 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5379 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005380 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005381 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005382 }
5383
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005384 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005385 if (Op0I->getOpcode() == Instruction::Add) {
5386 // ~(X-c) --> (-c-1)-X
5387 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005388 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005389 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00005390 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005391 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00005392 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005393 } else if (RHS->getValue().isSignBit()) {
5394 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005395 Constant *C = ConstantInt::get(*Context,
5396 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005397 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005398
5399 }
5400 } else if (Op0I->getOpcode() == Instruction::Or) {
5401 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5402 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005403 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005404 // Anything in both C1 and C2 is known to be zero, remove it from
5405 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00005406 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5407 NewRHS = ConstantExpr::getAnd(NewRHS,
5408 ConstantExpr::getNot(CommonBits));
Chris Lattner3183fb62009-08-30 06:13:40 +00005409 Worklist.Add(Op0I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005410 I.setOperand(0, Op0I->getOperand(0));
5411 I.setOperand(1, NewRHS);
5412 return &I;
5413 }
5414 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005415 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005416 }
5417
5418 // Try to fold constant and into select arguments.
5419 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5420 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5421 return R;
5422 if (isa<PHINode>(Op0))
5423 if (Instruction *NV = FoldOpIntoPhi(I))
5424 return NV;
5425 }
5426
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005427 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005428 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00005429 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005430
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005431 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005432 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00005433 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005434
5435
5436 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5437 if (Op1I) {
5438 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005439 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005440 if (A == Op0) { // B^(B|A) == (A|B)^B
5441 Op1I->swapOperands();
5442 I.swapOperands();
5443 std::swap(Op0, Op1);
5444 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5445 I.swapOperands(); // Simplified below.
5446 std::swap(Op0, Op1);
5447 }
Dan Gohmancdff2122009-08-12 16:23:25 +00005448 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005449 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005450 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005451 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005452 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005453 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005454 if (A == Op0) { // A^(A&B) -> A^(B&A)
5455 Op1I->swapOperands();
5456 std::swap(A, B);
5457 }
5458 if (B == Op0) { // A^(B&A) -> (B&A)^A
5459 I.swapOperands(); // Simplified below.
5460 std::swap(Op0, Op1);
5461 }
5462 }
5463 }
5464
5465 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5466 if (Op0I) {
5467 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005468 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005469 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005470 if (A == Op1) // (B|A)^B == (A|B)^B
5471 std::swap(A, B);
Chris Lattnerc7694852009-08-30 07:44:24 +00005472 if (B == Op1) // (A|B)^B == A & ~B
5473 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohmancdff2122009-08-12 16:23:25 +00005474 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005475 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005476 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005477 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005478 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005479 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005480 if (A == Op1) // (A&B)^A -> (B&A)^A
5481 std::swap(A, B);
5482 if (B == Op1 && // (B&A)^A == ~B & A
5483 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerc7694852009-08-30 07:44:24 +00005484 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005485 }
5486 }
5487 }
5488
5489 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5490 if (Op0I && Op1I && Op0I->isShift() &&
5491 Op0I->getOpcode() == Op1I->getOpcode() &&
5492 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5493 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005494 Value *NewOp =
5495 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5496 Op0I->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005497 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005498 Op1I->getOperand(1));
5499 }
5500
5501 if (Op0I && Op1I) {
5502 Value *A, *B, *C, *D;
5503 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005504 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5505 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005506 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005507 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005508 }
5509 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005510 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5511 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005512 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005513 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005514 }
5515
5516 // (A & B)^(C & D)
5517 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005518 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5519 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005520 // (X & Y)^(X & Y) -> (Y^Z) & X
5521 Value *X = 0, *Y = 0, *Z = 0;
5522 if (A == C)
5523 X = A, Y = B, Z = D;
5524 else if (A == D)
5525 X = A, Y = B, Z = C;
5526 else if (B == C)
5527 X = B, Y = A, Z = D;
5528 else if (B == D)
5529 X = B, Y = A, Z = C;
5530
5531 if (X) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005532 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005533 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005534 }
5535 }
5536 }
5537
5538 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5539 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005540 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005541 return R;
5542
5543 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005544 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005545 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5546 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5547 const Type *SrcTy = Op0C->getOperand(0)->getType();
5548 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5549 // Only do this if the casts both really cause code to be generated.
5550 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5551 I.getType(), TD) &&
5552 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5553 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005554 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5555 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005556 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005557 }
5558 }
Chris Lattner91882432007-10-24 05:38:08 +00005559 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005560
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005561 return Changed ? &I : 0;
5562}
5563
Owen Anderson24be4c12009-07-03 00:17:18 +00005564static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005565 LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005566 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005567}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005568
Dan Gohman8fd520a2009-06-15 22:12:54 +00005569static bool HasAddOverflow(ConstantInt *Result,
5570 ConstantInt *In1, ConstantInt *In2,
5571 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005572 if (IsSigned)
5573 if (In2->getValue().isNegative())
5574 return Result->getValue().sgt(In1->getValue());
5575 else
5576 return Result->getValue().slt(In1->getValue());
5577 else
5578 return Result->getValue().ult(In1->getValue());
5579}
5580
Dan Gohman8fd520a2009-06-15 22:12:54 +00005581/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005582/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005583static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005584 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005585 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005586 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005587
Dan Gohman8fd520a2009-06-15 22:12:54 +00005588 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5589 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005590 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005591 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5592 ExtractElement(In1, Idx, Context),
5593 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005594 IsSigned))
5595 return true;
5596 }
5597 return false;
5598 }
5599
5600 return HasAddOverflow(cast<ConstantInt>(Result),
5601 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5602 IsSigned);
5603}
5604
5605static bool HasSubOverflow(ConstantInt *Result,
5606 ConstantInt *In1, ConstantInt *In2,
5607 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005608 if (IsSigned)
5609 if (In2->getValue().isNegative())
5610 return Result->getValue().slt(In1->getValue());
5611 else
5612 return Result->getValue().sgt(In1->getValue());
5613 else
5614 return Result->getValue().ugt(In1->getValue());
5615}
5616
Dan Gohman8fd520a2009-06-15 22:12:54 +00005617/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5618/// overflowed for this type.
5619static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005620 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005621 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005622 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005623
5624 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5625 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005626 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005627 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5628 ExtractElement(In1, Idx, Context),
5629 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005630 IsSigned))
5631 return true;
5632 }
5633 return false;
5634 }
5635
5636 return HasSubOverflow(cast<ConstantInt>(Result),
5637 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5638 IsSigned);
5639}
5640
Chris Lattnereba75862008-04-22 02:53:33 +00005641
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005642/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5643/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohman17f46f72009-07-28 01:40:03 +00005644Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005645 ICmpInst::Predicate Cond,
5646 Instruction &I) {
Chris Lattnereba75862008-04-22 02:53:33 +00005647 // Look through bitcasts.
5648 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5649 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005650
5651 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohman17f46f72009-07-28 01:40:03 +00005652 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005653 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005654 // This transformation (ignoring the base and scales) is valid because we
Dan Gohman17f46f72009-07-28 01:40:03 +00005655 // know pointers can't overflow since the gep is inbounds. See if we can
5656 // output an optimized form.
Chris Lattnereba75862008-04-22 02:53:33 +00005657 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5658
5659 // If not, synthesize the offset the hard way.
5660 if (Offset == 0)
Chris Lattner93e6ff92009-11-04 08:05:20 +00005661 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005662 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonaac28372009-07-31 20:28:14 +00005663 Constant::getNullValue(Offset->getType()));
Dan Gohman17f46f72009-07-28 01:40:03 +00005664 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005665 // If the base pointers are different, but the indices are the same, just
5666 // compare the base pointer.
5667 if (PtrBase != GEPRHS->getOperand(0)) {
5668 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5669 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5670 GEPRHS->getOperand(0)->getType();
5671 if (IndicesTheSame)
5672 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5673 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5674 IndicesTheSame = false;
5675 break;
5676 }
5677
5678 // If all indices are the same, just compare the base pointers.
5679 if (IndicesTheSame)
Dan Gohmane6803b82009-08-25 23:17:54 +00005680 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005681 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5682
5683 // Otherwise, the base pointers are different and the indices are
5684 // different, bail out.
5685 return 0;
5686 }
5687
5688 // If one of the GEPs has all zero indices, recurse.
5689 bool AllZeros = true;
5690 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5691 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5692 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5693 AllZeros = false;
5694 break;
5695 }
5696 if (AllZeros)
5697 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5698 ICmpInst::getSwappedPredicate(Cond), I);
5699
5700 // If the other GEP has all zero indices, recurse.
5701 AllZeros = true;
5702 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5703 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5704 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5705 AllZeros = false;
5706 break;
5707 }
5708 if (AllZeros)
5709 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5710
5711 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5712 // If the GEPs only differ by one index, compare it.
5713 unsigned NumDifferences = 0; // Keep track of # differences.
5714 unsigned DiffOperand = 0; // The operand that differs.
5715 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5716 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5717 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5718 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5719 // Irreconcilable differences.
5720 NumDifferences = 2;
5721 break;
5722 } else {
5723 if (NumDifferences++) break;
5724 DiffOperand = i;
5725 }
5726 }
5727
5728 if (NumDifferences == 0) // SAME GEP?
5729 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson35b47072009-08-13 21:58:54 +00005730 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005731 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005732
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005733 else if (NumDifferences == 1) {
5734 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5735 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5736 // Make sure we do a signed comparison here.
Dan Gohmane6803b82009-08-25 23:17:54 +00005737 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005738 }
5739 }
5740
5741 // Only lower this if the icmp is the only user of the GEP or if we expect
5742 // the result to fold to a constant!
Dan Gohmana80e2712009-07-21 23:21:54 +00005743 if (TD &&
5744 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005745 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5746 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner93e6ff92009-11-04 08:05:20 +00005747 Value *L = EmitGEPOffset(GEPLHS, *this);
5748 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005749 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005750 }
5751 }
5752 return 0;
5753}
5754
Chris Lattnere6b62d92008-05-19 20:18:56 +00005755/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5756///
5757Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5758 Instruction *LHSI,
5759 Constant *RHSC) {
5760 if (!isa<ConstantFP>(RHSC)) return 0;
5761 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5762
5763 // Get the width of the mantissa. We don't want to hack on conversions that
5764 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005765 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005766 if (MantissaWidth == -1) return 0; // Unknown.
5767
5768 // Check to see that the input is converted from an integer type that is small
5769 // enough that preserves all bits. TODO: check here for "known" sign bits.
5770 // 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 +00005771 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005772
5773 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005774 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5775 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005776 ++InputSize;
5777
5778 // If the conversion would lose info, don't hack on this.
5779 if ((int)InputSize > MantissaWidth)
5780 return 0;
5781
5782 // Otherwise, we can potentially simplify the comparison. We know that it
5783 // will always come through as an integer value and we know the constant is
5784 // not a NAN (it would have been previously simplified).
5785 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5786
5787 ICmpInst::Predicate Pred;
5788 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005789 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnere6b62d92008-05-19 20:18:56 +00005790 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005791 case FCmpInst::FCMP_OEQ:
5792 Pred = ICmpInst::ICMP_EQ;
5793 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005794 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005795 case FCmpInst::FCMP_OGT:
5796 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5797 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005798 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005799 case FCmpInst::FCMP_OGE:
5800 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5801 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005802 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005803 case FCmpInst::FCMP_OLT:
5804 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5805 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005806 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005807 case FCmpInst::FCMP_OLE:
5808 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5809 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005810 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005811 case FCmpInst::FCMP_ONE:
5812 Pred = ICmpInst::ICMP_NE;
5813 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005814 case FCmpInst::FCMP_ORD:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005815 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005816 case FCmpInst::FCMP_UNO:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005817 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005818 }
5819
5820 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5821
5822 // Now we know that the APFloat is a normal number, zero or inf.
5823
Chris Lattnerf13ff492008-05-20 03:50:52 +00005824 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005825 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005826 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005827
Bill Wendling20636df2008-11-09 04:26:50 +00005828 if (!LHSUnsigned) {
5829 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5830 // and large values.
5831 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5832 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5833 APFloat::rmNearestTiesToEven);
5834 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5835 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5836 Pred == ICmpInst::ICMP_SLE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005837 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5838 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005839 }
5840 } else {
5841 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5842 // +INF and large values.
5843 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5844 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5845 APFloat::rmNearestTiesToEven);
5846 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5847 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5848 Pred == ICmpInst::ICMP_ULE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005849 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5850 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005851 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005852 }
5853
Bill Wendling20636df2008-11-09 04:26:50 +00005854 if (!LHSUnsigned) {
5855 // See if the RHS value is < SignedMin.
5856 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5857 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5858 APFloat::rmNearestTiesToEven);
5859 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5860 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5861 Pred == ICmpInst::ICMP_SGE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005862 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5863 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005864 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005865 }
5866
Bill Wendling20636df2008-11-09 04:26:50 +00005867 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5868 // [0, UMAX], but it may still be fractional. See if it is fractional by
5869 // casting the FP value to the integer value and back, checking for equality.
5870 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005871 Constant *RHSInt = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005872 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5873 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005874 if (!RHS.isZero()) {
5875 bool Equal = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005876 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5877 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005878 if (!Equal) {
5879 // If we had a comparison against a fractional value, we have to adjust
5880 // the compare predicate and sometimes the value. RHSC is rounded towards
5881 // zero at this point.
5882 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005883 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng14118132009-05-22 23:10:53 +00005884 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005885 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005886 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00005887 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005888 case ICmpInst::ICMP_ULE:
5889 // (float)int <= 4.4 --> int <= 4
5890 // (float)int <= -4.4 --> false
5891 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005892 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005893 break;
5894 case ICmpInst::ICMP_SLE:
5895 // (float)int <= 4.4 --> int <= 4
5896 // (float)int <= -4.4 --> int < -4
5897 if (RHS.isNegative())
5898 Pred = ICmpInst::ICMP_SLT;
5899 break;
5900 case ICmpInst::ICMP_ULT:
5901 // (float)int < -4.4 --> false
5902 // (float)int < 4.4 --> int <= 4
5903 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005904 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005905 Pred = ICmpInst::ICMP_ULE;
5906 break;
5907 case ICmpInst::ICMP_SLT:
5908 // (float)int < -4.4 --> int < -4
5909 // (float)int < 4.4 --> int <= 4
5910 if (!RHS.isNegative())
5911 Pred = ICmpInst::ICMP_SLE;
5912 break;
5913 case ICmpInst::ICMP_UGT:
5914 // (float)int > 4.4 --> int > 4
5915 // (float)int > -4.4 --> true
5916 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005917 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005918 break;
5919 case ICmpInst::ICMP_SGT:
5920 // (float)int > 4.4 --> int > 4
5921 // (float)int > -4.4 --> int >= -4
5922 if (RHS.isNegative())
5923 Pred = ICmpInst::ICMP_SGE;
5924 break;
5925 case ICmpInst::ICMP_UGE:
5926 // (float)int >= -4.4 --> true
5927 // (float)int >= 4.4 --> int > 4
5928 if (!RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005929 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005930 Pred = ICmpInst::ICMP_UGT;
5931 break;
5932 case ICmpInst::ICMP_SGE:
5933 // (float)int >= -4.4 --> int >= -4
5934 // (float)int >= 4.4 --> int > 4
5935 if (!RHS.isNegative())
5936 Pred = ICmpInst::ICMP_SGT;
5937 break;
5938 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005939 }
5940 }
5941
5942 // Lower this FP comparison into an appropriate integer version of the
5943 // comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00005944 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00005945}
5946
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005947Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5948 bool Changed = SimplifyCompare(I);
5949 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5950
5951 // Fold trivial predicates.
5952 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner41c09932009-09-02 05:12:37 +00005953 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005954 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner41c09932009-09-02 05:12:37 +00005955 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005956
5957 // Simplify 'fcmp pred X, X'
5958 if (Op0 == Op1) {
5959 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005960 default: llvm_unreachable("Unknown predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005961 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5962 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5963 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner41c09932009-09-02 05:12:37 +00005964 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005965 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5966 case FCmpInst::FCMP_OLT: // True if ordered and less than
5967 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner41c09932009-09-02 05:12:37 +00005968 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005969
5970 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5971 case FCmpInst::FCMP_ULT: // True if unordered or less than
5972 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5973 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5974 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5975 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersonaac28372009-07-31 20:28:14 +00005976 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005977 return &I;
5978
5979 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5980 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5981 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5982 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5983 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5984 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersonaac28372009-07-31 20:28:14 +00005985 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005986 return &I;
5987 }
5988 }
5989
5990 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner41c09932009-09-02 05:12:37 +00005991 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005992
5993 // Handle fcmp with constant RHS
5994 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005995 // If the constant is a nan, see if we can fold the comparison based on it.
5996 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5997 if (CFP->getValueAPF().isNaN()) {
5998 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson4f720fa2009-07-31 17:39:07 +00005999 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnerf13ff492008-05-20 03:50:52 +00006000 assert(FCmpInst::isUnordered(I.getPredicate()) &&
6001 "Comparison must be either ordered or unordered!");
6002 // True if unordered.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006003 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00006004 }
6005 }
6006
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006007 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6008 switch (LHSI->getOpcode()) {
6009 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00006010 // Only fold fcmp into the PHI if the phi and fcmp are in the same
6011 // block. If in the same block, we're encouraging jump threading. If
6012 // not, we are just pessimizing the code by making an i1 phi.
6013 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00006014 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00006015 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006016 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00006017 case Instruction::SIToFP:
6018 case Instruction::UIToFP:
6019 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6020 return NV;
6021 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006022 case Instruction::Select:
6023 // If either operand of the select is a constant, we can fold the
6024 // comparison into the select arms, which will cause one to be
6025 // constant folded and the select turned into a bitwise or.
6026 Value *Op1 = 0, *Op2 = 0;
6027 if (LHSI->hasOneUse()) {
6028 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6029 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006030 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006031 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006032 Op2 = Builder->CreateFCmp(I.getPredicate(),
6033 LHSI->getOperand(2), RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006034 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6035 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006036 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006037 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006038 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6039 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006040 }
6041 }
6042
6043 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006044 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006045 break;
6046 }
6047 }
6048
6049 return Changed ? &I : 0;
6050}
6051
6052Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6053 bool Changed = SimplifyCompare(I);
6054 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6055 const Type *Ty = Op0->getType();
6056
6057 // icmp X, X
6058 if (Op0 == Op1)
Chris Lattner41c09932009-09-02 05:12:37 +00006059 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewycky09284cf2008-05-17 07:33:39 +00006060 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006061
6062 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner41c09932009-09-02 05:12:37 +00006063 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lambf78cd322007-12-18 21:32:20 +00006064
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006065 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
6066 // addresses never equal each other! We already know that Op0 != Op1.
Chris Lattner95ac4eb2009-10-05 02:47:47 +00006067 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006068 isa<ConstantPointerNull>(Op0)) &&
Chris Lattner95ac4eb2009-10-05 02:47:47 +00006069 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006070 isa<ConstantPointerNull>(Op1)))
Owen Anderson35b47072009-08-13 21:58:54 +00006071 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00006072 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006073
6074 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson35b47072009-08-13 21:58:54 +00006075 if (Ty == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006076 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006077 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00006078 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattnerc7694852009-08-30 07:44:24 +00006079 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmancdff2122009-08-12 16:23:25 +00006080 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006081 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006082 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00006083 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006084
6085 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00006086 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006087 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006088 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattnerc7694852009-08-30 07:44:24 +00006089 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00006090 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006091 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006092 case ICmpInst::ICMP_SGT:
6093 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006094 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006095 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00006096 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006097 return BinaryOperator::CreateAnd(Not, Op0);
6098 }
6099 case ICmpInst::ICMP_UGE:
6100 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6101 // FALL THROUGH
6102 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattnerc7694852009-08-30 07:44:24 +00006103 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00006104 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006105 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006106 case ICmpInst::ICMP_SGE:
6107 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6108 // FALL THROUGH
6109 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00006110 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006111 return BinaryOperator::CreateOr(Not, Op0);
6112 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006113 }
6114 }
6115
Dan Gohman7934d592009-04-25 17:12:48 +00006116 unsigned BitWidth = 0;
6117 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00006118 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6119 else if (Ty->isIntOrIntVector())
6120 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00006121
6122 bool isSignBit = false;
6123
Dan Gohman58c09632008-09-16 18:46:06 +00006124 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006125 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00006126 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00006127
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006128 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6129 if (I.isEquality() && CI->isNullValue() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006130 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006131 // (icmp cond A B) if cond is equality
Dan Gohmane6803b82009-08-25 23:17:54 +00006132 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00006133 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006134
Dan Gohman58c09632008-09-16 18:46:06 +00006135 // If we have an icmp le or icmp ge instruction, turn it into the
6136 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6137 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00006138 switch (I.getPredicate()) {
6139 default: break;
6140 case ICmpInst::ICMP_ULE:
6141 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006142 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006143 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006144 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006145 case ICmpInst::ICMP_SLE:
6146 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006147 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006148 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006149 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006150 case ICmpInst::ICMP_UGE:
6151 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006152 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006153 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006154 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006155 case ICmpInst::ICMP_SGE:
6156 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006157 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006158 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006159 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006160 }
6161
Chris Lattnera1308652008-07-11 05:40:05 +00006162 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006163 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006164 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006165 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6166 }
6167
6168 // See if we can fold the comparison based on range information we can get
6169 // by checking whether bits are known to be zero or one in the input.
6170 if (BitWidth != 0) {
6171 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6172 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6173
6174 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006175 isSignBit ? APInt::getSignBit(BitWidth)
6176 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006177 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006178 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006179 if (SimplifyDemandedBits(I.getOperandUse(1),
6180 APInt::getAllOnesValue(BitWidth),
6181 Op1KnownZero, Op1KnownOne, 0))
6182 return &I;
6183
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006184 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006185 // in. Compute the Min, Max and RHS values based on the known bits. For the
6186 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006187 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6188 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006189 if (I.isSigned()) {
Dan Gohman7934d592009-04-25 17:12:48 +00006190 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6191 Op0Min, Op0Max);
6192 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6193 Op1Min, Op1Max);
6194 } else {
6195 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6196 Op0Min, Op0Max);
6197 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6198 Op1Min, Op1Max);
6199 }
6200
Chris Lattnera1308652008-07-11 05:40:05 +00006201 // If Min and Max are known to be the same, then SimplifyDemandedBits
6202 // figured out that the LHS is a constant. Just constant fold this now so
6203 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006204 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006205 return new ICmpInst(I.getPredicate(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006206 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006207 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006208 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006209 ConstantInt::get(*Context, Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006210
Chris Lattnera1308652008-07-11 05:40:05 +00006211 // Based on the range information we know about the LHS, see if we can
6212 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006213 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006214 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner62d0f232008-07-11 05:08:55 +00006215 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006216 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006217 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006218 break;
6219 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006220 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006221 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006222 break;
6223 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006224 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006225 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006226 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006227 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006228 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006229 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006230 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6231 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006232 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006233 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006234
6235 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6236 if (CI->isMinValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006237 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006238 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006239 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006240 break;
6241 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006242 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006243 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006244 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006245 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006246
6247 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006248 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006249 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6250 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006251 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006252 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006253
6254 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6255 if (CI->isMaxValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006256 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006257 Constant::getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006258 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006259 break;
6260 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006261 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006262 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006263 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006264 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006265 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006266 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006267 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6268 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006269 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006270 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006271 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006272 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006273 case ICmpInst::ICMP_SGT:
6274 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006275 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006276 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006277 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006278
6279 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006280 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006281 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6282 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006283 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006284 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006285 }
6286 break;
6287 case ICmpInst::ICMP_SGE:
6288 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6289 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006290 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006291 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006292 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006293 break;
6294 case ICmpInst::ICMP_SLE:
6295 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6296 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006297 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006298 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006299 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006300 break;
6301 case ICmpInst::ICMP_UGE:
6302 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6303 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006304 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006305 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006306 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006307 break;
6308 case ICmpInst::ICMP_ULE:
6309 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6310 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006311 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006312 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006313 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006314 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006315 }
Dan Gohman7934d592009-04-25 17:12:48 +00006316
6317 // Turn a signed comparison into an unsigned one if both operands
6318 // are known to have the same sign.
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006319 if (I.isSigned() &&
Dan Gohman7934d592009-04-25 17:12:48 +00006320 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6321 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohmane6803b82009-08-25 23:17:54 +00006322 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006323 }
6324
6325 // Test if the ICmpInst instruction is used exclusively by a select as
6326 // part of a minimum or maximum operation. If so, refrain from doing
6327 // any other folding. This helps out other analyses which understand
6328 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6329 // and CodeGen. And in this case, at least one of the comparison
6330 // operands has at least one user besides the compare (the select),
6331 // which would often largely negate the benefit of folding anyway.
6332 if (I.hasOneUse())
6333 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6334 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6335 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6336 return 0;
6337
6338 // See if we are doing a comparison between a constant and an instruction that
6339 // can be folded into the comparison.
6340 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006341 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6342 // instruction, see if that instruction also has constants so that the
6343 // instruction can be folded into the icmp
6344 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6345 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6346 return Res;
6347 }
6348
6349 // Handle icmp with constant (but not simple integer constant) RHS
6350 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6351 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6352 switch (LHSI->getOpcode()) {
6353 case Instruction::GetElementPtr:
6354 if (RHSC->isNullValue()) {
6355 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6356 bool isAllZeros = true;
6357 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6358 if (!isa<Constant>(LHSI->getOperand(i)) ||
6359 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6360 isAllZeros = false;
6361 break;
6362 }
6363 if (isAllZeros)
Dan Gohmane6803b82009-08-25 23:17:54 +00006364 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersonaac28372009-07-31 20:28:14 +00006365 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006366 }
6367 break;
6368
6369 case Instruction::PHI:
Chris Lattner9b61abd2009-09-27 20:46:36 +00006370 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattnera2417ba2008-06-08 20:52:11 +00006371 // block. If in the same block, we're encouraging jump threading. If
6372 // not, we are just pessimizing the code by making an i1 phi.
6373 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00006374 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00006375 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006376 break;
6377 case Instruction::Select: {
6378 // If either operand of the select is a constant, we can fold the
6379 // comparison into the select arms, which will cause one to be
6380 // constant folded and the select turned into a bitwise or.
6381 Value *Op1 = 0, *Op2 = 0;
6382 if (LHSI->hasOneUse()) {
6383 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6384 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006385 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006386 // Insert a new ICmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006387 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6388 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006389 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6390 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006391 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006392 // Insert a new ICmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006393 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6394 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006395 }
6396 }
6397
6398 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006399 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006400 break;
6401 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006402 case Instruction::Call:
6403 // If we have (malloc != null), and if the malloc has a single use, we
6404 // can assume it is successful and remove the malloc.
6405 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6406 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez67439f02009-10-21 19:11:40 +00006407 // Need to explicitly erase malloc call here, instead of adding it to
6408 // Worklist, because it won't get DCE'd from the Worklist since
6409 // isInstructionTriviallyDead() returns false for function calls.
6410 // It is OK to replace LHSI/MallocCall with Undef because the
6411 // instruction that uses it will be erased via Worklist.
6412 if (extractMallocCall(LHSI)) {
6413 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6414 EraseInstFromFunction(*LHSI);
6415 return ReplaceInstUsesWith(I,
Victor Hernandez48c3c542009-09-18 22:35:49 +00006416 ConstantInt::get(Type::getInt1Ty(*Context),
6417 !I.isTrueWhenEqual()));
Victor Hernandez67439f02009-10-21 19:11:40 +00006418 }
6419 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6420 if (MallocCall->hasOneUse()) {
6421 MallocCall->replaceAllUsesWith(
6422 UndefValue::get(MallocCall->getType()));
6423 EraseInstFromFunction(*MallocCall);
6424 Worklist.Add(LHSI); // The malloc's bitcast use.
6425 return ReplaceInstUsesWith(I,
6426 ConstantInt::get(Type::getInt1Ty(*Context),
6427 !I.isTrueWhenEqual()));
6428 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006429 }
6430 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006431 }
6432 }
6433
6434 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohman17f46f72009-07-28 01:40:03 +00006435 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006436 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6437 return NI;
Dan Gohman17f46f72009-07-28 01:40:03 +00006438 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006439 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6440 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6441 return NI;
6442
6443 // Test to see if the operands of the icmp are casted versions of other
6444 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6445 // now.
6446 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6447 if (isa<PointerType>(Op0->getType()) &&
6448 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6449 // We keep moving the cast from the left operand over to the right
6450 // operand, where it can often be eliminated completely.
6451 Op0 = CI->getOperand(0);
6452
6453 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6454 // so eliminate it as well.
6455 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6456 Op1 = CI2->getOperand(0);
6457
6458 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006459 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006460 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00006461 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006462 } else {
6463 // Otherwise, cast the RHS right before the icmp
Chris Lattner78628292009-08-30 19:47:22 +00006464 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006465 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006466 }
Dan Gohmane6803b82009-08-25 23:17:54 +00006467 return new ICmpInst(I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006468 }
6469 }
6470
6471 if (isa<CastInst>(Op0)) {
6472 // Handle the special case of: icmp (cast bool to X), <cst>
6473 // This comes up when you have code like
6474 // int X = A < B;
6475 // if (X) ...
6476 // For generality, we handle any zero-extension of any operand comparison
6477 // with a constant or another cast from the same type.
6478 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6479 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6480 return R;
6481 }
6482
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006483 // See if it's the same type of instruction on the left and right.
6484 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6485 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006486 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006487 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006488 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006489 default: break;
6490 case Instruction::Add:
6491 case Instruction::Sub:
6492 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006493 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohmane6803b82009-08-25 23:17:54 +00006494 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006495 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006496 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6497 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6498 if (CI->getValue().isSignBit()) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006499 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006500 ? I.getUnsignedPredicate()
6501 : I.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006502 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006503 Op1I->getOperand(0));
6504 }
6505
6506 if (CI->getValue().isMaxSignedValue()) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006507 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006508 ? I.getUnsignedPredicate()
6509 : I.getSignedPredicate();
6510 Pred = I.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006511 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006512 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006513 }
6514 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006515 break;
6516 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006517 if (!I.isEquality())
6518 break;
6519
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006520 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6521 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6522 // Mask = -1 >> count-trailing-zeros(Cst).
6523 if (!CI->isZero() && !CI->isOne()) {
6524 const APInt &AP = CI->getValue();
Owen Andersoneacb44d2009-07-24 23:12:02 +00006525 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006526 APInt::getLowBitsSet(AP.getBitWidth(),
6527 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006528 AP.countTrailingZeros()));
Chris Lattnerc7694852009-08-30 07:44:24 +00006529 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6530 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohmane6803b82009-08-25 23:17:54 +00006531 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006532 }
6533 }
6534 break;
6535 }
6536 }
6537 }
6538 }
6539
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006540 // ~x < ~y --> y < x
6541 { Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00006542 if (match(Op0, m_Not(m_Value(A))) &&
6543 match(Op1, m_Not(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006544 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006545 }
6546
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006547 if (I.isEquality()) {
6548 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006549
6550 // -x == -y --> x == y
Dan Gohmancdff2122009-08-12 16:23:25 +00006551 if (match(Op0, m_Neg(m_Value(A))) &&
6552 match(Op1, m_Neg(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006553 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006554
Dan Gohmancdff2122009-08-12 16:23:25 +00006555 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006556 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6557 Value *OtherVal = A == Op1 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006558 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006559 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006560 }
6561
Dan Gohmancdff2122009-08-12 16:23:25 +00006562 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006563 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006564 ConstantInt *C1, *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00006565 if (match(B, m_ConstantInt(C1)) &&
6566 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006567 Constant *NC =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006568 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnerc7694852009-08-30 07:44:24 +00006569 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6570 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattner3b874082008-11-16 05:38:51 +00006571 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006572
6573 // A^B == A^D -> B == D
Dan Gohmane6803b82009-08-25 23:17:54 +00006574 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6575 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6576 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6577 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006578 }
6579 }
6580
Dan Gohmancdff2122009-08-12 16:23:25 +00006581 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006582 (A == Op0 || B == Op0)) {
6583 // A == (A^B) -> B == 0
6584 Value *OtherVal = A == Op0 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006585 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006586 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006587 }
Chris Lattner3b874082008-11-16 05:38:51 +00006588
6589 // (A-B) == A -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006590 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006591 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006592 Constant::getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006593
6594 // A == (A-B) -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006595 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006596 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006597 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006598
6599 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6600 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006601 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6602 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006603 Value *X = 0, *Y = 0, *Z = 0;
6604
6605 if (A == C) {
6606 X = B; Y = D; Z = A;
6607 } else if (A == D) {
6608 X = B; Y = C; Z = A;
6609 } else if (B == C) {
6610 X = A; Y = D; Z = B;
6611 } else if (B == D) {
6612 X = A; Y = C; Z = B;
6613 }
6614
6615 if (X) { // Build (X^Y) & Z
Chris Lattnerc7694852009-08-30 07:44:24 +00006616 Op1 = Builder->CreateXor(X, Y, "tmp");
6617 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006618 I.setOperand(0, Op1);
Owen Andersonaac28372009-07-31 20:28:14 +00006619 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006620 return &I;
6621 }
6622 }
6623 }
6624 return Changed ? &I : 0;
6625}
6626
6627
6628/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6629/// and CmpRHS are both known to be integer constants.
6630Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6631 ConstantInt *DivRHS) {
6632 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6633 const APInt &CmpRHSV = CmpRHS->getValue();
6634
6635 // FIXME: If the operand types don't match the type of the divide
6636 // then don't attempt this transform. The code below doesn't have the
6637 // logic to deal with a signed divide and an unsigned compare (and
6638 // vice versa). This is because (x /s C1) <s C2 produces different
6639 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6640 // (x /u C1) <u C2. Simply casting the operands and result won't
6641 // work. :( The if statement below tests that condition and bails
6642 // if it finds it.
6643 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006644 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006645 return 0;
6646 if (DivRHS->isZero())
6647 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006648 if (DivIsSigned && DivRHS->isAllOnesValue())
6649 return 0; // The overflow computation also screws up here
6650 if (DivRHS->isOne())
6651 return 0; // Not worth bothering, and eliminates some funny cases
6652 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006653
6654 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6655 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6656 // C2 (CI). By solving for X we can turn this into a range check
6657 // instead of computing a divide.
Owen Anderson02b48c32009-07-29 18:55:55 +00006658 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006659
6660 // Determine if the product overflows by seeing if the product is
6661 // not equal to the divide. Make sure we do the same kind of divide
6662 // as in the LHS instruction that we're folding.
Owen Anderson02b48c32009-07-29 18:55:55 +00006663 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6664 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006665
6666 // Get the ICmp opcode
6667 ICmpInst::Predicate Pred = ICI.getPredicate();
6668
6669 // Figure out the interval that is being checked. For example, a comparison
6670 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6671 // Compute this interval based on the constants involved and the signedness of
6672 // the compare/divide. This computes a half-open interval, keeping track of
6673 // whether either value in the interval overflows. After analysis each
6674 // overflow variable is set to 0 if it's corresponding bound variable is valid
6675 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6676 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006677 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006678
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006679 if (!DivIsSigned) { // udiv
6680 // e.g. X/5 op 3 --> [15, 20)
6681 LoBound = Prod;
6682 HiOverflow = LoOverflow = ProdOV;
6683 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006684 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006685 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006686 if (CmpRHSV == 0) { // (X / pos) op 0
6687 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006688 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006689 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006690 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006691 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6692 HiOverflow = LoOverflow = ProdOV;
6693 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006694 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006695 } else { // (X / pos) op neg
6696 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006697 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006698 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6699 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006700 ConstantInt* DivNeg =
Owen Anderson02b48c32009-07-29 18:55:55 +00006701 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Anderson24be4c12009-07-03 00:17:18 +00006702 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006703 true) ? -1 : 0;
6704 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006705 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006706 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006707 if (CmpRHSV == 0) { // (X / neg) op 0
6708 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006709 LoBound = AddOne(DivRHS);
Owen Anderson02b48c32009-07-29 18:55:55 +00006710 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006711 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6712 HiOverflow = 1; // [INTMIN+1, overflow)
6713 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6714 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006715 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006716 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006717 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006718 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6719 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006720 LoOverflow = AddWithOverflow(LoBound, HiBound,
6721 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006722 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006723 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6724 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006725 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006726 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006727 }
6728
6729 // Dividing by a negative swaps the condition. LT <-> GT
6730 Pred = ICmpInst::getSwappedPredicate(Pred);
6731 }
6732
6733 Value *X = DivI->getOperand(0);
6734 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006735 default: llvm_unreachable("Unhandled icmp opcode!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006736 case ICmpInst::ICMP_EQ:
6737 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006738 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006739 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006740 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006741 ICmpInst::ICMP_UGE, X, LoBound);
6742 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006743 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006744 ICmpInst::ICMP_ULT, X, HiBound);
6745 else
6746 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6747 case ICmpInst::ICMP_NE:
6748 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006749 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006750 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006751 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006752 ICmpInst::ICMP_ULT, X, LoBound);
6753 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006754 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006755 ICmpInst::ICMP_UGE, X, HiBound);
6756 else
6757 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6758 case ICmpInst::ICMP_ULT:
6759 case ICmpInst::ICMP_SLT:
6760 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006761 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006762 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006763 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006764 return new ICmpInst(Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006765 case ICmpInst::ICMP_UGT:
6766 case ICmpInst::ICMP_SGT:
6767 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006768 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006769 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006770 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006771 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohmane6803b82009-08-25 23:17:54 +00006772 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006773 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006774 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006775 }
6776}
6777
6778
6779/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6780///
6781Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6782 Instruction *LHSI,
6783 ConstantInt *RHS) {
6784 const APInt &RHSV = RHS->getValue();
6785
6786 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006787 case Instruction::Trunc:
6788 if (ICI.isEquality() && LHSI->hasOneUse()) {
6789 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6790 // of the high bits truncated out of x are known.
6791 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6792 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6793 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6794 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6795 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6796
6797 // If all the high bits are known, we can do this xform.
6798 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6799 // Pull in the high bits from known-ones set.
6800 APInt NewRHS(RHS->getValue());
6801 NewRHS.zext(SrcBits);
6802 NewRHS |= KnownOne;
Dan Gohmane6803b82009-08-25 23:17:54 +00006803 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006804 ConstantInt::get(*Context, NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00006805 }
6806 }
6807 break;
6808
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006809 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6810 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6811 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6812 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006813 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6814 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006815 Value *CompareVal = LHSI->getOperand(0);
6816
6817 // If the sign bit of the XorCST is not set, there is no change to
6818 // the operation, just stop using the Xor.
6819 if (!XorCST->getValue().isNegative()) {
6820 ICI.setOperand(0, CompareVal);
Chris Lattner3183fb62009-08-30 06:13:40 +00006821 Worklist.Add(LHSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006822 return &ICI;
6823 }
6824
6825 // Was the old condition true if the operand is positive?
6826 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6827
6828 // If so, the new one isn't.
6829 isTrueIfPositive ^= true;
6830
6831 if (isTrueIfPositive)
Dan Gohmane6803b82009-08-25 23:17:54 +00006832 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006833 SubOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006834 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006835 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006836 AddOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006837 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006838
6839 if (LHSI->hasOneUse()) {
6840 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6841 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6842 const APInt &SignBit = XorCST->getValue();
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006843 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewyckydac84332009-01-31 21:30:05 +00006844 ? ICI.getUnsignedPredicate()
6845 : ICI.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006846 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006847 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006848 }
6849
6850 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006851 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006852 const APInt &NotSignBit = XorCST->getValue();
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006853 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewyckydac84332009-01-31 21:30:05 +00006854 ? ICI.getUnsignedPredicate()
6855 : ICI.getSignedPredicate();
6856 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006857 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006858 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006859 }
6860 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006861 }
6862 break;
6863 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6864 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6865 LHSI->getOperand(0)->hasOneUse()) {
6866 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6867
6868 // If the LHS is an AND of a truncating cast, we can widen the
6869 // and/compare to be the input width without changing the value
6870 // produced, eliminating a cast.
6871 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6872 // We can do this transformation if either the AND constant does not
6873 // have its sign bit set or if it is an equality comparison.
6874 // Extending a relational comparison when we're checking the sign
6875 // bit would not work.
6876 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006877 (ICI.isEquality() ||
6878 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006879 uint32_t BitWidth =
6880 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6881 APInt NewCST = AndCST->getValue();
6882 NewCST.zext(BitWidth);
6883 APInt NewCI = RHSV;
6884 NewCI.zext(BitWidth);
Chris Lattnerc7694852009-08-30 07:44:24 +00006885 Value *NewAnd =
6886 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006887 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00006888 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006889 ConstantInt::get(*Context, NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006890 }
6891 }
6892
6893 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6894 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6895 // happens a LOT in code produced by the C front-end, for bitfield
6896 // access.
6897 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6898 if (Shift && !Shift->isShift())
6899 Shift = 0;
6900
6901 ConstantInt *ShAmt;
6902 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6903 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6904 const Type *AndTy = AndCST->getType(); // Type of the and.
6905
6906 // We can fold this as long as we can't shift unknown bits
6907 // into the mask. This can only happen with signed shift
6908 // rights, as they sign-extend.
6909 if (ShAmt) {
6910 bool CanFold = Shift->isLogicalShift();
6911 if (!CanFold) {
6912 // To test for the bad case of the signed shr, see if any
6913 // of the bits shifted in could be tested after the mask.
6914 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6915 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6916
6917 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6918 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6919 AndCST->getValue()) == 0)
6920 CanFold = true;
6921 }
6922
6923 if (CanFold) {
6924 Constant *NewCst;
6925 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006926 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006927 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006928 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006929
6930 // Check to see if we are shifting out any of the bits being
6931 // compared.
Owen Anderson02b48c32009-07-29 18:55:55 +00006932 if (ConstantExpr::get(Shift->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00006933 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006934 // If we shifted bits out, the fold is not going to work out.
6935 // As a special case, check to see if this means that the
6936 // result is always true or false now.
6937 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006938 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006939 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006940 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006941 } else {
6942 ICI.setOperand(1, NewCst);
6943 Constant *NewAndCST;
6944 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006945 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006946 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006947 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006948 LHSI->setOperand(1, NewAndCST);
6949 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +00006950 Worklist.Add(Shift); // Shift is dead.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006951 return &ICI;
6952 }
6953 }
6954 }
6955
6956 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6957 // preferable because it allows the C<<Y expression to be hoisted out
6958 // of a loop if Y is invariant and X is not.
6959 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00006960 ICI.isEquality() && !Shift->isArithmeticShift() &&
6961 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006962 // Compute C << Y.
6963 Value *NS;
6964 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerc7694852009-08-30 07:44:24 +00006965 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006966 } else {
6967 // Insert a logical shift.
Chris Lattnerc7694852009-08-30 07:44:24 +00006968 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006969 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006970
6971 // Compute X & (C << Y).
Chris Lattnerc7694852009-08-30 07:44:24 +00006972 Value *NewAnd =
6973 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006974
6975 ICI.setOperand(0, NewAnd);
6976 return &ICI;
6977 }
6978 }
6979 break;
6980
6981 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6982 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6983 if (!ShAmt) break;
6984
6985 uint32_t TypeBits = RHSV.getBitWidth();
6986
6987 // Check that the shift amount is in range. If not, don't perform
6988 // undefined shifts. When the shift is visited it will be
6989 // simplified.
6990 if (ShAmt->uge(TypeBits))
6991 break;
6992
6993 if (ICI.isEquality()) {
6994 // If we are comparing against bits always shifted out, the
6995 // comparison cannot succeed.
6996 Constant *Comp =
Owen Anderson02b48c32009-07-29 18:55:55 +00006997 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Anderson24be4c12009-07-03 00:17:18 +00006998 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006999 if (Comp != RHS) {// Comparing against a bit that we know is zero.
7000 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00007001 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007002 return ReplaceInstUsesWith(ICI, Cst);
7003 }
7004
7005 if (LHSI->hasOneUse()) {
7006 // Otherwise strength reduce the shift into an and.
7007 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7008 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007009 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Anderson24be4c12009-07-03 00:17:18 +00007010 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007011
Chris Lattnerc7694852009-08-30 07:44:24 +00007012 Value *And =
7013 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007014 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007015 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007016 }
7017 }
7018
7019 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7020 bool TrueIfSigned = false;
7021 if (LHSI->hasOneUse() &&
7022 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7023 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneacb44d2009-07-24 23:12:02 +00007024 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007025 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattnerc7694852009-08-30 07:44:24 +00007026 Value *And =
7027 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007028 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00007029 And, Constant::getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007030 }
7031 break;
7032 }
7033
7034 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
7035 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007036 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007037 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00007038 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007039
Chris Lattner5ee84f82008-03-21 05:19:58 +00007040 // Check that the shift amount is in range. If not, don't perform
7041 // undefined shifts. When the shift is visited it will be
7042 // simplified.
7043 uint32_t TypeBits = RHSV.getBitWidth();
7044 if (ShAmt->uge(TypeBits))
7045 break;
7046
7047 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007048
Chris Lattner5ee84f82008-03-21 05:19:58 +00007049 // If we are comparing against bits always shifted out, the
7050 // comparison cannot succeed.
7051 APInt Comp = RHSV << ShAmtVal;
7052 if (LHSI->getOpcode() == Instruction::LShr)
7053 Comp = Comp.lshr(ShAmtVal);
7054 else
7055 Comp = Comp.ashr(ShAmtVal);
7056
7057 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7058 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00007059 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00007060 return ReplaceInstUsesWith(ICI, Cst);
7061 }
7062
7063 // Otherwise, check to see if the bits shifted out are known to be zero.
7064 // If so, we can compare against the unshifted value:
7065 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00007066 if (LHSI->hasOneUse() &&
7067 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007068 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007069 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007070 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00007071 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007072
Evan Chengfb9292a2008-04-23 00:38:06 +00007073 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007074 // Otherwise strength reduce the shift into an and.
7075 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007076 Constant *Mask = ConstantInt::get(*Context, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007077
Chris Lattnerc7694852009-08-30 07:44:24 +00007078 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7079 Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007080 return new ICmpInst(ICI.getPredicate(), And,
Owen Anderson02b48c32009-07-29 18:55:55 +00007081 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007082 }
7083 break;
7084 }
7085
7086 case Instruction::SDiv:
7087 case Instruction::UDiv:
7088 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7089 // Fold this div into the comparison, producing a range check.
7090 // Determine, based on the divide type, what the range is being
7091 // checked. If there is an overflow on the low or high side, remember
7092 // it, otherwise compute the range [low, hi) bounding the new value.
7093 // See: InsertRangeTest above for the kinds of replacements possible.
7094 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7095 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7096 DivRHS))
7097 return R;
7098 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007099
7100 case Instruction::Add:
7101 // Fold: icmp pred (add, X, C1), C2
7102
7103 if (!ICI.isEquality()) {
7104 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7105 if (!LHSC) break;
7106 const APInt &LHSV = LHSC->getValue();
7107
7108 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7109 .subtract(LHSV);
7110
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007111 if (ICI.isSigned()) {
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007112 if (CR.getLower().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007113 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007114 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007115 } else if (CR.getUpper().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007116 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007117 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007118 }
7119 } else {
7120 if (CR.getLower().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007121 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007122 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007123 } else if (CR.getUpper().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007124 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007125 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007126 }
7127 }
7128 }
7129 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007130 }
7131
7132 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7133 if (ICI.isEquality()) {
7134 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7135
7136 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7137 // the second operand is a constant, simplify a bit.
7138 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7139 switch (BO->getOpcode()) {
7140 case Instruction::SRem:
7141 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7142 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7143 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7144 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007145 Value *NewRem =
7146 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7147 BO->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00007148 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersonaac28372009-07-31 20:28:14 +00007149 Constant::getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007150 }
7151 }
7152 break;
7153 case Instruction::Add:
7154 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7155 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7156 if (BO->hasOneUse())
Dan Gohmane6803b82009-08-25 23:17:54 +00007157 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007158 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007159 } else if (RHSV == 0) {
7160 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7161 // efficiently invertible, or if the add has just this one use.
7162 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7163
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007164 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohmane6803b82009-08-25 23:17:54 +00007165 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007166 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohmane6803b82009-08-25 23:17:54 +00007167 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007168 else if (BO->hasOneUse()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007169 Value *Neg = Builder->CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007170 Neg->takeName(BO);
Dan Gohmane6803b82009-08-25 23:17:54 +00007171 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007172 }
7173 }
7174 break;
7175 case Instruction::Xor:
7176 // For the xor case, we can xor two constants together, eliminating
7177 // the explicit xor.
7178 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00007179 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007180 ConstantExpr::getXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007181
7182 // FALLTHROUGH
7183 case Instruction::Sub:
7184 // Replace (([sub|xor] A, B) != 0) with (A != B)
7185 if (RHSV == 0)
Dan Gohmane6803b82009-08-25 23:17:54 +00007186 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007187 BO->getOperand(1));
7188 break;
7189
7190 case Instruction::Or:
7191 // If bits are being or'd in that are not present in the constant we
7192 // are comparing against, then the comparison could never succeed!
7193 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007194 Constant *NotCI = ConstantExpr::getNot(RHS);
7195 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00007196 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007197 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007198 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007199 }
7200 break;
7201
7202 case Instruction::And:
7203 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7204 // If bits are being compared against that are and'd out, then the
7205 // comparison can never succeed!
7206 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007207 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007208 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007209 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007210
7211 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7212 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohmane6803b82009-08-25 23:17:54 +00007213 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007214 ICmpInst::ICMP_NE, LHSI,
Owen Andersonaac28372009-07-31 20:28:14 +00007215 Constant::getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007216
7217 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007218 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007219 Value *X = BO->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +00007220 Constant *Zero = Constant::getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007221 ICmpInst::Predicate pred = isICMP_NE ?
7222 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohmane6803b82009-08-25 23:17:54 +00007223 return new ICmpInst(pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007224 }
7225
7226 // ((X & ~7) == 0) --> X < 8
7227 if (RHSV == 0 && isHighOnes(BOC)) {
7228 Value *X = BO->getOperand(0);
Owen Anderson02b48c32009-07-29 18:55:55 +00007229 Constant *NegX = ConstantExpr::getNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007230 ICmpInst::Predicate pred = isICMP_NE ?
7231 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohmane6803b82009-08-25 23:17:54 +00007232 return new ICmpInst(pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007233 }
7234 }
7235 default: break;
7236 }
7237 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7238 // Handle icmp {eq|ne} <intrinsic>, intcst.
7239 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner3183fb62009-08-30 06:13:40 +00007240 Worklist.Add(II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007241 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007242 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007243 return &ICI;
7244 }
7245 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007246 }
7247 return 0;
7248}
7249
7250/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7251/// We only handle extending casts so far.
7252///
7253Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7254 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7255 Value *LHSCIOp = LHSCI->getOperand(0);
7256 const Type *SrcTy = LHSCIOp->getType();
7257 const Type *DestTy = LHSCI->getType();
7258 Value *RHSCIOp;
7259
7260 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7261 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007262 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7263 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007264 cast<IntegerType>(DestTy)->getBitWidth()) {
7265 Value *RHSOp = 0;
7266 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007267 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007268 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7269 RHSOp = RHSC->getOperand(0);
7270 // If the pointer types don't match, insert a bitcast.
7271 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner78628292009-08-30 19:47:22 +00007272 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007273 }
7274
7275 if (RHSOp)
Dan Gohmane6803b82009-08-25 23:17:54 +00007276 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007277 }
7278
7279 // The code below only handles extension cast instructions, so far.
7280 // Enforce this.
7281 if (LHSCI->getOpcode() != Instruction::ZExt &&
7282 LHSCI->getOpcode() != Instruction::SExt)
7283 return 0;
7284
7285 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007286 bool isSignedCmp = ICI.isSigned();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007287
7288 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7289 // Not an extension from the same type?
7290 RHSCIOp = CI->getOperand(0);
7291 if (RHSCIOp->getType() != LHSCIOp->getType())
7292 return 0;
7293
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007294 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007295 // and the other is a zext), then we can't handle this.
7296 if (CI->getOpcode() != LHSCI->getOpcode())
7297 return 0;
7298
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007299 // Deal with equality cases early.
7300 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007301 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007302
7303 // A signed comparison of sign extended values simplifies into a
7304 // signed comparison.
7305 if (isSignedCmp && isSignedExt)
Dan Gohmane6803b82009-08-25 23:17:54 +00007306 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007307
7308 // The other three cases all fold into an unsigned comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00007309 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007310 }
7311
7312 // If we aren't dealing with a constant on the RHS, exit early
7313 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7314 if (!CI)
7315 return 0;
7316
7317 // Compute the constant that would happen if we truncated to SrcTy then
7318 // reextended to DestTy.
Owen Anderson02b48c32009-07-29 18:55:55 +00007319 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7320 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007321 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007322
7323 // If the re-extended constant didn't change...
7324 if (Res2 == CI) {
7325 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7326 // For example, we might have:
Dan Gohman9e1657f2009-06-14 23:30:43 +00007327 // %A = sext i16 %X to i32
7328 // %B = icmp ugt i32 %A, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007329 // It is incorrect to transform this into
Dan Gohman9e1657f2009-06-14 23:30:43 +00007330 // %B = icmp ugt i16 %X, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007331 // because %A may have negative value.
7332 //
Chris Lattner3d816532008-07-11 04:09:09 +00007333 // However, we allow this when the compare is EQ/NE, because they are
7334 // signless.
7335 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007336 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00007337 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007338 }
7339
7340 // The re-extended constant changed so the constant cannot be represented
7341 // in the shorter type. Consequently, we cannot emit a simple comparison.
7342
7343 // First, handle some easy cases. We know the result cannot be equal at this
7344 // point so handle the ICI.isEquality() cases
7345 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007346 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007347 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007348 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007349
7350 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7351 // should have been folded away previously and not enter in here.
7352 Value *Result;
7353 if (isSignedCmp) {
7354 // We're performing a signed comparison.
7355 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00007356 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007357 else
Owen Anderson4f720fa2009-07-31 17:39:07 +00007358 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007359 } else {
7360 // We're performing an unsigned comparison.
7361 if (isSignedExt) {
7362 // We're performing an unsigned comp with a sign extended value.
7363 // This is true if the input is >= 0. [aka >s -1]
Owen Andersonaac28372009-07-31 20:28:14 +00007364 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattnerc7694852009-08-30 07:44:24 +00007365 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007366 } else {
7367 // Unsigned extend & unsigned compare -> always true.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007368 Result = ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007369 }
7370 }
7371
7372 // Finally, return the value computed.
7373 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007374 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007375 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007376
7377 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7378 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7379 "ICmp should be folded!");
7380 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00007381 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohmancdff2122009-08-12 16:23:25 +00007382 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007383}
7384
7385Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7386 return commonShiftTransforms(I);
7387}
7388
7389Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7390 return commonShiftTransforms(I);
7391}
7392
7393Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007394 if (Instruction *R = commonShiftTransforms(I))
7395 return R;
7396
7397 Value *Op0 = I.getOperand(0);
7398
7399 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7400 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7401 if (CSI->isAllOnesValue())
7402 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007403
Dan Gohman2526aea2009-06-16 19:55:29 +00007404 // See if we can turn a signed shr into an unsigned shr.
7405 if (MaskedValueIsZero(Op0,
7406 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7407 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7408
7409 // Arithmetic shifting an all-sign-bit value is a no-op.
7410 unsigned NumSignBits = ComputeNumSignBits(Op0);
7411 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7412 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007413
Chris Lattnere3c504f2007-12-06 01:59:46 +00007414 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007415}
7416
7417Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7418 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7419 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7420
7421 // shl X, 0 == X and shr X, 0 == X
7422 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00007423 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7424 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007425 return ReplaceInstUsesWith(I, Op0);
7426
7427 if (isa<UndefValue>(Op0)) {
7428 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7429 return ReplaceInstUsesWith(I, Op0);
7430 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007431 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007432 }
7433 if (isa<UndefValue>(Op1)) {
7434 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7435 return ReplaceInstUsesWith(I, Op0);
7436 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007437 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007438 }
7439
Dan Gohman2bc21562009-05-21 02:28:33 +00007440 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007441 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007442 return &I;
7443
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007444 // Try to fold constant and into select arguments.
7445 if (isa<Constant>(Op0))
7446 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7447 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7448 return R;
7449
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007450 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7451 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7452 return Res;
7453 return 0;
7454}
7455
7456Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7457 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007458 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007459
7460 // See if we can simplify any instructions used by the instruction whose sole
7461 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007462 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007463
Dan Gohman9e1657f2009-06-14 23:30:43 +00007464 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7465 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007466 //
7467 if (Op1->uge(TypeBits)) {
7468 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007469 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007470 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007471 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007472 return &I;
7473 }
7474 }
7475
7476 // ((X*C1) << C2) == (X * (C1 << C2))
7477 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7478 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7479 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007480 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007481 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007482
7483 // Try to fold constant and into select arguments.
7484 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7485 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7486 return R;
7487 if (isa<PHINode>(Op0))
7488 if (Instruction *NV = FoldOpIntoPhi(I))
7489 return NV;
7490
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007491 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7492 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7493 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7494 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7495 // place. Don't try to do this transformation in this case. Also, we
7496 // require that the input operand is a shift-by-constant so that we have
7497 // confidence that the shifts will get folded together. We could do this
7498 // xform in more cases, but it is unlikely to be profitable.
7499 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7500 isa<ConstantInt>(TrOp->getOperand(1))) {
7501 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00007502 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00007503 // (shift2 (shift1 & 0x00FF), c2)
7504 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007505
7506 // For logical shifts, the truncation has the effect of making the high
7507 // part of the register be zeros. Emulate this by inserting an AND to
7508 // clear the top bits as needed. This 'and' will usually be zapped by
7509 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007510 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7511 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007512 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7513
7514 // The mask we constructed says what the trunc would do if occurring
7515 // between the shifts. We want to know the effect *after* the second
7516 // shift. We know that it is a logical shift by a constant, so adjust the
7517 // mask as appropriate.
7518 if (I.getOpcode() == Instruction::Shl)
7519 MaskV <<= Op1->getZExtValue();
7520 else {
7521 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7522 MaskV = MaskV.lshr(Op1->getZExtValue());
7523 }
7524
Chris Lattnerc7694852009-08-30 07:44:24 +00007525 // shift1 & 0x00FF
7526 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7527 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007528
7529 // Return the value truncated to the interesting size.
7530 return new TruncInst(And, I.getType());
7531 }
7532 }
7533
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007534 if (Op0->hasOneUse()) {
7535 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7536 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7537 Value *V1, *V2;
7538 ConstantInt *CC;
7539 switch (Op0BO->getOpcode()) {
7540 default: break;
7541 case Instruction::Add:
7542 case Instruction::And:
7543 case Instruction::Or:
7544 case Instruction::Xor: {
7545 // These operators commute.
7546 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7547 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007548 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerad7516a2009-08-30 18:50:58 +00007549 m_Specific(Op1)))) {
7550 Value *YS = // (Y << C)
7551 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7552 // (X + (Y << C))
7553 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7554 Op0BO->getOperand(1)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007555 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007556 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007557 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7558 }
7559
7560 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7561 Value *Op0BOOp1 = Op0BO->getOperand(1);
7562 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7563 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007564 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007565 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007566 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007567 Value *YS = // (Y << C)
7568 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7569 Op0BO->getName());
7570 // X & (CC << C)
7571 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7572 V1->getName()+".mask");
Gabor Greifa645dd32008-05-16 19:29:10 +00007573 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007574 }
7575 }
7576
7577 // FALL THROUGH.
7578 case Instruction::Sub: {
7579 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7580 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007581 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007582 m_Specific(Op1)))) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007583 Value *YS = // (Y << C)
7584 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7585 // (X + (Y << C))
7586 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7587 Op0BO->getOperand(0)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007588 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007589 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007590 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7591 }
7592
7593 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7594 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7595 match(Op0BO->getOperand(0),
7596 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007597 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007598 cast<BinaryOperator>(Op0BO->getOperand(0))
7599 ->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007600 Value *YS = // (Y << C)
7601 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7602 // X & (CC << C)
7603 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7604 V1->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007605
Gabor Greifa645dd32008-05-16 19:29:10 +00007606 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007607 }
7608
7609 break;
7610 }
7611 }
7612
7613
7614 // If the operand is an bitwise operator with a constant RHS, and the
7615 // shift is the only use, we can pull it out of the shift.
7616 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7617 bool isValid = true; // Valid only for And, Or, Xor
7618 bool highBitSet = false; // Transform if high bit of constant set?
7619
7620 switch (Op0BO->getOpcode()) {
7621 default: isValid = false; break; // Do not perform transform!
7622 case Instruction::Add:
7623 isValid = isLeftShift;
7624 break;
7625 case Instruction::Or:
7626 case Instruction::Xor:
7627 highBitSet = false;
7628 break;
7629 case Instruction::And:
7630 highBitSet = true;
7631 break;
7632 }
7633
7634 // If this is a signed shift right, and the high bit is modified
7635 // by the logical operation, do not perform the transformation.
7636 // The highBitSet boolean indicates the value of the high bit of
7637 // the constant which would cause it to be modified for this
7638 // operation.
7639 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007640 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007641 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007642
7643 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007644 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007645
Chris Lattnerad7516a2009-08-30 18:50:58 +00007646 Value *NewShift =
7647 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007648 NewShift->takeName(Op0BO);
7649
Gabor Greifa645dd32008-05-16 19:29:10 +00007650 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007651 NewRHS);
7652 }
7653 }
7654 }
7655 }
7656
7657 // Find out if this is a shift of a shift by a constant.
7658 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7659 if (ShiftOp && !ShiftOp->isShift())
7660 ShiftOp = 0;
7661
7662 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7663 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7664 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7665 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7666 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7667 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7668 Value *X = ShiftOp->getOperand(0);
7669
7670 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007671
7672 const IntegerType *Ty = cast<IntegerType>(I.getType());
7673
7674 // Check for (X << c1) << c2 and (X >> c1) >> c2
7675 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007676 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7677 // saturates.
7678 if (AmtSum >= TypeBits) {
7679 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007680 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007681 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7682 }
7683
Gabor Greifa645dd32008-05-16 19:29:10 +00007684 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007685 ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007686 }
7687
7688 if (ShiftOp->getOpcode() == Instruction::LShr &&
7689 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007690 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00007691 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007692
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007693 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00007694 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007695 }
7696
7697 if (ShiftOp->getOpcode() == Instruction::AShr &&
7698 I.getOpcode() == Instruction::LShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007699 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007700 if (AmtSum >= TypeBits)
7701 AmtSum = TypeBits-1;
7702
Chris Lattnerad7516a2009-08-30 18:50:58 +00007703 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007704
7705 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007706 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007707 }
7708
7709 // Okay, if we get here, one shift must be left, and the other shift must be
7710 // right. See if the amounts are equal.
7711 if (ShiftAmt1 == ShiftAmt2) {
7712 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7713 if (I.getOpcode() == Instruction::Shl) {
7714 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007715 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007716 }
7717 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7718 if (I.getOpcode() == Instruction::LShr) {
7719 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007720 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007721 }
7722 // We can simplify ((X << C) >>s C) into a trunc + sext.
7723 // NOTE: we could do this for any C, but that would make 'unusual' integer
7724 // types. For now, just stick to ones well-supported by the code
7725 // generators.
7726 const Type *SExtType = 0;
7727 switch (Ty->getBitWidth() - ShiftAmt1) {
7728 case 1 :
7729 case 8 :
7730 case 16 :
7731 case 32 :
7732 case 64 :
7733 case 128:
Owen Anderson35b47072009-08-13 21:58:54 +00007734 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007735 break;
7736 default: break;
7737 }
Chris Lattnerad7516a2009-08-30 18:50:58 +00007738 if (SExtType)
7739 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007740 // Otherwise, we can't handle it yet.
7741 } else if (ShiftAmt1 < ShiftAmt2) {
7742 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7743
7744 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7745 if (I.getOpcode() == Instruction::Shl) {
7746 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7747 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007748 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007749
7750 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007751 return BinaryOperator::CreateAnd(Shift,
7752 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007753 }
7754
7755 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7756 if (I.getOpcode() == Instruction::LShr) {
7757 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007758 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007759
7760 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007761 return BinaryOperator::CreateAnd(Shift,
7762 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007763 }
7764
7765 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7766 } else {
7767 assert(ShiftAmt2 < ShiftAmt1);
7768 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7769
7770 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7771 if (I.getOpcode() == Instruction::Shl) {
7772 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7773 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007774 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7775 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007776
7777 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007778 return BinaryOperator::CreateAnd(Shift,
7779 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007780 }
7781
7782 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7783 if (I.getOpcode() == Instruction::LShr) {
7784 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007785 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007786
7787 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007788 return BinaryOperator::CreateAnd(Shift,
7789 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007790 }
7791
7792 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7793 }
7794 }
7795 return 0;
7796}
7797
7798
7799/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7800/// expression. If so, decompose it, returning some value X, such that Val is
7801/// X*Scale+Offset.
7802///
7803static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007804 int &Offset, LLVMContext *Context) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007805 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7806 "Unexpected allocation size type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007807 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7808 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007809 Scale = 0;
Owen Anderson35b47072009-08-13 21:58:54 +00007810 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007811 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7812 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7813 if (I->getOpcode() == Instruction::Shl) {
7814 // This is a value scaled by '1 << the shift amt'.
7815 Scale = 1U << RHS->getZExtValue();
7816 Offset = 0;
7817 return I->getOperand(0);
7818 } else if (I->getOpcode() == Instruction::Mul) {
7819 // This value is scaled by 'RHS'.
7820 Scale = RHS->getZExtValue();
7821 Offset = 0;
7822 return I->getOperand(0);
7823 } else if (I->getOpcode() == Instruction::Add) {
7824 // We have X+C. Check to see if we really have (X*C2)+C1,
7825 // where C1 is divisible by C2.
7826 unsigned SubScale;
7827 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00007828 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7829 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007830 Offset += RHS->getZExtValue();
7831 Scale = SubScale;
7832 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007833 }
7834 }
7835 }
7836
7837 // Otherwise, we can't look past this.
7838 Scale = 1;
7839 Offset = 0;
7840 return Val;
7841}
7842
7843
7844/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7845/// try to eliminate the cast by moving the type information into the alloc.
7846Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandezb1687302009-10-23 21:09:37 +00007847 AllocaInst &AI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007848 const PointerType *PTy = cast<PointerType>(CI.getType());
7849
Chris Lattnerad7516a2009-08-30 18:50:58 +00007850 BuilderTy AllocaBuilder(*Builder);
7851 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7852
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007853 // Remove any uses of AI that are dead.
7854 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7855
7856 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7857 Instruction *User = cast<Instruction>(*UI++);
7858 if (isInstructionTriviallyDead(User)) {
7859 while (UI != E && *UI == User)
7860 ++UI; // If this instruction uses AI more than once, don't break UI.
7861
7862 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00007863 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007864 EraseInstFromFunction(*User);
7865 }
7866 }
Dan Gohmana80e2712009-07-21 23:21:54 +00007867
7868 // This requires TargetData to get the alloca alignment and size information.
7869 if (!TD) return 0;
7870
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007871 // Get the type really allocated and the type casted to.
7872 const Type *AllocElTy = AI.getAllocatedType();
7873 const Type *CastElTy = PTy->getElementType();
7874 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7875
7876 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7877 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7878 if (CastElTyAlign < AllocElTyAlign) return 0;
7879
7880 // If the allocation has multiple uses, only promote it if we are strictly
7881 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007882 // same, we open the door to infinite loops of various kinds. (A reference
7883 // from a dbg.declare doesn't count as a use for this purpose.)
7884 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7885 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007886
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007887 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7888 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007889 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7890
7891 // See if we can satisfy the modulus by pulling a scale out of the array
7892 // size argument.
7893 unsigned ArraySizeScale;
7894 int ArrayOffset;
7895 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00007896 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7897 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007898
7899 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7900 // do the xform.
7901 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7902 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7903
7904 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7905 Value *Amt = 0;
7906 if (Scale == 1) {
7907 Amt = NumElements;
7908 } else {
Owen Anderson35b47072009-08-13 21:58:54 +00007909 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007910 // Insert before the alloca, not before the cast.
7911 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007912 }
7913
7914 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson35b47072009-08-13 21:58:54 +00007915 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007916 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007917 }
7918
Victor Hernandezb1687302009-10-23 21:09:37 +00007919 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007920 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007921 New->takeName(&AI);
7922
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007923 // If the allocation has one real use plus a dbg.declare, just remove the
7924 // declare.
7925 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7926 EraseInstFromFunction(*DI);
7927 }
7928 // If the allocation has multiple real uses, insert a cast and change all
7929 // things that used it to use the new cast. This will also hack on CI, but it
7930 // will die soon.
7931 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007932 // New is the allocation instruction, pointer typed. AI is the original
7933 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerad7516a2009-08-30 18:50:58 +00007934 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007935 AI.replaceAllUsesWith(NewCast);
7936 }
7937 return ReplaceInstUsesWith(CI, New);
7938}
7939
7940/// CanEvaluateInDifferentType - Return true if we can take the specified value
7941/// and return it as type Ty without inserting any new casts and without
7942/// changing the computed value. This is used by code that tries to decide
7943/// whether promoting or shrinking integer operations to wider or smaller types
7944/// will allow us to eliminate a truncate or extend.
7945///
7946/// This is a truncation operation if Ty is smaller than V->getType(), or an
7947/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007948///
7949/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7950/// should return true if trunc(V) can be computed by computing V in the smaller
7951/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7952/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7953/// efficiently truncated.
7954///
7955/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7956/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7957/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007958bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00007959 unsigned CastOpc,
7960 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007961 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007962 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007963 return true;
7964
7965 Instruction *I = dyn_cast<Instruction>(V);
7966 if (!I) return false;
7967
Dan Gohman8fd520a2009-06-15 22:12:54 +00007968 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007969
Chris Lattneref70bb82007-08-02 06:11:14 +00007970 // If this is an extension or truncate, we can often eliminate it.
7971 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7972 // If this is a cast from the destination type, we can trivially eliminate
7973 // it, and this will remove a cast overall.
7974 if (I->getOperand(0)->getType() == Ty) {
7975 // If the first operand is itself a cast, and is eliminable, do not count
7976 // this as an eliminable cast. We would prefer to eliminate those two
7977 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007978 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007979 ++NumCastsRemoved;
7980 return true;
7981 }
7982 }
7983
7984 // We can't extend or shrink something that has multiple uses: doing so would
7985 // require duplicating the instruction in general, which isn't profitable.
7986 if (!I->hasOneUse()) return false;
7987
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007988 unsigned Opc = I->getOpcode();
7989 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007990 case Instruction::Add:
7991 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007992 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007993 case Instruction::And:
7994 case Instruction::Or:
7995 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007996 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007997 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007998 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007999 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008000 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008001
Eli Friedman08c45bc2009-07-13 22:46:01 +00008002 case Instruction::UDiv:
8003 case Instruction::URem: {
8004 // UDiv and URem can be truncated if all the truncated bits are zero.
8005 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8006 uint32_t BitWidth = Ty->getScalarSizeInBits();
8007 if (BitWidth < OrigBitWidth) {
8008 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8009 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8010 MaskedValueIsZero(I->getOperand(1), Mask)) {
8011 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8012 NumCastsRemoved) &&
8013 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8014 NumCastsRemoved);
8015 }
8016 }
8017 break;
8018 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008019 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008020 // If we are truncating the result of this SHL, and if it's a shift of a
8021 // constant amount, we can always perform a SHL in a smaller type.
8022 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008023 uint32_t BitWidth = Ty->getScalarSizeInBits();
8024 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008025 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00008026 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008027 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008028 }
8029 break;
8030 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008031 // If this is a truncate of a logical shr, we can truncate it to a smaller
8032 // lshr iff we know that the bits we would otherwise be shifting in are
8033 // already zeros.
8034 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008035 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8036 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008037 if (BitWidth < OrigBitWidth &&
8038 MaskedValueIsZero(I->getOperand(0),
8039 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8040 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00008041 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008042 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008043 }
8044 }
8045 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008046 case Instruction::ZExt:
8047 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00008048 case Instruction::Trunc:
8049 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00008050 // can safely replace it. Note that replacing it does not reduce the number
8051 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008052 if (Opc == CastOpc)
8053 return true;
8054
8055 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00008056 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008057 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008058 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008059 case Instruction::Select: {
8060 SelectInst *SI = cast<SelectInst>(I);
8061 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008062 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008063 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008064 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008065 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008066 case Instruction::PHI: {
8067 // We can change a phi if we can change all operands.
8068 PHINode *PN = cast<PHINode>(I);
8069 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8070 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008071 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00008072 return false;
8073 return true;
8074 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008075 default:
8076 // TODO: Can handle more cases here.
8077 break;
8078 }
8079
8080 return false;
8081}
8082
8083/// EvaluateInDifferentType - Given an expression that
8084/// CanEvaluateInDifferentType returns true for, actually insert the code to
8085/// evaluate the expression.
8086Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8087 bool isSigned) {
8088 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner1cd526b2009-11-08 19:23:30 +00008089 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008090
8091 // Otherwise, it must be an instruction.
8092 Instruction *I = cast<Instruction>(V);
8093 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008094 unsigned Opc = I->getOpcode();
8095 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008096 case Instruction::Add:
8097 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00008098 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008099 case Instruction::And:
8100 case Instruction::Or:
8101 case Instruction::Xor:
8102 case Instruction::AShr:
8103 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00008104 case Instruction::Shl:
8105 case Instruction::UDiv:
8106 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008107 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8108 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008109 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008110 break;
8111 }
8112 case Instruction::Trunc:
8113 case Instruction::ZExt:
8114 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008115 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00008116 // just return the source. There's no need to insert it because it is not
8117 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008118 if (I->getOperand(0)->getType() == Ty)
8119 return I->getOperand(0);
8120
Chris Lattner4200c2062008-06-18 04:00:49 +00008121 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner1cd526b2009-11-08 19:23:30 +00008122 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00008123 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008124 case Instruction::Select: {
8125 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8126 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8127 Res = SelectInst::Create(I->getOperand(0), True, False);
8128 break;
8129 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008130 case Instruction::PHI: {
8131 PHINode *OPN = cast<PHINode>(I);
8132 PHINode *NPN = PHINode::Create(Ty);
8133 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8134 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8135 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8136 }
8137 Res = NPN;
8138 break;
8139 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008140 default:
8141 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00008142 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008143 break;
8144 }
8145
Chris Lattner4200c2062008-06-18 04:00:49 +00008146 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008147 return InsertNewInstBefore(Res, *I);
8148}
8149
8150/// @brief Implement the transforms common to all CastInst visitors.
8151Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8152 Value *Src = CI.getOperand(0);
8153
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008154 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8155 // eliminate it now.
8156 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8157 if (Instruction::CastOps opc =
8158 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8159 // The first cast (CSrc) is eliminable so we need to fix up or replace
8160 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008161 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008162 }
8163 }
8164
8165 // If we are casting a select then fold the cast into the select
8166 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8167 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8168 return NV;
8169
8170 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner1cd526b2009-11-08 19:23:30 +00008171 if (isa<PHINode>(Src)) {
8172 // We don't do this if this would create a PHI node with an illegal type if
8173 // it is currently legal.
8174 if (!isa<IntegerType>(Src->getType()) ||
8175 !isa<IntegerType>(CI.getType()) ||
8176 (TD && TD->isLegalInteger(CI.getType()->getPrimitiveSizeInBits())) ||
8177 (TD && !TD->isLegalInteger(Src->getType()->getPrimitiveSizeInBits())))
8178 if (Instruction *NV = FoldOpIntoPhi(CI))
8179 return NV;
8180
8181 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008182
8183 return 0;
8184}
8185
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008186/// FindElementAtOffset - Given a type and a constant offset, determine whether
8187/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008188/// the specified offset. If so, fill them into NewIndices and return the
8189/// resultant element type, otherwise return null.
8190static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8191 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008192 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008193 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008194 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008195 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008196
8197 // Start with the index over the outer type. Note that the type size
8198 // might be zero (even if the offset isn't zero) if the indexed type
8199 // is something like [0 x {int, int}]
Owen Anderson35b47072009-08-13 21:58:54 +00008200 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008201 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008202 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008203 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008204 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008205
Chris Lattnerce48c462009-01-11 20:15:20 +00008206 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008207 if (Offset < 0) {
8208 --FirstIdx;
8209 Offset += TySize;
8210 assert(Offset >= 0);
8211 }
8212 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8213 }
8214
Owen Andersoneacb44d2009-07-24 23:12:02 +00008215 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008216
8217 // Index into the types. If we fail, set OrigBase to null.
8218 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008219 // Indexing into tail padding between struct/array elements.
8220 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008221 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008222
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008223 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8224 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008225 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8226 "Offset must stay within the indexed type");
8227
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008228 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson35b47072009-08-13 21:58:54 +00008229 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008230
8231 Offset -= SL->getElementOffset(Elt);
8232 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008233 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008234 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008235 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00008236 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008237 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008238 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008239 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008240 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008241 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008242 }
8243 }
8244
Chris Lattner54dddc72009-01-24 01:00:13 +00008245 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008246}
8247
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008248/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8249Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8250 Value *Src = CI.getOperand(0);
8251
8252 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8253 // If casting the result of a getelementptr instruction with no offset, turn
8254 // this into a cast of the original pointer!
8255 if (GEP->hasAllZeroIndices()) {
8256 // Changing the cast operand is usually not a good idea but it is safe
8257 // here because the pointer operand is being replaced with another
8258 // pointer operand so the opcode doesn't need to change.
Chris Lattner3183fb62009-08-30 06:13:40 +00008259 Worklist.Add(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008260 CI.setOperand(0, GEP->getOperand(0));
8261 return &CI;
8262 }
8263
8264 // If the GEP has a single use, and the base pointer is a bitcast, and the
8265 // GEP computes a constant offset, see if we can convert these three
8266 // instructions into fewer. This typically happens with unions and other
8267 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008268 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008269 if (GEP->hasAllConstantIndices()) {
8270 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner93e6ff92009-11-04 08:05:20 +00008271 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008272 int64_t Offset = OffsetV->getSExtValue();
8273
8274 // Get the base pointer input of the bitcast, and the type it points to.
8275 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8276 const Type *GEPIdxTy =
8277 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008278 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008279 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008280 // If we were able to index down into an element, create the GEP
8281 // and bitcast the result. This eliminates one bitcast, potentially
8282 // two.
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008283 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8284 Builder->CreateInBoundsGEP(OrigBase,
8285 NewIndices.begin(), NewIndices.end()) :
8286 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008287 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008288
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008289 if (isa<BitCastInst>(CI))
8290 return new BitCastInst(NGEP, CI.getType());
8291 assert(isa<PtrToIntInst>(CI));
8292 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008293 }
8294 }
8295 }
8296 }
8297
8298 return commonCastTransforms(CI);
8299}
8300
Eli Friedman827e37a2009-07-13 20:58:59 +00008301/// commonIntCastTransforms - This function implements the common transforms
8302/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008303Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8304 if (Instruction *Result = commonCastTransforms(CI))
8305 return Result;
8306
8307 Value *Src = CI.getOperand(0);
8308 const Type *SrcTy = Src->getType();
8309 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008310 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8311 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008312
8313 // See if we can simplify any instructions used by the LHS whose sole
8314 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008315 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008316 return &CI;
8317
8318 // If the source isn't an instruction or has more than one use then we
8319 // can't do anything more.
8320 Instruction *SrcI = dyn_cast<Instruction>(Src);
8321 if (!SrcI || !Src->hasOneUse())
8322 return 0;
8323
8324 // Attempt to propagate the cast into the instruction for int->int casts.
8325 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008326 // Only do this if the dest type is a simple type, don't convert the
8327 // expression tree to something weird like i93 unless the source is also
8328 // strange.
Chris Lattner2e9f5d02009-11-07 19:11:46 +00008329 if (TD &&
8330 (TD->isLegalInteger(DestTy->getScalarType()->getPrimitiveSizeInBits()) ||
8331 !TD->isLegalInteger((SrcI->getType()->getScalarType()
8332 ->getPrimitiveSizeInBits()))) &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008333 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng814a00c2009-01-16 02:11:43 +00008334 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008335 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008336 // eliminates the cast, so it is always a win. If this is a zero-extension,
8337 // we need to do an AND to maintain the clear top-part of the computation,
8338 // so we require that the input have eliminated at least one cast. If this
8339 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008340 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008341 bool DoXForm = false;
8342 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008343 switch (CI.getOpcode()) {
8344 default:
8345 // All the others use floating point so we shouldn't actually
8346 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008347 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008348 case Instruction::Trunc:
8349 DoXForm = true;
8350 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008351 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008352 DoXForm = NumCastsRemoved >= 1;
Chris Lattner2e9f5d02009-11-07 19:11:46 +00008353
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008354 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008355 // If it's unnecessary to issue an AND to clear the high bits, it's
8356 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008357 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008358 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8359 if (MaskedValueIsZero(TryRes, Mask))
8360 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008361
8362 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008363 if (TryI->use_empty())
8364 EraseInstFromFunction(*TryI);
8365 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008366 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008367 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008368 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008369 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008370 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008371 // If we do not have to emit the truncate + sext pair, then it's always
8372 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008373 //
8374 // It's not safe to eliminate the trunc + sext pair if one of the
8375 // eliminated cast is a truncate. e.g.
8376 // t2 = trunc i32 t1 to i16
8377 // t3 = sext i16 t2 to i32
8378 // !=
8379 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008380 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008381 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8382 if (NumSignBits > (DestBitSize - SrcBitSize))
8383 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008384
8385 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008386 if (TryI->use_empty())
8387 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008388 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008389 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008390 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008391 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008392
8393 if (DoXForm) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00008394 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8395 " to avoid cast: " << CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008396 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8397 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008398 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008399 // Just replace this cast with the result.
8400 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008401
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008402 assert(Res->getType() == DestTy);
8403 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008404 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008405 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008406 // Just replace this cast with the result.
8407 return ReplaceInstUsesWith(CI, Res);
8408 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008409 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008410
8411 // If the high bits are already zero, just replace this cast with the
8412 // result.
8413 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8414 if (MaskedValueIsZero(Res, Mask))
8415 return ReplaceInstUsesWith(CI, Res);
8416
8417 // We need to emit an AND to clear the high bits.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008418 Constant *C = ConstantInt::get(*Context,
8419 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008420 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008421 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008422 case Instruction::SExt: {
8423 // If the high bits are already filled with sign bit, just replace this
8424 // cast with the result.
8425 unsigned NumSignBits = ComputeNumSignBits(Res);
8426 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008427 return ReplaceInstUsesWith(CI, Res);
8428
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008429 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008430 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008431 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008432 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008433 }
8434 }
8435
8436 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8437 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8438
8439 switch (SrcI->getOpcode()) {
8440 case Instruction::Add:
8441 case Instruction::Mul:
8442 case Instruction::And:
8443 case Instruction::Or:
8444 case Instruction::Xor:
8445 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008446 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8447 // Don't insert two casts unless at least one can be eliminated.
8448 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008449 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008450 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8451 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008452 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008453 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8454 }
8455 }
8456
8457 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8458 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8459 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson4f720fa2009-07-31 17:39:07 +00008460 Op1 == ConstantInt::getTrue(*Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008461 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008462 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Anderson24be4c12009-07-03 00:17:18 +00008463 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008464 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008465 }
8466 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008467
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008468 case Instruction::Shl: {
8469 // Canonicalize trunc inside shl, if we can.
8470 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8471 if (CI && DestBitSize < SrcBitSize &&
8472 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008473 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8474 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008475 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008476 }
8477 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008478 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008479 }
8480 return 0;
8481}
8482
8483Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8484 if (Instruction *Result = commonIntCastTransforms(CI))
8485 return Result;
8486
8487 Value *Src = CI.getOperand(0);
8488 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008489 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8490 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008491
8492 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008493 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008494 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008495 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersonaac28372009-07-31 20:28:14 +00008496 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohmane6803b82009-08-25 23:17:54 +00008497 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008498 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008499
Chris Lattner32177f82009-03-24 18:15:30 +00008500 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8501 ConstantInt *ShAmtV = 0;
8502 Value *ShiftOp = 0;
8503 if (Src->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00008504 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner32177f82009-03-24 18:15:30 +00008505 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8506
8507 // Get a mask for the bits shifting in.
8508 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8509 if (MaskedValueIsZero(ShiftOp, Mask)) {
8510 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00008511 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008512
8513 // Okay, we can shrink this. Truncate the input, then return a new
8514 // shift.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008515 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Anderson02b48c32009-07-29 18:55:55 +00008516 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008517 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008518 }
8519 }
Chris Lattner1cd526b2009-11-08 19:23:30 +00008520
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008521 return 0;
8522}
8523
Evan Chenge3779cf2008-03-24 00:21:34 +00008524/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8525/// in order to eliminate the icmp.
8526Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8527 bool DoXform) {
8528 // If we are just checking for a icmp eq of a single bit and zext'ing it
8529 // to an integer, then shift the bit to the appropriate place and then
8530 // cast to integer to avoid the comparison.
8531 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8532 const APInt &Op1CV = Op1C->getValue();
8533
8534 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8535 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8536 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8537 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8538 if (!DoXform) return ICI;
8539
8540 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008541 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008542 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008543 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008544 if (In->getType() != CI.getType())
Chris Lattnerad7516a2009-08-30 18:50:58 +00008545 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008546
8547 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008548 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008549 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chenge3779cf2008-03-24 00:21:34 +00008550 }
8551
8552 return ReplaceInstUsesWith(CI, In);
8553 }
8554
8555
8556
8557 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8558 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8559 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8560 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8561 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8562 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8563 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8564 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8565 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8566 // This only works for EQ and NE
8567 ICI->isEquality()) {
8568 // If Op1C some other power of two, convert:
8569 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8570 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8571 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8572 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8573
8574 APInt KnownZeroMask(~KnownZero);
8575 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8576 if (!DoXform) return ICI;
8577
8578 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8579 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8580 // (X&4) == 2 --> false
8581 // (X&4) != 2 --> true
Owen Anderson35b47072009-08-13 21:58:54 +00008582 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00008583 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008584 return ReplaceInstUsesWith(CI, Res);
8585 }
8586
8587 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8588 Value *In = ICI->getOperand(0);
8589 if (ShiftAmt) {
8590 // Perform a logical shr by shiftamt.
8591 // Insert the shift to put the result in the low bit.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008592 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8593 In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008594 }
8595
8596 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008597 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008598 In = Builder->CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008599 }
8600
8601 if (CI.getType() == In->getType())
8602 return ReplaceInstUsesWith(CI, In);
8603 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008604 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008605 }
8606 }
8607 }
8608
8609 return 0;
8610}
8611
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008612Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8613 // If one of the common conversion will work ..
8614 if (Instruction *Result = commonIntCastTransforms(CI))
8615 return Result;
8616
8617 Value *Src = CI.getOperand(0);
8618
Chris Lattner215d56e2009-02-17 20:47:23 +00008619 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8620 // types and if the sizes are just right we can convert this into a logical
8621 // 'and' which will be much cheaper than the pair of casts.
8622 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8623 // Get the sizes of the types involved. We know that the intermediate type
8624 // will be smaller than A or C, but don't know the relation between A and C.
8625 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008626 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8627 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8628 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008629 // If we're actually extending zero bits, then if
8630 // SrcSize < DstSize: zext(a & mask)
8631 // SrcSize == DstSize: a & mask
8632 // SrcSize > DstSize: trunc(a) & mask
8633 if (SrcSize < DstSize) {
8634 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008635 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008636 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattner215d56e2009-02-17 20:47:23 +00008637 return new ZExtInst(And, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008638 }
8639
8640 if (SrcSize == DstSize) {
Chris Lattner215d56e2009-02-17 20:47:23 +00008641 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008642 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008643 AndValue));
Chris Lattnerad7516a2009-08-30 18:50:58 +00008644 }
8645 if (SrcSize > DstSize) {
8646 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattner215d56e2009-02-17 20:47:23 +00008647 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008648 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008649 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008650 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008651 }
8652 }
8653
Evan Chenge3779cf2008-03-24 00:21:34 +00008654 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8655 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008656
Evan Chenge3779cf2008-03-24 00:21:34 +00008657 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8658 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8659 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8660 // of the (zext icmp) will be transformed.
8661 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8662 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8663 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8664 (transformZExtICmp(LHS, CI, false) ||
8665 transformZExtICmp(RHS, CI, false))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008666 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8667 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008668 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008669 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008670 }
8671
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008672 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008673 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8674 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8675 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8676 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008677 if (TI0->getType() == CI.getType())
8678 return
8679 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00008680 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008681 }
8682
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008683 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8684 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8685 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8686 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8687 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8688 And->getOperand(1) == C)
8689 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8690 Value *TI0 = TI->getOperand(0);
8691 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00008692 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008693 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008694 return BinaryOperator::CreateXor(NewAnd, ZC);
8695 }
8696 }
8697
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008698 return 0;
8699}
8700
8701Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8702 if (Instruction *I = commonIntCastTransforms(CI))
8703 return I;
8704
8705 Value *Src = CI.getOperand(0);
8706
Dan Gohman35b76162008-10-30 20:40:10 +00008707 // Canonicalize sign-extend from i1 to a select.
Owen Anderson35b47072009-08-13 21:58:54 +00008708 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman35b76162008-10-30 20:40:10 +00008709 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00008710 Constant::getAllOnesValue(CI.getType()),
8711 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008712
8713 // See if the value being truncated is already sign extended. If so, just
8714 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00008715 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00008716 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008717 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8718 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8719 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008720 unsigned NumSignBits = ComputeNumSignBits(Op);
8721
8722 if (OpBits == DestBits) {
8723 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8724 // bits, it is already ready.
8725 if (NumSignBits > DestBits-MidBits)
8726 return ReplaceInstUsesWith(CI, Op);
8727 } else if (OpBits < DestBits) {
8728 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8729 // bits, just sext from i32.
8730 if (NumSignBits > OpBits-MidBits)
8731 return new SExtInst(Op, CI.getType(), "tmp");
8732 } else {
8733 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8734 // bits, just truncate to i32.
8735 if (NumSignBits > OpBits-MidBits)
8736 return new TruncInst(Op, CI.getType(), "tmp");
8737 }
8738 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008739
8740 // If the input is a shl/ashr pair of a same constant, then this is a sign
8741 // extension from a smaller value. If we could trust arbitrary bitwidth
8742 // integers, we could turn this into a truncate to the smaller bit and then
8743 // use a sext for the whole extension. Since we don't, look deeper and check
8744 // for a truncate. If the source and dest are the same type, eliminate the
8745 // trunc and extend and just do shifts. For example, turn:
8746 // %a = trunc i32 %i to i8
8747 // %b = shl i8 %a, 6
8748 // %c = ashr i8 %b, 6
8749 // %d = sext i8 %c to i32
8750 // into:
8751 // %a = shl i32 %i, 30
8752 // %d = ashr i32 %a, 30
8753 Value *A = 0;
8754 ConstantInt *BA = 0, *CA = 0;
8755 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohmancdff2122009-08-12 16:23:25 +00008756 m_ConstantInt(CA))) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008757 BA == CA && isa<TruncInst>(A)) {
8758 Value *I = cast<TruncInst>(A)->getOperand(0);
8759 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008760 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8761 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008762 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00008763 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008764 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner8a2d0592008-08-06 07:35:52 +00008765 return BinaryOperator::CreateAShr(I, ShAmtV);
8766 }
8767 }
8768
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008769 return 0;
8770}
8771
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008772/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8773/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008774static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008775 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008776 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008777 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008778 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8779 if (!losesInfo)
Owen Andersond363a0e2009-07-27 20:59:43 +00008780 return ConstantFP::get(*Context, F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008781 return 0;
8782}
8783
8784/// LookThroughFPExtensions - If this is an fp extension instruction, look
8785/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00008786static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008787 if (Instruction *I = dyn_cast<Instruction>(V))
8788 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00008789 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008790
8791 // If this value is a constant, return the constant in the smallest FP type
8792 // that can accurately represent it. This allows us to turn
8793 // (float)((double)X+2.0) into x+2.0f.
8794 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +00008795 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008796 return V; // No constant folding of this.
8797 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00008798 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008799 return V;
Owen Anderson35b47072009-08-13 21:58:54 +00008800 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008801 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00008802 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008803 return V;
8804 // Don't try to shrink to various long double types.
8805 }
8806
8807 return V;
8808}
8809
8810Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8811 if (Instruction *I = commonCastTransforms(CI))
8812 return I;
8813
Dan Gohman7ce405e2009-06-04 22:49:04 +00008814 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008815 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008816 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008817 // many builtins (sqrt, etc).
8818 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8819 if (OpI && OpI->hasOneUse()) {
8820 switch (OpI->getOpcode()) {
8821 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008822 case Instruction::FAdd:
8823 case Instruction::FSub:
8824 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008825 case Instruction::FDiv:
8826 case Instruction::FRem:
8827 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00008828 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8829 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008830 if (LHSTrunc->getType() != SrcTy &&
8831 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008832 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008833 // If the source types were both smaller than the destination type of
8834 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008835 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8836 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008837 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8838 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00008839 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008840 }
8841 }
8842 break;
8843 }
8844 }
8845 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008846}
8847
8848Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8849 return commonCastTransforms(CI);
8850}
8851
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008852Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008853 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8854 if (OpI == 0)
8855 return commonCastTransforms(FI);
8856
8857 // fptoui(uitofp(X)) --> X
8858 // fptoui(sitofp(X)) --> X
8859 // This is safe if the intermediate type has enough bits in its mantissa to
8860 // accurately represent all values of X. For example, do not do this with
8861 // i64->float->i64. This is also safe for sitofp case, because any negative
8862 // 'X' value would cause an undefined result for the fptoui.
8863 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8864 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008865 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008866 OpI->getType()->getFPMantissaWidth())
8867 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008868
8869 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008870}
8871
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008872Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008873 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8874 if (OpI == 0)
8875 return commonCastTransforms(FI);
8876
8877 // fptosi(sitofp(X)) --> X
8878 // fptosi(uitofp(X)) --> X
8879 // This is safe if the intermediate type has enough bits in its mantissa to
8880 // accurately represent all values of X. For example, do not do this with
8881 // i64->float->i64. This is also safe for sitofp case, because any negative
8882 // 'X' value would cause an undefined result for the fptoui.
8883 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8884 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008885 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008886 OpI->getType()->getFPMantissaWidth())
8887 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008888
8889 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008890}
8891
8892Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8893 return commonCastTransforms(CI);
8894}
8895
8896Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8897 return commonCastTransforms(CI);
8898}
8899
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008900Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8901 // If the destination integer type is smaller than the intptr_t type for
8902 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8903 // trunc to be exposed to other transforms. Don't do this for extending
8904 // ptrtoint's, because we don't know if the target sign or zero extends its
8905 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008906 if (TD &&
8907 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008908 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8909 TD->getIntPtrType(CI.getContext()),
8910 "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008911 return new TruncInst(P, CI.getType());
8912 }
8913
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008914 return commonPointerCastTransforms(CI);
8915}
8916
Chris Lattner7c1626482008-01-08 07:23:51 +00008917Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008918 // If the source integer type is larger than the intptr_t type for
8919 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8920 // allows the trunc to be exposed to other transforms. Don't do this for
8921 // extending inttoptr's, because we don't know if the target sign or zero
8922 // extends to pointers.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008923 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008924 TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008925 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8926 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008927 return new IntToPtrInst(P, CI.getType());
8928 }
8929
Chris Lattner7c1626482008-01-08 07:23:51 +00008930 if (Instruction *I = commonCastTransforms(CI))
8931 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00008932
Chris Lattner7c1626482008-01-08 07:23:51 +00008933 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008934}
8935
8936Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8937 // If the operands are integer typed then apply the integer transforms,
8938 // otherwise just apply the common ones.
8939 Value *Src = CI.getOperand(0);
8940 const Type *SrcTy = Src->getType();
8941 const Type *DestTy = CI.getType();
8942
Eli Friedman5013d3f2009-07-13 20:53:00 +00008943 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008944 if (Instruction *I = commonPointerCastTransforms(CI))
8945 return I;
8946 } else {
8947 if (Instruction *Result = commonCastTransforms(CI))
8948 return Result;
8949 }
8950
8951
8952 // Get rid of casts from one type to the same type. These are useless and can
8953 // be replaced by the operand.
8954 if (DestTy == Src->getType())
8955 return ReplaceInstUsesWith(CI, Src);
8956
8957 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8958 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8959 const Type *DstElTy = DstPTy->getElementType();
8960 const Type *SrcElTy = SrcPTy->getElementType();
8961
Nate Begemandf5b3612008-03-31 00:22:16 +00008962 // If the address spaces don't match, don't eliminate the bitcast, which is
8963 // required for changing types.
8964 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8965 return 0;
8966
Victor Hernandez48c3c542009-09-18 22:35:49 +00008967 // If we are casting a alloca to a pointer to a type of the same
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008968 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez48c3c542009-09-18 22:35:49 +00008969 // There is no need to modify malloc calls because it is their bitcast that
8970 // needs to be cleaned up.
Victor Hernandezb1687302009-10-23 21:09:37 +00008971 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008972 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8973 return V;
8974
8975 // If the source and destination are pointers, and this cast is equivalent
8976 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8977 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson35b47072009-08-13 21:58:54 +00008978 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008979 unsigned NumZeros = 0;
8980 while (SrcElTy != DstElTy &&
8981 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8982 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8983 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8984 ++NumZeros;
8985 }
8986
8987 // If we found a path from the src to dest, create the getelementptr now.
8988 if (SrcElTy == DstElTy) {
8989 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008990 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8991 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008992 }
8993 }
8994
Eli Friedman1d31dee2009-07-18 23:06:53 +00008995 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8996 if (DestVTy->getNumElements() == 1) {
8997 if (!isa<VectorType>(SrcTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008998 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00008999 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattnerd6164c22009-08-30 20:01:10 +00009000 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009001 }
9002 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9003 }
9004 }
9005
9006 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9007 if (SrcVTy->getNumElements() == 1) {
9008 if (!isa<VectorType>(DestTy)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009009 Value *Elem =
9010 Builder->CreateExtractElement(Src,
9011 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009012 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9013 }
9014 }
9015 }
9016
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009017 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9018 if (SVI->hasOneUse()) {
9019 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9020 // a bitconvert to a vector with the same # elts.
9021 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009022 cast<VectorType>(DestTy)->getNumElements() ==
9023 SVI->getType()->getNumElements() &&
9024 SVI->getType()->getNumElements() ==
9025 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009026 CastInst *Tmp;
9027 // If either of the operands is a cast from CI.getType(), then
9028 // evaluating the shuffle in the casted destination's type will allow
9029 // us to eliminate at least one cast.
9030 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9031 Tmp->getOperand(0)->getType() == DestTy) ||
9032 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9033 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00009034 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9035 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009036 // Return a new shuffle vector. Use the same element ID's, as we
9037 // know the vector types match #elts.
9038 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9039 }
9040 }
9041 }
9042 }
9043 return 0;
9044}
9045
9046/// GetSelectFoldableOperands - We want to turn code that looks like this:
9047/// %C = or %A, %B
9048/// %D = select %cond, %C, %A
9049/// into:
9050/// %C = select %cond, %B, 0
9051/// %D = or %A, %C
9052///
9053/// Assuming that the specified instruction is an operand to the select, return
9054/// a bitmask indicating which operands of this instruction are foldable if they
9055/// equal the other incoming value of the select.
9056///
9057static unsigned GetSelectFoldableOperands(Instruction *I) {
9058 switch (I->getOpcode()) {
9059 case Instruction::Add:
9060 case Instruction::Mul:
9061 case Instruction::And:
9062 case Instruction::Or:
9063 case Instruction::Xor:
9064 return 3; // Can fold through either operand.
9065 case Instruction::Sub: // Can only fold on the amount subtracted.
9066 case Instruction::Shl: // Can only fold on the shift amount.
9067 case Instruction::LShr:
9068 case Instruction::AShr:
9069 return 1;
9070 default:
9071 return 0; // Cannot fold
9072 }
9073}
9074
9075/// GetSelectFoldableConstant - For the same transformation as the previous
9076/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00009077static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00009078 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009079 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00009080 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009081 case Instruction::Add:
9082 case Instruction::Sub:
9083 case Instruction::Or:
9084 case Instruction::Xor:
9085 case Instruction::Shl:
9086 case Instruction::LShr:
9087 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00009088 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009089 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00009090 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009091 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00009092 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009093 }
9094}
9095
9096/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9097/// have the same opcode and only one use each. Try to simplify this.
9098Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9099 Instruction *FI) {
9100 if (TI->getNumOperands() == 1) {
9101 // If this is a non-volatile load or a cast from the same type,
9102 // merge.
9103 if (TI->isCast()) {
9104 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9105 return 0;
9106 } else {
9107 return 0; // unknown unary op.
9108 }
9109
9110 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009111 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00009112 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009113 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009114 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009115 TI->getType());
9116 }
9117
9118 // Only handle binary operators here.
9119 if (!isa<BinaryOperator>(TI))
9120 return 0;
9121
9122 // Figure out if the operations have any operands in common.
9123 Value *MatchOp, *OtherOpT, *OtherOpF;
9124 bool MatchIsOpZero;
9125 if (TI->getOperand(0) == FI->getOperand(0)) {
9126 MatchOp = TI->getOperand(0);
9127 OtherOpT = TI->getOperand(1);
9128 OtherOpF = FI->getOperand(1);
9129 MatchIsOpZero = true;
9130 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9131 MatchOp = TI->getOperand(1);
9132 OtherOpT = TI->getOperand(0);
9133 OtherOpF = FI->getOperand(0);
9134 MatchIsOpZero = false;
9135 } else if (!TI->isCommutative()) {
9136 return 0;
9137 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9138 MatchOp = TI->getOperand(0);
9139 OtherOpT = TI->getOperand(1);
9140 OtherOpF = FI->getOperand(0);
9141 MatchIsOpZero = true;
9142 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9143 MatchOp = TI->getOperand(1);
9144 OtherOpT = TI->getOperand(0);
9145 OtherOpF = FI->getOperand(1);
9146 MatchIsOpZero = true;
9147 } else {
9148 return 0;
9149 }
9150
9151 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009152 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9153 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009154 InsertNewInstBefore(NewSI, SI);
9155
9156 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9157 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009158 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009159 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009160 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009161 }
Edwin Törökbd448e32009-07-14 16:55:14 +00009162 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009163 return 0;
9164}
9165
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009166static bool isSelect01(Constant *C1, Constant *C2) {
9167 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9168 if (!C1I)
9169 return false;
9170 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9171 if (!C2I)
9172 return false;
9173 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9174}
9175
9176/// FoldSelectIntoOp - Try fold the select into one of the operands to
9177/// facilitate further optimization.
9178Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9179 Value *FalseVal) {
9180 // See the comment above GetSelectFoldableOperands for a description of the
9181 // transformation we are doing here.
9182 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9183 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9184 !isa<Constant>(FalseVal)) {
9185 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9186 unsigned OpToFold = 0;
9187 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9188 OpToFold = 1;
9189 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9190 OpToFold = 2;
9191 }
9192
9193 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009194 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009195 Value *OOp = TVI->getOperand(2-OpToFold);
9196 // Avoid creating select between 2 constants unless it's selecting
9197 // between 0 and 1.
9198 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9199 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9200 InsertNewInstBefore(NewSel, SI);
9201 NewSel->takeName(TVI);
9202 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9203 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009204 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009205 }
9206 }
9207 }
9208 }
9209 }
9210
9211 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9212 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9213 !isa<Constant>(TrueVal)) {
9214 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9215 unsigned OpToFold = 0;
9216 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9217 OpToFold = 1;
9218 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9219 OpToFold = 2;
9220 }
9221
9222 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009223 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009224 Value *OOp = FVI->getOperand(2-OpToFold);
9225 // Avoid creating select between 2 constants unless it's selecting
9226 // between 0 and 1.
9227 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9228 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9229 InsertNewInstBefore(NewSel, SI);
9230 NewSel->takeName(FVI);
9231 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9232 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009233 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009234 }
9235 }
9236 }
9237 }
9238 }
9239
9240 return 0;
9241}
9242
Dan Gohman58c09632008-09-16 18:46:06 +00009243/// visitSelectInstWithICmp - Visit a SelectInst that has an
9244/// ICmpInst as its first operand.
9245///
9246Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9247 ICmpInst *ICI) {
9248 bool Changed = false;
9249 ICmpInst::Predicate Pred = ICI->getPredicate();
9250 Value *CmpLHS = ICI->getOperand(0);
9251 Value *CmpRHS = ICI->getOperand(1);
9252 Value *TrueVal = SI.getTrueValue();
9253 Value *FalseVal = SI.getFalseValue();
9254
9255 // Check cases where the comparison is with a constant that
9256 // can be adjusted to fit the min/max idiom. We may edit ICI in
9257 // place here, so make sure the select is the only user.
9258 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009259 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009260 switch (Pred) {
9261 default: break;
9262 case ICmpInst::ICMP_ULT:
9263 case ICmpInst::ICMP_SLT: {
9264 // X < MIN ? T : F --> F
9265 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9266 return ReplaceInstUsesWith(SI, FalseVal);
9267 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009268 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009269 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9270 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9271 Pred = ICmpInst::getSwappedPredicate(Pred);
9272 CmpRHS = AdjustedRHS;
9273 std::swap(FalseVal, TrueVal);
9274 ICI->setPredicate(Pred);
9275 ICI->setOperand(1, CmpRHS);
9276 SI.setOperand(1, TrueVal);
9277 SI.setOperand(2, FalseVal);
9278 Changed = true;
9279 }
9280 break;
9281 }
9282 case ICmpInst::ICMP_UGT:
9283 case ICmpInst::ICMP_SGT: {
9284 // X > MAX ? T : F --> F
9285 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9286 return ReplaceInstUsesWith(SI, FalseVal);
9287 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009288 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009289 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9290 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9291 Pred = ICmpInst::getSwappedPredicate(Pred);
9292 CmpRHS = AdjustedRHS;
9293 std::swap(FalseVal, TrueVal);
9294 ICI->setPredicate(Pred);
9295 ICI->setOperand(1, CmpRHS);
9296 SI.setOperand(1, TrueVal);
9297 SI.setOperand(2, FalseVal);
9298 Changed = true;
9299 }
9300 break;
9301 }
9302 }
9303
Dan Gohman35b76162008-10-30 20:40:10 +00009304 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9305 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009306 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohmancdff2122009-08-12 16:23:25 +00009307 if (match(TrueVal, m_ConstantInt<-1>()) &&
9308 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009309 Pred = ICI->getPredicate();
Dan Gohmancdff2122009-08-12 16:23:25 +00009310 else if (match(TrueVal, m_ConstantInt<0>()) &&
9311 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009312 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9313
Dan Gohman35b76162008-10-30 20:40:10 +00009314 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9315 // If we are just checking for a icmp eq of a single bit and zext'ing it
9316 // to an integer, then shift the bit to the appropriate place and then
9317 // cast to integer to avoid the comparison.
9318 const APInt &Op1CV = CI->getValue();
9319
9320 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9321 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9322 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009323 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009324 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00009325 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009326 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009327 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00009328 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00009329 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009330 if (In->getType() != SI.getType())
9331 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009332 true/*SExt*/, "tmp", ICI);
9333
9334 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohmancdff2122009-08-12 16:23:25 +00009335 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman35b76162008-10-30 20:40:10 +00009336 In->getName()+".not"), *ICI);
9337
9338 return ReplaceInstUsesWith(SI, In);
9339 }
9340 }
9341 }
9342
Dan Gohman58c09632008-09-16 18:46:06 +00009343 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9344 // Transform (X == Y) ? X : Y -> Y
9345 if (Pred == ICmpInst::ICMP_EQ)
9346 return ReplaceInstUsesWith(SI, FalseVal);
9347 // Transform (X != Y) ? X : Y -> X
9348 if (Pred == ICmpInst::ICMP_NE)
9349 return ReplaceInstUsesWith(SI, TrueVal);
9350 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9351
9352 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9353 // Transform (X == Y) ? Y : X -> X
9354 if (Pred == ICmpInst::ICMP_EQ)
9355 return ReplaceInstUsesWith(SI, FalseVal);
9356 // Transform (X != Y) ? Y : X -> Y
9357 if (Pred == ICmpInst::ICMP_NE)
9358 return ReplaceInstUsesWith(SI, TrueVal);
9359 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9360 }
9361
9362 /// NOTE: if we wanted to, this is where to detect integer ABS
9363
9364 return Changed ? &SI : 0;
9365}
9366
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009367
Chris Lattnerb5ed7f02009-10-22 00:17:26 +00009368/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9369/// PHI node (but the two may be in different blocks). See if the true/false
9370/// values (V) are live in all of the predecessor blocks of the PHI. For
9371/// example, cases like this cannot be mapped:
9372///
9373/// X = phi [ C1, BB1], [C2, BB2]
9374/// Y = add
9375/// Z = select X, Y, 0
9376///
9377/// because Y is not live in BB1/BB2.
9378///
9379static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9380 const SelectInst &SI) {
9381 // If the value is a non-instruction value like a constant or argument, it
9382 // can always be mapped.
9383 const Instruction *I = dyn_cast<Instruction>(V);
9384 if (I == 0) return true;
9385
9386 // If V is a PHI node defined in the same block as the condition PHI, we can
9387 // map the arguments.
9388 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9389
9390 if (const PHINode *VP = dyn_cast<PHINode>(I))
9391 if (VP->getParent() == CondPHI->getParent())
9392 return true;
9393
9394 // Otherwise, if the PHI and select are defined in the same block and if V is
9395 // defined in a different block, then we can transform it.
9396 if (SI.getParent() == CondPHI->getParent() &&
9397 I->getParent() != CondPHI->getParent())
9398 return true;
9399
9400 // Otherwise we have a 'hard' case and we can't tell without doing more
9401 // detailed dominator based analysis, punt.
9402 return false;
9403}
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009404
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009405Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9406 Value *CondVal = SI.getCondition();
9407 Value *TrueVal = SI.getTrueValue();
9408 Value *FalseVal = SI.getFalseValue();
9409
9410 // select true, X, Y -> X
9411 // select false, X, Y -> Y
9412 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9413 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9414
9415 // select C, X, X -> X
9416 if (TrueVal == FalseVal)
9417 return ReplaceInstUsesWith(SI, TrueVal);
9418
9419 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9420 return ReplaceInstUsesWith(SI, FalseVal);
9421 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9422 return ReplaceInstUsesWith(SI, TrueVal);
9423 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9424 if (isa<Constant>(TrueVal))
9425 return ReplaceInstUsesWith(SI, TrueVal);
9426 else
9427 return ReplaceInstUsesWith(SI, FalseVal);
9428 }
9429
Owen Anderson35b47072009-08-13 21:58:54 +00009430 if (SI.getType() == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009431 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9432 if (C->getZExtValue()) {
9433 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009434 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009435 } else {
9436 // Change: A = select B, false, C --> A = and !B, C
9437 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009438 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009439 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009440 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009441 }
9442 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9443 if (C->getZExtValue() == false) {
9444 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009445 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009446 } else {
9447 // Change: A = select B, C, true --> A = or !B, C
9448 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009449 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009450 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009451 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009452 }
9453 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009454
9455 // select a, b, a -> a&b
9456 // select a, a, b -> a|b
9457 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009458 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009459 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009460 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009461 }
9462
9463 // Selecting between two integer constants?
9464 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9465 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9466 // select C, 1, 0 -> zext C to int
9467 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009468 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009469 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9470 // select C, 0, 1 -> zext !C to int
9471 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009472 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009473 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009474 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009475 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009476
9477 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009478 // If one of the constants is zero (we know they can't both be) and we
9479 // have an icmp instruction with zero, and we have an 'and' with the
9480 // non-constant value, eliminate this whole mess. This corresponds to
9481 // cases like this: ((X & 27) ? 27 : 0)
9482 if (TrueValC->isZero() || FalseValC->isZero())
9483 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9484 cast<Constant>(IC->getOperand(1))->isNullValue())
9485 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9486 if (ICA->getOpcode() == Instruction::And &&
9487 isa<ConstantInt>(ICA->getOperand(1)) &&
9488 (ICA->getOperand(1) == TrueValC ||
9489 ICA->getOperand(1) == FalseValC) &&
9490 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9491 // Okay, now we know that everything is set up, we just don't
9492 // know whether we have a icmp_ne or icmp_eq and whether the
9493 // true or false val is the zero.
9494 bool ShouldNotVal = !TrueValC->isZero();
9495 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9496 Value *V = ICA;
9497 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009498 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009499 Instruction::Xor, V, ICA->getOperand(1)), SI);
9500 return ReplaceInstUsesWith(SI, V);
9501 }
9502 }
9503 }
9504
9505 // See if we are selecting two values based on a comparison of the two values.
9506 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9507 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9508 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009509 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9510 // This is not safe in general for floating point:
9511 // consider X== -0, Y== +0.
9512 // It becomes safe if either operand is a nonzero constant.
9513 ConstantFP *CFPt, *CFPf;
9514 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9515 !CFPt->getValueAPF().isZero()) ||
9516 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9517 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009518 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009519 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009520 // Transform (X != Y) ? X : Y -> X
9521 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9522 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009523 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009524
9525 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9526 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009527 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9528 // This is not safe in general for floating point:
9529 // consider X== -0, Y== +0.
9530 // It becomes safe if either operand is a nonzero constant.
9531 ConstantFP *CFPt, *CFPf;
9532 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9533 !CFPt->getValueAPF().isZero()) ||
9534 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9535 !CFPf->getValueAPF().isZero()))
9536 return ReplaceInstUsesWith(SI, FalseVal);
9537 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009538 // Transform (X != Y) ? Y : X -> Y
9539 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9540 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009541 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009542 }
Dan Gohman58c09632008-09-16 18:46:06 +00009543 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009544 }
9545
9546 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009547 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9548 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9549 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009550
9551 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9552 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9553 if (TI->hasOneUse() && FI->hasOneUse()) {
9554 Instruction *AddOp = 0, *SubOp = 0;
9555
9556 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9557 if (TI->getOpcode() == FI->getOpcode())
9558 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9559 return IV;
9560
9561 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9562 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009563 if ((TI->getOpcode() == Instruction::Sub &&
9564 FI->getOpcode() == Instruction::Add) ||
9565 (TI->getOpcode() == Instruction::FSub &&
9566 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009567 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009568 } else if ((FI->getOpcode() == Instruction::Sub &&
9569 TI->getOpcode() == Instruction::Add) ||
9570 (FI->getOpcode() == Instruction::FSub &&
9571 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009572 AddOp = TI; SubOp = FI;
9573 }
9574
9575 if (AddOp) {
9576 Value *OtherAddOp = 0;
9577 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9578 OtherAddOp = AddOp->getOperand(1);
9579 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9580 OtherAddOp = AddOp->getOperand(0);
9581 }
9582
9583 if (OtherAddOp) {
9584 // So at this point we know we have (Y -> OtherAddOp):
9585 // select C, (add X, Y), (sub X, Z)
9586 Value *NegVal; // Compute -Z
9587 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00009588 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009589 } else {
9590 NegVal = InsertNewInstBefore(
Dan Gohmancdff2122009-08-12 16:23:25 +00009591 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00009592 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009593 }
9594
9595 Value *NewTrueOp = OtherAddOp;
9596 Value *NewFalseOp = NegVal;
9597 if (AddOp != TI)
9598 std::swap(NewTrueOp, NewFalseOp);
9599 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009600 SelectInst::Create(CondVal, NewTrueOp,
9601 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009602
9603 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009604 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009605 }
9606 }
9607 }
9608
9609 // See if we can fold the select into one of our operands.
9610 if (SI.getType()->isInteger()) {
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009611 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9612 if (FoldI)
9613 return FoldI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009614 }
9615
Chris Lattnerb5ed7f02009-10-22 00:17:26 +00009616 // See if we can fold the select into a phi node if the condition is a select.
9617 if (isa<PHINode>(SI.getCondition()))
9618 // The true/false values have to be live in the PHI predecessor's blocks.
9619 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9620 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9621 if (Instruction *NV = FoldOpIntoPhi(SI))
9622 return NV;
Chris Lattnerf7843b72009-09-27 19:57:57 +00009623
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009624 if (BinaryOperator::isNot(CondVal)) {
9625 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9626 SI.setOperand(1, FalseVal);
9627 SI.setOperand(2, TrueVal);
9628 return &SI;
9629 }
9630
9631 return 0;
9632}
9633
Dan Gohman2d648bb2008-04-10 18:43:06 +00009634/// EnforceKnownAlignment - If the specified pointer points to an object that
9635/// we control, modify the object's alignment to PrefAlign. This isn't
9636/// often possible though. If alignment is important, a more reliable approach
9637/// is to simply align all global variables and allocation instructions to
9638/// their preferred alignment from the beginning.
9639///
9640static unsigned EnforceKnownAlignment(Value *V,
9641 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009642
Dan Gohman2d648bb2008-04-10 18:43:06 +00009643 User *U = dyn_cast<User>(V);
9644 if (!U) return Align;
9645
Dan Gohman9545fb02009-07-17 20:47:02 +00009646 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009647 default: break;
9648 case Instruction::BitCast:
9649 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9650 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009651 // If all indexes are zero, it is just the alignment of the base pointer.
9652 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009653 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009654 if (!isa<Constant>(*i) ||
9655 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009656 AllZeroOperands = false;
9657 break;
9658 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009659
9660 if (AllZeroOperands) {
9661 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009662 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009663 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009664 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009665 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009666 }
9667
9668 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9669 // If there is a large requested alignment and we can, bump up the alignment
9670 // of the global.
9671 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009672 if (GV->getAlignment() >= PrefAlign)
9673 Align = GV->getAlignment();
9674 else {
9675 GV->setAlignment(PrefAlign);
9676 Align = PrefAlign;
9677 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009678 }
Chris Lattnere8ad9ae2009-09-27 21:42:46 +00009679 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9680 // If there is a requested alignment and if this is an alloca, round up.
9681 if (AI->getAlignment() >= PrefAlign)
9682 Align = AI->getAlignment();
9683 else {
9684 AI->setAlignment(PrefAlign);
9685 Align = PrefAlign;
Dan Gohman2d648bb2008-04-10 18:43:06 +00009686 }
9687 }
9688
9689 return Align;
9690}
9691
9692/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9693/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9694/// and it is more than the alignment of the ultimate object, see if we can
9695/// increase the alignment of the ultimate object, making this check succeed.
9696unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9697 unsigned PrefAlign) {
9698 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9699 sizeof(PrefAlign) * CHAR_BIT;
9700 APInt Mask = APInt::getAllOnesValue(BitWidth);
9701 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9702 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9703 unsigned TrailZ = KnownZero.countTrailingOnes();
9704 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9705
9706 if (PrefAlign > Align)
9707 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9708
9709 // We don't need to make any adjustment.
9710 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009711}
9712
Chris Lattner00ae5132008-01-13 23:50:23 +00009713Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009714 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009715 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009716 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009717 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009718
9719 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009720 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009721 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00009722 return MI;
9723 }
9724
9725 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9726 // load/store.
9727 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9728 if (MemOpLength == 0) return 0;
9729
Chris Lattnerc669fb62008-01-14 00:28:35 +00009730 // Source and destination pointer types are always "i8*" for intrinsic. See
9731 // if the size is something we can handle with a single primitive load/store.
9732 // A single load+store correctly handles overlapping memory in the memmove
9733 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009734 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009735 if (Size == 0) return MI; // Delete this mem transfer.
9736
9737 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009738 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009739
Chris Lattnerc669fb62008-01-14 00:28:35 +00009740 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00009741 Type *NewPtrTy =
Owen Anderson35b47072009-08-13 21:58:54 +00009742 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009743
9744 // Memcpy forces the use of i8* for the source and destination. That means
9745 // that if you're using memcpy to move one double around, you'll get a cast
9746 // from double* to i8*. We'd much rather use a double load+store rather than
9747 // an i64 load+store, here because this improves the odds that the source or
9748 // dest address will be promotable. See if we can find a better type than the
9749 // integer datatype.
9750 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9751 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00009752 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009753 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9754 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009755 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009756 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9757 if (STy->getNumElements() == 1)
9758 SrcETy = STy->getElementType(0);
9759 else
9760 break;
9761 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9762 if (ATy->getNumElements() == 1)
9763 SrcETy = ATy->getElementType();
9764 else
9765 break;
9766 } else
9767 break;
9768 }
9769
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009770 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009771 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009772 }
9773 }
9774
9775
Chris Lattner00ae5132008-01-13 23:50:23 +00009776 // If the memcpy/memmove provides better alignment info than we can
9777 // infer, use it.
9778 SrcAlign = std::max(SrcAlign, CopyAlign);
9779 DstAlign = std::max(DstAlign, CopyAlign);
9780
Chris Lattner78628292009-08-30 19:47:22 +00009781 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9782 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009783 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9784 InsertNewInstBefore(L, *MI);
9785 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9786
9787 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009788 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009789 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009790}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009791
Chris Lattner5af8a912008-04-30 06:39:11 +00009792Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9793 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009794 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009795 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009796 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +00009797 return MI;
9798 }
9799
9800 // Extract the length and alignment and fill if they are constant.
9801 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9802 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson35b47072009-08-13 21:58:54 +00009803 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner5af8a912008-04-30 06:39:11 +00009804 return 0;
9805 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009806 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009807
9808 // If the length is zero, this is a no-op
9809 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9810
9811 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9812 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson35b47072009-08-13 21:58:54 +00009813 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00009814
9815 Value *Dest = MI->getDest();
Chris Lattner78628292009-08-30 19:47:22 +00009816 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner5af8a912008-04-30 06:39:11 +00009817
9818 // Alignment 0 is identity for alignment 1 for memset, but not store.
9819 if (Alignment == 0) Alignment = 1;
9820
9821 // Extract the fill value and store.
9822 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +00009823 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +00009824 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009825
9826 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009827 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00009828 return MI;
9829 }
9830
9831 return 0;
9832}
9833
9834
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009835/// visitCallInst - CallInst simplification. This mostly only handles folding
9836/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9837/// the heavy lifting.
9838///
9839Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez93946082009-10-24 04:23:03 +00009840 if (isFreeCall(&CI))
9841 return visitFree(CI);
9842
Chris Lattneraa295aa2009-05-13 17:39:14 +00009843 // If the caller function is nounwind, mark the call as nounwind, even if the
9844 // callee isn't.
9845 if (CI.getParent()->getParent()->doesNotThrow() &&
9846 !CI.doesNotThrow()) {
9847 CI.setDoesNotThrow();
9848 return &CI;
9849 }
9850
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009851 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9852 if (!II) return visitCallSite(&CI);
9853
9854 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9855 // visitCallSite.
9856 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9857 bool Changed = false;
9858
9859 // memmove/cpy/set of zero bytes is a noop.
9860 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9861 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9862
9863 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9864 if (CI->getZExtValue() == 1) {
9865 // Replace the instruction with just byte operations. We would
9866 // transform other cases to loads/stores, but we don't know if
9867 // alignment is sufficient.
9868 }
9869 }
9870
9871 // If we have a memmove and the source operation is a constant global,
9872 // then the source and dest pointers can't alias, so we can change this
9873 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009874 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009875 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9876 if (GVSrc->isConstant()) {
9877 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009878 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9879 const Type *Tys[1];
9880 Tys[0] = CI.getOperand(3)->getType();
9881 CI.setOperand(0,
9882 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009883 Changed = true;
9884 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009885
9886 // memmove(x,x,size) -> noop.
9887 if (MMI->getSource() == MMI->getDest())
9888 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009889 }
9890
9891 // If we can determine a pointer alignment that is bigger than currently
9892 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009893 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009894 if (Instruction *I = SimplifyMemTransfer(MI))
9895 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009896 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9897 if (Instruction *I = SimplifyMemSet(MSI))
9898 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009899 }
9900
9901 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009902 }
9903
9904 switch (II->getIntrinsicID()) {
9905 default: break;
9906 case Intrinsic::bswap:
9907 // bswap(bswap(x)) -> x
9908 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9909 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9910 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9911 break;
9912 case Intrinsic::ppc_altivec_lvx:
9913 case Intrinsic::ppc_altivec_lvxl:
9914 case Intrinsic::x86_sse_loadu_ps:
9915 case Intrinsic::x86_sse2_loadu_pd:
9916 case Intrinsic::x86_sse2_loadu_dq:
9917 // Turn PPC lvx -> load if the pointer is known aligned.
9918 // Turn X86 loadups -> load if the pointer is known aligned.
9919 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner78628292009-08-30 19:47:22 +00009920 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9921 PointerType::getUnqual(II->getType()));
Chris Lattner989ba312008-06-18 04:33:20 +00009922 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009923 }
Chris Lattner989ba312008-06-18 04:33:20 +00009924 break;
9925 case Intrinsic::ppc_altivec_stvx:
9926 case Intrinsic::ppc_altivec_stvxl:
9927 // Turn stvx -> store if the pointer is known aligned.
9928 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9929 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009930 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00009931 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00009932 return new StoreInst(II->getOperand(1), Ptr);
9933 }
9934 break;
9935 case Intrinsic::x86_sse_storeu_ps:
9936 case Intrinsic::x86_sse2_storeu_pd:
9937 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009938 // Turn X86 storeu -> store if the pointer is known aligned.
9939 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9940 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009941 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner78628292009-08-30 19:47:22 +00009942 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +00009943 return new StoreInst(II->getOperand(2), Ptr);
9944 }
9945 break;
9946
9947 case Intrinsic::x86_sse_cvttss2si: {
9948 // These intrinsics only demands the 0th element of its input vector. If
9949 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00009950 unsigned VWidth =
9951 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9952 APInt DemandedElts(VWidth, 1);
9953 APInt UndefElts(VWidth, 0);
9954 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00009955 UndefElts)) {
9956 II->setOperand(1, V);
9957 return II;
9958 }
9959 break;
9960 }
9961
9962 case Intrinsic::ppc_altivec_vperm:
9963 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9964 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9965 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009966
Chris Lattner989ba312008-06-18 04:33:20 +00009967 // Check that all of the elements are integer constants or undefs.
9968 bool AllEltsOk = true;
9969 for (unsigned i = 0; i != 16; ++i) {
9970 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9971 !isa<UndefValue>(Mask->getOperand(i))) {
9972 AllEltsOk = false;
9973 break;
9974 }
9975 }
9976
9977 if (AllEltsOk) {
9978 // Cast the input vectors to byte vectors.
Chris Lattner78628292009-08-30 19:47:22 +00009979 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9980 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00009981 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009982
Chris Lattner989ba312008-06-18 04:33:20 +00009983 // Only extract each element once.
9984 Value *ExtractedElts[32];
9985 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9986
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009987 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00009988 if (isa<UndefValue>(Mask->getOperand(i)))
9989 continue;
9990 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9991 Idx &= 31; // Match the hardware behavior.
9992
9993 if (ExtractedElts[Idx] == 0) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00009994 ExtractedElts[Idx] =
9995 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9996 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9997 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009998 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009999
Chris Lattner989ba312008-06-18 04:33:20 +000010000 // Insert this value into the result vector.
Chris Lattnerad7516a2009-08-30 18:50:58 +000010001 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10002 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10003 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010004 }
Chris Lattner989ba312008-06-18 04:33:20 +000010005 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010006 }
Chris Lattner989ba312008-06-18 04:33:20 +000010007 }
10008 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010009
Chris Lattner989ba312008-06-18 04:33:20 +000010010 case Intrinsic::stackrestore: {
10011 // If the save is right next to the restore, remove the restore. This can
10012 // happen when variable allocas are DCE'd.
10013 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10014 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10015 BasicBlock::iterator BI = SS;
10016 if (&*++BI == II)
10017 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010018 }
Chris Lattner989ba312008-06-18 04:33:20 +000010019 }
10020
10021 // Scan down this block to see if there is another stack restore in the
10022 // same block without an intervening call/alloca.
10023 BasicBlock::iterator BI = II;
10024 TerminatorInst *TI = II->getParent()->getTerminator();
10025 bool CannotRemove = false;
10026 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez48c3c542009-09-18 22:35:49 +000010027 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner989ba312008-06-18 04:33:20 +000010028 CannotRemove = true;
10029 break;
10030 }
Chris Lattnera6b477c2008-06-25 05:59:28 +000010031 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10032 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10033 // If there is a stackrestore below this one, remove this one.
10034 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10035 return EraseInstFromFunction(CI);
10036 // Otherwise, ignore the intrinsic.
10037 } else {
10038 // If we found a non-intrinsic call, we can't remove the stack
10039 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +000010040 CannotRemove = true;
10041 break;
10042 }
Chris Lattner989ba312008-06-18 04:33:20 +000010043 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010044 }
Chris Lattner989ba312008-06-18 04:33:20 +000010045
10046 // If the stack restore is in a return/unwind block and if there are no
10047 // allocas or calls between the restore and the return, nuke the restore.
10048 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10049 return EraseInstFromFunction(CI);
10050 break;
10051 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010052 }
10053
10054 return visitCallSite(II);
10055}
10056
10057// InvokeInst simplification
10058//
10059Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10060 return visitCallSite(&II);
10061}
10062
Dale Johannesen96021832008-04-25 21:16:07 +000010063/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10064/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +000010065static bool isSafeToEliminateVarargsCast(const CallSite CS,
10066 const CastInst * const CI,
10067 const TargetData * const TD,
10068 const int ix) {
10069 if (!CI->isLosslessCast())
10070 return false;
10071
10072 // The size of ByVal arguments is derived from the type, so we
10073 // can't change to a type with a different size. If the size were
10074 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +000010075 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +000010076 return true;
10077
10078 const Type* SrcTy =
10079 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10080 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10081 if (!SrcTy->isSized() || !DstTy->isSized())
10082 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +000010083 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +000010084 return false;
10085 return true;
10086}
10087
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010088// visitCallSite - Improvements for call and invoke instructions.
10089//
10090Instruction *InstCombiner::visitCallSite(CallSite CS) {
10091 bool Changed = false;
10092
10093 // If the callee is a constexpr cast of a function, attempt to move the cast
10094 // to the arguments of the call/invoke.
10095 if (transformConstExprCastCall(CS)) return 0;
10096
10097 Value *Callee = CS.getCalledValue();
10098
10099 if (Function *CalleeF = dyn_cast<Function>(Callee))
10100 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10101 Instruction *OldCall = CS.getInstruction();
10102 // If the call and callee calling conventions don't match, this call must
10103 // be unreachable, as the call is undefined.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010104 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000010105 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Anderson24be4c12009-07-03 00:17:18 +000010106 OldCall);
Devang Patele3829c82009-10-13 22:56:32 +000010107 // If OldCall dues not return void then replaceAllUsesWith undef.
10108 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010109 if (!OldCall->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010110 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010111 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10112 return EraseInstFromFunction(*OldCall);
10113 return 0;
10114 }
10115
10116 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10117 // This instruction is not reachable, just remove it. We insert a store to
10118 // undef so that we know that this code is not reachable, despite the fact
10119 // that we can't modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010120 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000010121 UndefValue::get(Type::getInt1PtrTy(*Context)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010122 CS.getInstruction());
10123
Devang Patele3829c82009-10-13 22:56:32 +000010124 // If CS dues not return void then replaceAllUsesWith undef.
10125 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010126 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010127 CS.getInstruction()->
10128 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010129
10130 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10131 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010132 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson4f720fa2009-07-31 17:39:07 +000010133 ConstantInt::getTrue(*Context), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010134 }
10135 return EraseInstFromFunction(*CS.getInstruction());
10136 }
10137
Duncan Sands74833f22007-09-17 10:26:40 +000010138 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10139 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10140 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10141 return transformCallThroughTrampoline(CS);
10142
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010143 const PointerType *PTy = cast<PointerType>(Callee->getType());
10144 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10145 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +000010146 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010147 // See if we can optimize any arguments passed through the varargs area of
10148 // the call.
10149 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +000010150 E = CS.arg_end(); I != E; ++I, ++ix) {
10151 CastInst *CI = dyn_cast<CastInst>(*I);
10152 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10153 *I = CI->getOperand(0);
10154 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010155 }
Dale Johannesen35615462008-04-23 18:34:37 +000010156 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010157 }
10158
Duncan Sands2937e352007-12-19 21:13:37 +000010159 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010160 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010161 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010162 Changed = true;
10163 }
10164
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010165 return Changed ? CS.getInstruction() : 0;
10166}
10167
10168// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10169// attempt to move the cast to the arguments of the call/invoke.
10170//
10171bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10172 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10173 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10174 if (CE->getOpcode() != Instruction::BitCast ||
10175 !isa<Function>(CE->getOperand(0)))
10176 return false;
10177 Function *Callee = cast<Function>(CE->getOperand(0));
10178 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010179 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010180
10181 // Okay, this is a cast from a function to a different type. Unless doing so
10182 // would cause a type conversion of one of our arguments, change this call to
10183 // be a direct call with arguments casted to the appropriate types.
10184 //
10185 const FunctionType *FT = Callee->getFunctionType();
10186 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010187 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010188
Duncan Sands7901ce12008-06-01 07:38:42 +000010189 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010190 return false; // TODO: Handle multiple return values.
10191
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010192 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010193 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010194 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010195 // Conversion is ok if changing from one pointer type to another or from
10196 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +000010197 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010198 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000010199 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010200 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010201 return false; // Cannot transform this return value.
10202
Duncan Sands5c489582008-01-06 10:12:28 +000010203 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010204 // void -> non-void is handled specially
Devang Patele9d08b82009-10-14 17:29:00 +000010205 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010206 return false; // Cannot transform this return value.
10207
Chris Lattner1c8733e2008-03-12 17:45:29 +000010208 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010209 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010210 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010211 return false; // Attribute not compatible with transformed value.
10212 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010213
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010214 // If the callsite is an invoke instruction, and the return value is used by
10215 // a PHI node in a successor, we cannot change the return type of the call
10216 // because there is no place to put the cast instruction (without breaking
10217 // the critical edge). Bail out in this case.
10218 if (!Caller->use_empty())
10219 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10220 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10221 UI != E; ++UI)
10222 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10223 if (PN->getParent() == II->getNormalDest() ||
10224 PN->getParent() == II->getUnwindDest())
10225 return false;
10226 }
10227
10228 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10229 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10230
10231 CallSite::arg_iterator AI = CS.arg_begin();
10232 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10233 const Type *ParamTy = FT->getParamType(i);
10234 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010235
10236 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010237 return false; // Cannot transform this parameter value.
10238
Devang Patelf2a4a922008-09-26 22:53:05 +000010239 if (CallerPAL.getParamAttributes(i + 1)
10240 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010241 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010242
Duncan Sands7901ce12008-06-01 07:38:42 +000010243 // Converting from one pointer type to another or between a pointer and an
10244 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010245 bool isConvertible = ActTy == ParamTy ||
Owen Anderson35b47072009-08-13 21:58:54 +000010246 (TD && ((isa<PointerType>(ParamTy) ||
10247 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10248 (isa<PointerType>(ActTy) ||
10249 ActTy == TD->getIntPtrType(Caller->getContext()))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010250 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010251 }
10252
10253 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10254 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010255 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010256
Chris Lattner1c8733e2008-03-12 17:45:29 +000010257 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10258 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010259 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010260 // won't be dropping them. Check that these extra arguments have attributes
10261 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010262 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10263 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010264 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010265 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010266 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010267 return false;
10268 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010269
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010270 // Okay, we decided that this is a safe thing to do: go ahead and start
10271 // inserting cast instructions as necessary...
10272 std::vector<Value*> Args;
10273 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010274 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010275 attrVec.reserve(NumCommonArgs);
10276
10277 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010278 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010279
10280 // If the return value is not being used, the type may not be compatible
10281 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010282 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010283
10284 // Add the new return attributes.
10285 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010286 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010287
10288 AI = CS.arg_begin();
10289 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10290 const Type *ParamTy = FT->getParamType(i);
10291 if ((*AI)->getType() == ParamTy) {
10292 Args.push_back(*AI);
10293 } else {
10294 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10295 false, ParamTy, false);
Chris Lattnerad7516a2009-08-30 18:50:58 +000010296 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010297 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010298
10299 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010300 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010301 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010302 }
10303
10304 // If the function takes more arguments than the call was taking, add them
Chris Lattnerad7516a2009-08-30 18:50:58 +000010305 // now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010306 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +000010307 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010308
Chris Lattnerad7516a2009-08-30 18:50:58 +000010309 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010310 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010311 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +000010312 errs() << "WARNING: While resolving call to function '"
10313 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010314 } else {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010315 // Add all of the arguments in their promoted form to the arg list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010316 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10317 const Type *PTy = getPromotedType((*AI)->getType());
10318 if (PTy != (*AI)->getType()) {
10319 // Must promote to pass through va_arg area!
Chris Lattnerad7516a2009-08-30 18:50:58 +000010320 Instruction::CastOps opcode =
10321 CastInst::getCastOpcode(*AI, false, PTy, false);
10322 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010323 } else {
10324 Args.push_back(*AI);
10325 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010326
Duncan Sands4ced1f82008-01-13 08:02:44 +000010327 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010328 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010329 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010330 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010331 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010332 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010333
Devang Patelf2a4a922008-09-26 22:53:05 +000010334 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10335 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10336
Devang Patele9d08b82009-10-14 17:29:00 +000010337 if (NewRetTy->isVoidTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010338 Caller->setName(""); // Void type should not have a name.
10339
Eric Christopher3e7381f2009-07-25 02:45:27 +000010340 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10341 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010342
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010343 Instruction *NC;
10344 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010345 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010346 Args.begin(), Args.end(),
10347 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010348 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010349 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010350 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010351 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10352 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010353 CallInst *CI = cast<CallInst>(Caller);
10354 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010355 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010356 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010357 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010358 }
10359
10360 // Insert a cast of the return type as necessary.
10361 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010362 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patele9d08b82009-10-14 17:29:00 +000010363 if (!NV->getType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010364 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010365 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010366 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010367
10368 // If this is an invoke instruction, we should insert it after the first
10369 // non-phi, instruction in the normal successor block.
10370 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010371 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010372 InsertNewInstBefore(NC, *I);
10373 } else {
10374 // Otherwise, it's a call, just insert cast right after the call instr
10375 InsertNewInstBefore(NC, *Caller);
10376 }
Chris Lattner4796b622009-08-30 06:22:51 +000010377 Worklist.AddUsersToWorkList(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010378 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010379 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010380 }
10381 }
10382
Devang Pateledad36f2009-10-13 21:41:20 +000010383
Chris Lattner26b7f942009-08-31 05:17:58 +000010384 if (!Caller->use_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010385 Caller->replaceAllUsesWith(NV);
Chris Lattner26b7f942009-08-31 05:17:58 +000010386
10387 EraseInstFromFunction(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010388 return true;
10389}
10390
Duncan Sands74833f22007-09-17 10:26:40 +000010391// transformCallThroughTrampoline - Turn a call to a function created by the
10392// init_trampoline intrinsic into a direct call to the underlying function.
10393//
10394Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10395 Value *Callee = CS.getCalledValue();
10396 const PointerType *PTy = cast<PointerType>(Callee->getType());
10397 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010398 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010399
10400 // If the call already has the 'nest' attribute somewhere then give up -
10401 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010402 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010403 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010404
10405 IntrinsicInst *Tramp =
10406 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10407
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010408 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010409 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10410 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10411
Devang Pateld222f862008-09-25 21:00:45 +000010412 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010413 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010414 unsigned NestIdx = 1;
10415 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010416 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010417
10418 // Look for a parameter marked with the 'nest' attribute.
10419 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10420 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010421 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010422 // Record the parameter type and any other attributes.
10423 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010424 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010425 break;
10426 }
10427
10428 if (NestTy) {
10429 Instruction *Caller = CS.getInstruction();
10430 std::vector<Value*> NewArgs;
10431 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10432
Devang Pateld222f862008-09-25 21:00:45 +000010433 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010434 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010435
Duncan Sands74833f22007-09-17 10:26:40 +000010436 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010437 // mean appending it. Likewise for attributes.
10438
Devang Patelf2a4a922008-09-26 22:53:05 +000010439 // Add any result attributes.
10440 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010441 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010442
Duncan Sands74833f22007-09-17 10:26:40 +000010443 {
10444 unsigned Idx = 1;
10445 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10446 do {
10447 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010448 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010449 Value *NestVal = Tramp->getOperand(3);
10450 if (NestVal->getType() != NestTy)
10451 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10452 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010453 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010454 }
10455
10456 if (I == E)
10457 break;
10458
Duncan Sands48b81112008-01-14 19:52:09 +000010459 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010460 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010461 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010462 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010463 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010464
10465 ++Idx, ++I;
10466 } while (1);
10467 }
10468
Devang Patelf2a4a922008-09-26 22:53:05 +000010469 // Add any function attributes.
10470 if (Attributes Attr = Attrs.getFnAttributes())
10471 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10472
Duncan Sands74833f22007-09-17 10:26:40 +000010473 // The trampoline may have been bitcast to a bogus type (FTy).
10474 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010475 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010476
Duncan Sands74833f22007-09-17 10:26:40 +000010477 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010478 NewTypes.reserve(FTy->getNumParams()+1);
10479
Duncan Sands74833f22007-09-17 10:26:40 +000010480 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010481 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010482 {
10483 unsigned Idx = 1;
10484 FunctionType::param_iterator I = FTy->param_begin(),
10485 E = FTy->param_end();
10486
10487 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010488 if (Idx == NestIdx)
10489 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010490 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010491
10492 if (I == E)
10493 break;
10494
Duncan Sands48b81112008-01-14 19:52:09 +000010495 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010496 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010497
10498 ++Idx, ++I;
10499 } while (1);
10500 }
10501
10502 // Replace the trampoline call with a direct call. Let the generic
10503 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010504 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +000010505 FTy->isVarArg());
10506 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010507 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +000010508 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010509 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +000010510 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10511 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010512
10513 Instruction *NewCaller;
10514 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010515 NewCaller = InvokeInst::Create(NewCallee,
10516 II->getNormalDest(), II->getUnwindDest(),
10517 NewArgs.begin(), NewArgs.end(),
10518 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010519 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010520 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010521 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010522 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10523 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010524 if (cast<CallInst>(Caller)->isTailCall())
10525 cast<CallInst>(NewCaller)->setTailCall();
10526 cast<CallInst>(NewCaller)->
10527 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010528 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010529 }
Devang Patele9d08b82009-10-14 17:29:00 +000010530 if (!Caller->getType()->isVoidTy())
Duncan Sands74833f22007-09-17 10:26:40 +000010531 Caller->replaceAllUsesWith(NewCaller);
10532 Caller->eraseFromParent();
Chris Lattner3183fb62009-08-30 06:13:40 +000010533 Worklist.Remove(Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010534 return 0;
10535 }
10536 }
10537
10538 // Replace the trampoline call with a direct call. Since there is no 'nest'
10539 // parameter, there is no need to adjust the argument list. Let the generic
10540 // code sort out any function type mismatches.
10541 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010542 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +000010543 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010544 CS.setCalledFunction(NewCallee);
10545 return CS.getInstruction();
10546}
10547
Dan Gohman09cf2b62009-09-16 16:50:24 +000010548/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10549/// 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 +000010550/// and a single binop.
10551Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10552 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010553 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010554 unsigned Opc = FirstInst->getOpcode();
10555 Value *LHSVal = FirstInst->getOperand(0);
10556 Value *RHSVal = FirstInst->getOperand(1);
10557
10558 const Type *LHSType = LHSVal->getType();
10559 const Type *RHSType = RHSVal->getType();
10560
Dan Gohman09cf2b62009-09-16 16:50:24 +000010561 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010562 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010563 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10564 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10565 // Verify type of the LHS matches so we don't fold cmp's of different
10566 // types or GEP's with different index types.
10567 I->getOperand(0)->getType() != LHSType ||
10568 I->getOperand(1)->getType() != RHSType)
10569 return 0;
10570
10571 // If they are CmpInst instructions, check their predicates
10572 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10573 if (cast<CmpInst>(I)->getPredicate() !=
10574 cast<CmpInst>(FirstInst)->getPredicate())
10575 return 0;
10576
10577 // Keep track of which operand needs a phi node.
10578 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10579 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10580 }
Dan Gohman09cf2b62009-09-16 16:50:24 +000010581
10582 // If both LHS and RHS would need a PHI, don't do this transformation,
10583 // because it would increase the number of PHIs entering the block,
10584 // which leads to higher register pressure. This is especially
10585 // bad when the PHIs are in the header of a loop.
10586 if (!LHSVal && !RHSVal)
10587 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010588
Chris Lattner30078012008-12-01 03:42:51 +000010589 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010590
10591 Value *InLHS = FirstInst->getOperand(0);
10592 Value *InRHS = FirstInst->getOperand(1);
10593 PHINode *NewLHS = 0, *NewRHS = 0;
10594 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010595 NewLHS = PHINode::Create(LHSType,
10596 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010597 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10598 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10599 InsertNewInstBefore(NewLHS, PN);
10600 LHSVal = NewLHS;
10601 }
10602
10603 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010604 NewRHS = PHINode::Create(RHSType,
10605 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010606 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10607 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10608 InsertNewInstBefore(NewRHS, PN);
10609 RHSVal = NewRHS;
10610 }
10611
10612 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010613 if (NewLHS || NewRHS) {
10614 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10615 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10616 if (NewLHS) {
10617 Value *NewInLHS = InInst->getOperand(0);
10618 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10619 }
10620 if (NewRHS) {
10621 Value *NewInRHS = InInst->getOperand(1);
10622 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10623 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010624 }
10625 }
10626
10627 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010628 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010629 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohmane6803b82009-08-25 23:17:54 +000010630 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson6601fcd2009-07-09 23:48:35 +000010631 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010632}
10633
Chris Lattner9e1916e2008-12-01 02:34:36 +000010634Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10635 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10636
10637 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10638 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010639 // This is true if all GEP bases are allocas and if all indices into them are
10640 // constants.
10641 bool AllBasePointersAreAllocas = true;
Dan Gohman37a534b2009-09-16 02:01:52 +000010642
10643 // We don't want to replace this phi if the replacement would require
Dan Gohman09cf2b62009-09-16 16:50:24 +000010644 // more than one phi, which leads to higher register pressure. This is
10645 // especially bad when the PHIs are in the header of a loop.
Dan Gohman37a534b2009-09-16 02:01:52 +000010646 bool NeededPhi = false;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010647
Dan Gohman09cf2b62009-09-16 16:50:24 +000010648 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010649 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10650 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10651 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10652 GEP->getNumOperands() != FirstInst->getNumOperands())
10653 return 0;
10654
Chris Lattneradf354b2009-02-21 00:46:50 +000010655 // Keep track of whether or not all GEPs are of alloca pointers.
10656 if (AllBasePointersAreAllocas &&
10657 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10658 !GEP->hasAllConstantIndices()))
10659 AllBasePointersAreAllocas = false;
10660
Chris Lattner9e1916e2008-12-01 02:34:36 +000010661 // Compare the operand lists.
10662 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10663 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10664 continue;
10665
10666 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10667 // if one of the PHIs has a constant for the index. The index may be
10668 // substantially cheaper to compute for the constants, so making it a
10669 // variable index could pessimize the path. This also handles the case
10670 // for struct indices, which must always be constant.
10671 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10672 isa<ConstantInt>(GEP->getOperand(op)))
10673 return 0;
10674
10675 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10676 return 0;
Dan Gohman37a534b2009-09-16 02:01:52 +000010677
10678 // If we already needed a PHI for an earlier operand, and another operand
10679 // also requires a PHI, we'd be introducing more PHIs than we're
10680 // eliminating, which increases register pressure on entry to the PHI's
10681 // block.
10682 if (NeededPhi)
10683 return 0;
10684
Chris Lattner9e1916e2008-12-01 02:34:36 +000010685 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohman37a534b2009-09-16 02:01:52 +000010686 NeededPhi = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010687 }
10688 }
10689
Chris Lattneradf354b2009-02-21 00:46:50 +000010690 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010691 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010692 // offset calculation, but all the predecessors will have to materialize the
10693 // stack address into a register anyway. We'd actually rather *clone* the
10694 // load up into the predecessors so that we have a load of a gep of an alloca,
10695 // which can usually all be folded into the load.
10696 if (AllBasePointersAreAllocas)
10697 return 0;
10698
Chris Lattner9e1916e2008-12-01 02:34:36 +000010699 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10700 // that is variable.
10701 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10702
10703 bool HasAnyPHIs = false;
10704 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10705 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10706 Value *FirstOp = FirstInst->getOperand(i);
10707 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10708 FirstOp->getName()+".pn");
10709 InsertNewInstBefore(NewPN, PN);
10710
10711 NewPN->reserveOperandSpace(e);
10712 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10713 OperandPhis[i] = NewPN;
10714 FixedOperands[i] = NewPN;
10715 HasAnyPHIs = true;
10716 }
10717
10718
10719 // Add all operands to the new PHIs.
10720 if (HasAnyPHIs) {
10721 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10722 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10723 BasicBlock *InBB = PN.getIncomingBlock(i);
10724
10725 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10726 if (PHINode *OpPhi = OperandPhis[op])
10727 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10728 }
10729 }
10730
10731 Value *Base = FixedOperands[0];
Dan Gohmanf3a08b82009-09-07 23:54:19 +000010732 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10733 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10734 FixedOperands.end()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000010735 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10736 FixedOperands.end());
Chris Lattner9e1916e2008-12-01 02:34:36 +000010737}
10738
10739
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010740/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10741/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010742/// obvious the value of the load is not changed from the point of the load to
10743/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010744///
10745/// Finally, it is safe, but not profitable, to sink a load targetting a
10746/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10747/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010748static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010749 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10750
10751 for (++BBI; BBI != E; ++BBI)
10752 if (BBI->mayWriteToMemory())
10753 return false;
10754
10755 // Check for non-address taken alloca. If not address-taken already, it isn't
10756 // profitable to do this xform.
10757 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10758 bool isAddressTaken = false;
10759 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10760 UI != E; ++UI) {
10761 if (isa<LoadInst>(UI)) continue;
10762 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10763 // If storing TO the alloca, then the address isn't taken.
10764 if (SI->getOperand(1) == AI) continue;
10765 }
10766 isAddressTaken = true;
10767 break;
10768 }
10769
Chris Lattneradf354b2009-02-21 00:46:50 +000010770 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010771 return false;
10772 }
10773
Chris Lattneradf354b2009-02-21 00:46:50 +000010774 // If this load is a load from a GEP with a constant offset from an alloca,
10775 // then we don't want to sink it. In its present form, it will be
10776 // load [constant stack offset]. Sinking it will cause us to have to
10777 // materialize the stack addresses in each predecessor in a register only to
10778 // do a shared load from register in the successor.
10779 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10780 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10781 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10782 return false;
10783
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010784 return true;
10785}
10786
Chris Lattner38751f82009-11-01 20:04:24 +000010787Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10788 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10789
10790 // When processing loads, we need to propagate two bits of information to the
10791 // sunk load: whether it is volatile, and what its alignment is. We currently
10792 // don't sink loads when some have their alignment specified and some don't.
10793 // visitLoadInst will propagate an alignment onto the load when TD is around,
10794 // and if TD isn't around, we can't handle the mixed case.
10795 bool isVolatile = FirstLI->isVolatile();
10796 unsigned LoadAlignment = FirstLI->getAlignment();
10797
10798 // We can't sink the load if the loaded value could be modified between the
10799 // load and the PHI.
10800 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10801 !isSafeAndProfitableToSinkLoad(FirstLI))
10802 return 0;
10803
10804 // If the PHI is of volatile loads and the load block has multiple
10805 // successors, sinking it would remove a load of the volatile value from
10806 // the path through the other successor.
10807 if (isVolatile &&
10808 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10809 return 0;
10810
10811 // Check to see if all arguments are the same operation.
10812 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10813 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10814 if (!LI || !LI->hasOneUse())
10815 return 0;
10816
10817 // We can't sink the load if the loaded value could be modified between
10818 // the load and the PHI.
10819 if (LI->isVolatile() != isVolatile ||
10820 LI->getParent() != PN.getIncomingBlock(i) ||
10821 !isSafeAndProfitableToSinkLoad(LI))
10822 return 0;
10823
10824 // If some of the loads have an alignment specified but not all of them,
10825 // we can't do the transformation.
10826 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10827 return 0;
10828
Chris Lattner52fe1bc2009-11-01 20:07:07 +000010829 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner38751f82009-11-01 20:04:24 +000010830
10831 // If the PHI is of volatile loads and the load block has multiple
10832 // successors, sinking it would remove a load of the volatile value from
10833 // the path through the other successor.
10834 if (isVolatile &&
10835 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10836 return 0;
10837 }
10838
10839 // Okay, they are all the same operation. Create a new PHI node of the
10840 // correct type, and PHI together all of the LHS's of the instructions.
10841 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10842 PN.getName()+".in");
10843 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10844
10845 Value *InVal = FirstLI->getOperand(0);
10846 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10847
10848 // Add all operands to the new PHI.
10849 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10850 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10851 if (NewInVal != InVal)
10852 InVal = 0;
10853 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10854 }
10855
10856 Value *PhiVal;
10857 if (InVal) {
10858 // The new PHI unions all of the same values together. This is really
10859 // common, so we handle it intelligently here for compile-time speed.
10860 PhiVal = InVal;
10861 delete NewPN;
10862 } else {
10863 InsertNewInstBefore(NewPN, PN);
10864 PhiVal = NewPN;
10865 }
10866
10867 // If this was a volatile load that we are merging, make sure to loop through
10868 // and mark all the input loads as non-volatile. If we don't do this, we will
10869 // insert a new volatile load and the old ones will not be deletable.
10870 if (isVolatile)
10871 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10872 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10873
10874 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
10875}
10876
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010877
10878// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10879// operator and they all are only used by the PHI, PHI together their
10880// inputs, and do the operation once, to the result of the PHI.
10881Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10882 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10883
Chris Lattner38751f82009-11-01 20:04:24 +000010884 if (isa<GetElementPtrInst>(FirstInst))
10885 return FoldPHIArgGEPIntoPHI(PN);
10886 if (isa<LoadInst>(FirstInst))
10887 return FoldPHIArgLoadIntoPHI(PN);
10888
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010889 // Scan the instruction, looking for input operations that can be folded away.
10890 // If all input operands to the phi are the same instruction (e.g. a cast from
10891 // the same type or "+42") we can pull the operation through the PHI, reducing
10892 // code size and simplifying code.
10893 Constant *ConstantOp = 0;
10894 const Type *CastSrcTy = 0;
Chris Lattner310a00f2009-11-01 19:50:13 +000010895
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010896 if (isa<CastInst>(FirstInst)) {
10897 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattner4ca73902009-11-08 21:20:06 +000010898
10899 // Be careful about transforming integer PHIs. We don't want to pessimize
10900 // the code by turning an i32 into an i1293.
10901 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
10902 // If we don't have TD, we don't know if the original PHI was legal.
10903 if (!TD) return 0;
10904
10905 unsigned PHIWidth = PN.getType()->getPrimitiveSizeInBits();
10906 unsigned NewWidth = CastSrcTy->getPrimitiveSizeInBits();
10907 bool PHILegal = TD->isLegalInteger(PHIWidth);
10908 bool NewLegal = TD->isLegalInteger(NewWidth);
Chris Lattner1cd526b2009-11-08 19:23:30 +000010909
Chris Lattner4ca73902009-11-08 21:20:06 +000010910 // If this is a legal integer PHI node, and pulling the operation through
10911 // would cause it to be an illegal integer PHI, don't do the
10912 // transformation.
10913 if (PHILegal && !NewLegal)
10914 return 0;
10915
10916 // Otherwise, if both are illegal, do not increase the size of the PHI. We
10917 // do allow things like i160 -> i64, but not i64 -> i160.
10918 if (!PHILegal && !NewLegal && NewWidth > PHIWidth)
10919 return 0;
10920 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010921 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10922 // Can fold binop, compare or shift here if the RHS is a constant,
10923 // otherwise call FoldPHIArgBinOpIntoPHI.
10924 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10925 if (ConstantOp == 0)
10926 return FoldPHIArgBinOpIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010927 } else {
10928 return 0; // Cannot fold this operation.
10929 }
10930
10931 // Check to see if all arguments are the same operation.
10932 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner38751f82009-11-01 20:04:24 +000010933 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10934 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010935 return 0;
10936 if (CastSrcTy) {
10937 if (I->getOperand(0)->getType() != CastSrcTy)
10938 return 0; // Cast operation must match.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010939 } else if (I->getOperand(1) != ConstantOp) {
10940 return 0;
10941 }
10942 }
10943
10944 // Okay, they are all the same operation. Create a new PHI node of the
10945 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010946 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10947 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010948 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10949
10950 Value *InVal = FirstInst->getOperand(0);
10951 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10952
10953 // Add all operands to the new PHI.
10954 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10955 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10956 if (NewInVal != InVal)
10957 InVal = 0;
10958 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10959 }
10960
10961 Value *PhiVal;
10962 if (InVal) {
10963 // The new PHI unions all of the same values together. This is really
10964 // common, so we handle it intelligently here for compile-time speed.
10965 PhiVal = InVal;
10966 delete NewPN;
10967 } else {
10968 InsertNewInstBefore(NewPN, PN);
10969 PhiVal = NewPN;
10970 }
10971
10972 // Insert and return the new operation.
Chris Lattner310a00f2009-11-01 19:50:13 +000010973 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010974 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner310a00f2009-11-01 19:50:13 +000010975
Chris Lattnerfc984e92008-04-29 17:13:43 +000010976 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010977 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner310a00f2009-11-01 19:50:13 +000010978
Chris Lattner38751f82009-11-01 20:04:24 +000010979 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10980 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10981 PhiVal, ConstantOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010982}
10983
10984/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10985/// that is dead.
10986static bool DeadPHICycle(PHINode *PN,
10987 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10988 if (PN->use_empty()) return true;
10989 if (!PN->hasOneUse()) return false;
10990
10991 // Remember this node, and if we find the cycle, return.
10992 if (!PotentiallyDeadPHIs.insert(PN))
10993 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010994
10995 // Don't scan crazily complex things.
10996 if (PotentiallyDeadPHIs.size() == 16)
10997 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010998
10999 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11000 return DeadPHICycle(PU, PotentiallyDeadPHIs);
11001
11002 return false;
11003}
11004
Chris Lattner27b695d2007-11-06 21:52:06 +000011005/// PHIsEqualValue - Return true if this phi node is always equal to
11006/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11007/// z = some value; x = phi (y, z); y = phi (x, z)
11008static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11009 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11010 // See if we already saw this PHI node.
11011 if (!ValueEqualPHIs.insert(PN))
11012 return true;
11013
11014 // Don't scan crazily complex things.
11015 if (ValueEqualPHIs.size() == 16)
11016 return false;
11017
11018 // Scan the operands to see if they are either phi nodes or are equal to
11019 // the value.
11020 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11021 Value *Op = PN->getIncomingValue(i);
11022 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11023 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11024 return false;
11025 } else if (Op != NonPhiInVal)
11026 return false;
11027 }
11028
11029 return true;
11030}
11031
11032
Chris Lattner1cd526b2009-11-08 19:23:30 +000011033namespace {
11034struct PHIUsageRecord {
Chris Lattner073c12c2009-11-09 01:38:00 +000011035 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner1cd526b2009-11-08 19:23:30 +000011036 unsigned Shift; // The amount shifted.
11037 Instruction *Inst; // The trunc instruction.
11038
Chris Lattner073c12c2009-11-09 01:38:00 +000011039 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11040 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner1cd526b2009-11-08 19:23:30 +000011041
11042 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattner073c12c2009-11-09 01:38:00 +000011043 if (PHIId < RHS.PHIId) return true;
11044 if (PHIId > RHS.PHIId) return false;
Chris Lattner1cd526b2009-11-08 19:23:30 +000011045 if (Shift < RHS.Shift) return true;
Chris Lattner073c12c2009-11-09 01:38:00 +000011046 if (Shift > RHS.Shift) return false;
11047 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner1cd526b2009-11-08 19:23:30 +000011048 RHS.Inst->getType()->getPrimitiveSizeInBits();
11049 }
11050};
Chris Lattner073c12c2009-11-09 01:38:00 +000011051
11052struct LoweredPHIRecord {
11053 PHINode *PN; // The PHI that was lowered.
11054 unsigned Shift; // The amount shifted.
11055 unsigned Width; // The width extracted.
11056
11057 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11058 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11059
11060 // Ctor form used by DenseMap.
11061 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11062 : PN(pn), Shift(Sh), Width(0) {}
11063};
11064}
11065
11066namespace llvm {
11067 template<>
11068 struct DenseMapInfo<LoweredPHIRecord> {
11069 static inline LoweredPHIRecord getEmptyKey() {
11070 return LoweredPHIRecord(0, 0);
11071 }
11072 static inline LoweredPHIRecord getTombstoneKey() {
11073 return LoweredPHIRecord(0, 1);
11074 }
11075 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11076 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11077 (Val.Width>>3);
11078 }
11079 static bool isEqual(const LoweredPHIRecord &LHS,
11080 const LoweredPHIRecord &RHS) {
11081 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11082 LHS.Width == RHS.Width;
11083 }
11084 static bool isPod() { return true; }
11085 };
Chris Lattner1cd526b2009-11-08 19:23:30 +000011086}
11087
11088
11089/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11090/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11091/// so, we split the PHI into the various pieces being extracted. This sort of
11092/// thing is introduced when SROA promotes an aggregate to large integer values.
11093///
11094/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11095/// inttoptr. We should produce new PHIs in the right type.
11096///
Chris Lattner073c12c2009-11-09 01:38:00 +000011097Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11098 // PHIUsers - Keep track of all of the truncated values extracted from a set
11099 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner1cd526b2009-11-08 19:23:30 +000011100 SmallVector<PHIUsageRecord, 16> PHIUsers;
11101
Chris Lattner073c12c2009-11-09 01:38:00 +000011102 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11103 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11104 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11105 // check the uses of (to ensure they are all extracts).
11106 SmallVector<PHINode*, 8> PHIsToSlice;
11107 SmallPtrSet<PHINode*, 8> PHIsInspected;
11108
11109 PHIsToSlice.push_back(&FirstPhi);
11110 PHIsInspected.insert(&FirstPhi);
11111
11112 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11113 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner1cd526b2009-11-08 19:23:30 +000011114
Chris Lattner073c12c2009-11-09 01:38:00 +000011115 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11116 UI != E; ++UI) {
11117 Instruction *User = cast<Instruction>(*UI);
11118
11119 // If the user is a PHI, inspect its uses recursively.
11120 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11121 if (PHIsInspected.insert(UserPN))
11122 PHIsToSlice.push_back(UserPN);
11123 continue;
11124 }
11125
11126 // Truncates are always ok.
11127 if (isa<TruncInst>(User)) {
11128 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11129 continue;
11130 }
11131
11132 // Otherwise it must be a lshr which can only be used by one trunc.
11133 if (User->getOpcode() != Instruction::LShr ||
11134 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11135 !isa<ConstantInt>(User->getOperand(1)))
11136 return 0;
11137
11138 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11139 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner1cd526b2009-11-08 19:23:30 +000011140 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011141 }
11142
11143 // If we have no users, they must be all self uses, just nuke the PHI.
11144 if (PHIUsers.empty())
Chris Lattner073c12c2009-11-09 01:38:00 +000011145 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner1cd526b2009-11-08 19:23:30 +000011146
11147 // If this phi node is transformable, create new PHIs for all the pieces
11148 // extracted out of it. First, sort the users by their offset and size.
11149 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11150
Chris Lattner073c12c2009-11-09 01:38:00 +000011151 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11152 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11153 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11154 );
Chris Lattner1cd526b2009-11-08 19:23:30 +000011155
Chris Lattner073c12c2009-11-09 01:38:00 +000011156 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11157 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner1cd526b2009-11-08 19:23:30 +000011158 DenseMap<BasicBlock*, Value*> PredValues;
11159
Chris Lattner073c12c2009-11-09 01:38:00 +000011160 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11161 // introduce redundant PHIs.
11162 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11163
11164 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11165 unsigned PHIId = PHIUsers[UserI].PHIId;
11166 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner1cd526b2009-11-08 19:23:30 +000011167 unsigned Offset = PHIUsers[UserI].Shift;
11168 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner1cd526b2009-11-08 19:23:30 +000011169
Chris Lattner073c12c2009-11-09 01:38:00 +000011170 PHINode *EltPHI;
11171
11172 // If we've already lowered a user like this, reuse the previously lowered
11173 // value.
11174 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner1cd526b2009-11-08 19:23:30 +000011175
Chris Lattner073c12c2009-11-09 01:38:00 +000011176 // Otherwise, Create the new PHI node for this user.
11177 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11178 assert(EltPHI->getType() != PN->getType() &&
11179 "Truncate didn't shrink phi?");
11180
11181 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11182 BasicBlock *Pred = PN->getIncomingBlock(i);
11183 Value *&PredVal = PredValues[Pred];
11184
11185 // If we already have a value for this predecessor, reuse it.
11186 if (PredVal) {
11187 EltPHI->addIncoming(PredVal, Pred);
11188 continue;
11189 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011190
Chris Lattner073c12c2009-11-09 01:38:00 +000011191 // Handle the PHI self-reuse case.
11192 Value *InVal = PN->getIncomingValue(i);
11193 if (InVal == PN) {
11194 PredVal = EltPHI;
11195 EltPHI->addIncoming(PredVal, Pred);
11196 continue;
11197 } else if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
11198 // If the incoming value was a PHI, and if it was one of the PHIs we
11199 // already rewrote it, just use the lowered value.
11200 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11201 PredVal = Res;
11202 EltPHI->addIncoming(PredVal, Pred);
11203 continue;
11204 }
11205 }
11206
11207 // Otherwise, do an extract in the predecessor.
11208 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11209 Value *Res = InVal;
11210 if (Offset)
11211 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11212 Offset), "extract");
11213 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11214 PredVal = Res;
11215 EltPHI->addIncoming(Res, Pred);
11216
11217 // If the incoming value was a PHI, and if it was one of the PHIs we are
11218 // rewriting, we will ultimately delete the code we inserted. This
11219 // means we need to revisit that PHI to make sure we extract out the
11220 // needed piece.
11221 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11222 if (PHIsInspected.count(OldInVal)) {
11223 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11224 OldInVal)-PHIsToSlice.begin();
11225 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11226 cast<Instruction>(Res)));
11227 ++UserE;
11228 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011229 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011230 PredValues.clear();
Chris Lattner1cd526b2009-11-08 19:23:30 +000011231
Chris Lattner073c12c2009-11-09 01:38:00 +000011232 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11233 << *EltPHI << '\n');
11234 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner1cd526b2009-11-08 19:23:30 +000011235 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011236
Chris Lattner073c12c2009-11-09 01:38:00 +000011237 // Replace the use of this piece with the PHI node.
11238 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner1cd526b2009-11-08 19:23:30 +000011239 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011240
11241 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11242 // with undefs.
11243 Value *Undef = UndefValue::get(FirstPhi.getType());
11244 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11245 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11246 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner1cd526b2009-11-08 19:23:30 +000011247}
11248
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011249// PHINode simplification
11250//
11251Instruction *InstCombiner::visitPHINode(PHINode &PN) {
11252 // If LCSSA is around, don't mess with Phi nodes
11253 if (MustPreserveLCSSA) return 0;
11254
11255 if (Value *V = PN.hasConstantValue())
11256 return ReplaceInstUsesWith(PN, V);
11257
11258 // If all PHI operands are the same operation, pull them through the PHI,
11259 // reducing code size.
11260 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000011261 isa<Instruction>(PN.getIncomingValue(1)) &&
11262 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11263 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11264 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11265 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011266 PN.getIncomingValue(0)->hasOneUse())
11267 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11268 return Result;
11269
11270 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11271 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11272 // PHI)... break the cycle.
11273 if (PN.hasOneUse()) {
11274 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11275 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
11276 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
11277 PotentiallyDeadPHIs.insert(&PN);
11278 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011279 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011280 }
11281
11282 // If this phi has a single use, and if that use just computes a value for
11283 // the next iteration of a loop, delete the phi. This occurs with unused
11284 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11285 // common case here is good because the only other things that catch this
11286 // are induction variable analysis (sometimes) and ADCE, which is only run
11287 // late.
11288 if (PHIUser->hasOneUse() &&
11289 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11290 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000011291 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011292 }
11293 }
11294
Chris Lattner27b695d2007-11-06 21:52:06 +000011295 // We sometimes end up with phi cycles that non-obviously end up being the
11296 // same value, for example:
11297 // z = some value; x = phi (y, z); y = phi (x, z)
11298 // where the phi nodes don't necessarily need to be in the same block. Do a
11299 // quick check to see if the PHI node only contains a single non-phi value, if
11300 // so, scan to see if the phi cycle is actually equal to that value.
11301 {
11302 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11303 // Scan for the first non-phi operand.
11304 while (InValNo != NumOperandVals &&
11305 isa<PHINode>(PN.getIncomingValue(InValNo)))
11306 ++InValNo;
11307
11308 if (InValNo != NumOperandVals) {
11309 Value *NonPhiInVal = PN.getOperand(InValNo);
11310
11311 // Scan the rest of the operands to see if there are any conflicts, if so
11312 // there is no need to recursively scan other phis.
11313 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11314 Value *OpVal = PN.getIncomingValue(InValNo);
11315 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11316 break;
11317 }
11318
11319 // If we scanned over all operands, then we have one unique value plus
11320 // phi values. Scan PHI nodes to see if they all merge in each other or
11321 // the value.
11322 if (InValNo == NumOperandVals) {
11323 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11324 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11325 return ReplaceInstUsesWith(PN, NonPhiInVal);
11326 }
11327 }
11328 }
Dan Gohman012d03d2009-10-30 22:22:22 +000011329
Dan Gohman2cc8e842009-10-31 14:22:52 +000011330 // If there are multiple PHIs, sort their operands so that they all list
11331 // the blocks in the same order. This will help identical PHIs be eliminated
11332 // by other passes. Other passes shouldn't depend on this for correctness
11333 // however.
11334 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11335 if (&PN != FirstPN)
11336 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman012d03d2009-10-30 22:22:22 +000011337 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman2cc8e842009-10-31 14:22:52 +000011338 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11339 if (BBA != BBB) {
11340 Value *VA = PN.getIncomingValue(i);
11341 unsigned j = PN.getBasicBlockIndex(BBB);
11342 Value *VB = PN.getIncomingValue(j);
11343 PN.setIncomingBlock(i, BBB);
11344 PN.setIncomingValue(i, VB);
11345 PN.setIncomingBlock(j, BBA);
11346 PN.setIncomingValue(j, VA);
Chris Lattnerd56c0cb2009-10-31 17:48:31 +000011347 // NOTE: Instcombine normally would want us to "return &PN" if we
11348 // modified any of the operands of an instruction. However, since we
11349 // aren't adding or removing uses (just rearranging them) we don't do
11350 // this in this case.
Dan Gohman2cc8e842009-10-31 14:22:52 +000011351 }
Dan Gohman012d03d2009-10-30 22:22:22 +000011352 }
11353
Chris Lattner1cd526b2009-11-08 19:23:30 +000011354 // If this is an integer PHI and we know that it has an illegal type, see if
11355 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11356 // PHI into the various pieces being extracted. This sort of thing is
11357 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattner4ca73902009-11-08 21:20:06 +000011358 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner1cd526b2009-11-08 19:23:30 +000011359 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11360 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11361 return Res;
11362
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011363 return 0;
11364}
11365
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011366Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11367 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerf3a23592009-08-30 20:36:46 +000011368 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011369 if (GEP.getNumOperands() == 1)
11370 return ReplaceInstUsesWith(GEP, PtrOp);
11371
11372 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011373 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011374
11375 bool HasZeroPointerIndex = false;
11376 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11377 HasZeroPointerIndex = C->isNullValue();
11378
11379 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11380 return ReplaceInstUsesWith(GEP, PtrOp);
11381
11382 // Eliminate unneeded casts for indices.
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011383 if (TD) {
11384 bool MadeChange = false;
11385 unsigned PtrSize = TD->getPointerSizeInBits();
11386
11387 gep_type_iterator GTI = gep_type_begin(GEP);
11388 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11389 I != E; ++I, ++GTI) {
11390 if (!isa<SequentialType>(*GTI)) continue;
11391
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011392 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011393 // to what we need. If narrower, sign-extend it to what we need. This
11394 // explicit cast can make subsequent optimizations more obvious.
11395 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011396 if (OpBits == PtrSize)
11397 continue;
11398
Chris Lattnerd6164c22009-08-30 20:01:10 +000011399 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011400 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011401 }
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011402 if (MadeChange) return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011403 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011404
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011405 // Combine Indices - If the source pointer to this getelementptr instruction
11406 // is a getelementptr instruction, combine the indices of the two
11407 // getelementptr instructions into a single instruction.
11408 //
Dan Gohman17f46f72009-07-28 01:40:03 +000011409 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011410 // Note that if our source is a gep chain itself that we wait for that
11411 // chain to be resolved before we perform this transformation. This
11412 // avoids us creating a TON of code in some cases.
11413 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011414 if (GetElementPtrInst *SrcGEP =
11415 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11416 if (SrcGEP->getNumOperands() == 2)
11417 return 0; // Wait until our source is folded to completion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011418
11419 SmallVector<Value*, 8> Indices;
11420
11421 // Find out whether the last index in the source GEP is a sequential idx.
11422 bool EndsWithSequential = false;
Chris Lattner1c641fc2009-08-30 05:30:55 +000011423 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11424 I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011425 EndsWithSequential = !isa<StructType>(*I);
11426
11427 // Can we combine the two pointer arithmetics offsets?
11428 if (EndsWithSequential) {
11429 // Replace: gep (gep %P, long B), long A, ...
11430 // With: T = long A+B; gep %P, T, ...
11431 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011432 Value *Sum;
11433 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11434 Value *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +000011435 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011436 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +000011437 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011438 Sum = SO1;
11439 } else {
Chris Lattner1c641fc2009-08-30 05:30:55 +000011440 // If they aren't the same type, then the input hasn't been processed
11441 // by the loop above yet (which canonicalizes sequential index types to
11442 // intptr_t). Just avoid transforming this until the input has been
11443 // normalized.
11444 if (SO1->getType() != GO1->getType())
11445 return 0;
Chris Lattnerad7516a2009-08-30 18:50:58 +000011446 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011447 }
11448
Chris Lattner1c641fc2009-08-30 05:30:55 +000011449 // Update the GEP in place if possible.
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011450 if (Src->getNumOperands() == 2) {
11451 GEP.setOperand(0, Src->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011452 GEP.setOperand(1, Sum);
11453 return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011454 }
Chris Lattner1c641fc2009-08-30 05:30:55 +000011455 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011456 Indices.push_back(Sum);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011457 Indices.append(GEP.op_begin()+2, GEP.op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011458 } else if (isa<Constant>(*GEP.idx_begin()) &&
11459 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011460 Src->getNumOperands() != 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011461 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner1c641fc2009-08-30 05:30:55 +000011462 Indices.append(Src->op_begin()+1, Src->op_end());
11463 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011464 }
11465
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011466 if (!Indices.empty())
11467 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11468 Src->isInBounds()) ?
11469 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11470 Indices.end(), GEP.getName()) :
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011471 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011472 Indices.end(), GEP.getName());
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011473 }
11474
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011475 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11476 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011477 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattnerf3a23592009-08-30 20:36:46 +000011478
Chris Lattner83288fa2009-08-30 20:38:21 +000011479 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11480 // want to change the gep until the bitcasts are eliminated.
11481 if (getBitCastOperand(X)) {
11482 Worklist.AddValue(PtrOp);
11483 return 0;
11484 }
11485
Chris Lattnerf3a23592009-08-30 20:36:46 +000011486 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11487 // into : GEP [10 x i8]* X, i32 0, ...
11488 //
11489 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11490 // into : GEP i8* X, ...
11491 //
11492 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011493 if (HasZeroPointerIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011494 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11495 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011496 if (const ArrayType *CATy =
11497 dyn_cast<ArrayType>(CPTy->getElementType())) {
11498 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11499 if (CATy->getElementType() == XTy->getElementType()) {
11500 // -> GEP i8* X, ...
11501 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011502 return cast<GEPOperator>(&GEP)->isInBounds() ?
11503 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11504 GEP.getName()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000011505 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11506 GEP.getName());
Chris Lattnerf3a23592009-08-30 20:36:46 +000011507 }
11508
11509 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sandscf866e62009-03-02 09:18:21 +000011510 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011511 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011512 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011513 // At this point, we know that the cast source type is a pointer
11514 // to an array of the same type as the destination pointer
11515 // array. Because the array type is never stepped over (there
11516 // is a leading zero) we can fold the cast into this GEP.
11517 GEP.setOperand(0, X);
11518 return &GEP;
11519 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011520 }
11521 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011522 } else if (GEP.getNumOperands() == 2) {
11523 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011524 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11525 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011526 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11527 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000011528 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011529 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11530 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011531 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011532 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011533 Idx[1] = GEP.getOperand(1);
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011534 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11535 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerad7516a2009-08-30 18:50:58 +000011536 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011537 // V and GEP are both pointer types --> BitCast
Chris Lattnerad7516a2009-08-30 18:50:58 +000011538 return new BitCastInst(NewGEP, GEP.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011539 }
11540
11541 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011542 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011543 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011544 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011545
Owen Anderson35b47072009-08-13 21:58:54 +000011546 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011547 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011548 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011549
11550 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11551 // allow either a mul, shift, or constant here.
11552 Value *NewIdx = 0;
11553 ConstantInt *Scale = 0;
11554 if (ArrayEltSize == 1) {
11555 NewIdx = GEP.getOperand(1);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011556 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011557 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011558 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011559 Scale = CI;
11560 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11561 if (Inst->getOpcode() == Instruction::Shl &&
11562 isa<ConstantInt>(Inst->getOperand(1))) {
11563 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11564 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +000011565 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011566 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011567 NewIdx = Inst->getOperand(0);
11568 } else if (Inst->getOpcode() == Instruction::Mul &&
11569 isa<ConstantInt>(Inst->getOperand(1))) {
11570 Scale = cast<ConstantInt>(Inst->getOperand(1));
11571 NewIdx = Inst->getOperand(0);
11572 }
11573 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011574
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011575 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011576 // out, perform the transformation. Note, we don't know whether Scale is
11577 // signed or not. We'll use unsigned version of division/modulo
11578 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011579 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011580 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011581 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011582 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011583 if (Scale->getZExtValue() != 1) {
Chris Lattnerbf09d632009-08-30 05:56:44 +000011584 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11585 false /*ZExt*/);
Chris Lattnerad7516a2009-08-30 18:50:58 +000011586 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011587 }
11588
11589 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011590 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011591 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011592 Idx[1] = NewIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011593 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11594 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11595 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011596 // The NewGEP must be pointer typed, so must the old one -> BitCast
11597 return new BitCastInst(NewGEP, GEP.getType());
11598 }
11599 }
11600 }
11601 }
Chris Lattner111ea772009-01-09 04:53:57 +000011602
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011603 /// See if we can simplify:
Chris Lattner5119c702009-08-30 05:55:36 +000011604 /// X = bitcast A* to B*
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011605 /// Y = gep X, <...constant indices...>
11606 /// into a gep of the original struct. This is important for SROA and alias
11607 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011608 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011609 if (TD &&
11610 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011611 // Determine how much the GEP moves the pointer. We are guaranteed to get
11612 // a constant back from EmitGEPOffset.
Chris Lattner93e6ff92009-11-04 08:05:20 +000011613 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011614 int64_t Offset = OffsetV->getSExtValue();
11615
11616 // If this GEP instruction doesn't move the pointer, just replace the GEP
11617 // with a bitcast of the real input to the dest type.
11618 if (Offset == 0) {
11619 // If the bitcast is of an allocation, and the allocation will be
11620 // converted to match the type of the cast, don't touch this.
Victor Hernandezb1687302009-10-23 21:09:37 +000011621 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez48c3c542009-09-18 22:35:49 +000011622 isMalloc(BCI->getOperand(0))) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011623 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11624 if (Instruction *I = visitBitCast(*BCI)) {
11625 if (I != BCI) {
11626 I->takeName(BCI);
11627 BCI->getParent()->getInstList().insert(BCI, I);
11628 ReplaceInstUsesWith(*BCI, I);
11629 }
11630 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011631 }
Chris Lattner111ea772009-01-09 04:53:57 +000011632 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011633 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011634 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011635
11636 // Otherwise, if the offset is non-zero, we need to find out if there is a
11637 // field at Offset in 'A's type. If so, we can pull the cast through the
11638 // GEP.
11639 SmallVector<Value*, 8> NewIndices;
11640 const Type *InTy =
11641 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000011642 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011643 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11644 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11645 NewIndices.end()) :
11646 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11647 NewIndices.end());
Chris Lattnerad7516a2009-08-30 18:50:58 +000011648
11649 if (NGEP->getType() == GEP.getType())
11650 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011651 NGEP->takeName(&GEP);
11652 return new BitCastInst(NGEP, GEP.getType());
11653 }
Chris Lattner111ea772009-01-09 04:53:57 +000011654 }
11655 }
11656
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011657 return 0;
11658}
11659
Victor Hernandezb1687302009-10-23 21:09:37 +000011660Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattner310a00f2009-11-01 19:50:13 +000011661 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011662 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011663 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11664 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011665 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandez37f513d2009-10-17 01:18:07 +000011666 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandezb1687302009-10-23 21:09:37 +000011667 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerad7516a2009-08-30 18:50:58 +000011668 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011669
11670 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011671 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011672 //
11673 BasicBlock::iterator It = New;
Victor Hernandezb1687302009-10-23 21:09:37 +000011674 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011675
11676 // Now that I is pointing to the first non-allocation-inst in the block,
11677 // insert our getelementptr instruction...
11678 //
Owen Anderson35b47072009-08-13 21:58:54 +000011679 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011680 Value *Idx[2];
11681 Idx[0] = NullIdx;
11682 Idx[1] = NullIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011683 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11684 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011685
11686 // Now make everything use the getelementptr instead of the original
11687 // allocation.
11688 return ReplaceInstUsesWith(AI, V);
11689 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +000011690 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011691 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011692 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011693
Dan Gohmana80e2712009-07-21 23:21:54 +000011694 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000011695 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011696 // Note that we only do this for alloca's, because malloc should allocate
11697 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011698 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +000011699 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000011700
11701 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11702 if (AI.getAlignment() == 0)
11703 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11704 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011705
11706 return 0;
11707}
11708
Victor Hernandez93946082009-10-24 04:23:03 +000011709Instruction *InstCombiner::visitFree(Instruction &FI) {
11710 Value *Op = FI.getOperand(1);
11711
11712 // free undef -> unreachable.
11713 if (isa<UndefValue>(Op)) {
11714 // Insert a new store to null because we cannot modify the CFG here.
11715 new StoreInst(ConstantInt::getTrue(*Context),
11716 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11717 return EraseInstFromFunction(FI);
11718 }
11719
11720 // If we have 'free null' delete the instruction. This can happen in stl code
11721 // when lots of inlining happens.
11722 if (isa<ConstantPointerNull>(Op))
11723 return EraseInstFromFunction(FI);
11724
Victor Hernandezf9a7a332009-10-26 23:43:48 +000011725 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman1674ea52009-10-27 00:11:02 +000011726 if (isMalloc(Op)) {
Victor Hernandez93946082009-10-24 04:23:03 +000011727 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11728 if (Op->hasOneUse() && CI->hasOneUse()) {
11729 EraseInstFromFunction(FI);
11730 EraseInstFromFunction(*CI);
11731 return EraseInstFromFunction(*cast<Instruction>(Op));
11732 }
11733 } else {
11734 // Op is a call to malloc
11735 if (Op->hasOneUse()) {
11736 EraseInstFromFunction(FI);
11737 return EraseInstFromFunction(*cast<Instruction>(Op));
11738 }
11739 }
Dan Gohman1674ea52009-10-27 00:11:02 +000011740 }
Victor Hernandez93946082009-10-24 04:23:03 +000011741
11742 return 0;
11743}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011744
11745/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011746static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011747 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011748 User *CI = cast<User>(LI.getOperand(0));
11749 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011750 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011751
Mon P Wangbd05ed82009-02-07 22:19:29 +000011752 const PointerType *DestTy = cast<PointerType>(CI->getType());
11753 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011754 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011755
11756 // If the address spaces don't match, don't eliminate the cast.
11757 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11758 return 0;
11759
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011760 const Type *SrcPTy = SrcTy->getElementType();
11761
11762 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11763 isa<VectorType>(DestPTy)) {
11764 // If the source is an array, the code below will not succeed. Check to
11765 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11766 // constants.
11767 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11768 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11769 if (ASrcTy->getNumElements() != 0) {
11770 Value *Idxs[2];
Chris Lattner7bdc6d52009-10-22 06:44:07 +000011771 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11772 Idxs[1] = Idxs[0];
Owen Anderson02b48c32009-07-29 18:55:55 +000011773 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011774 SrcTy = cast<PointerType>(CastOp->getType());
11775 SrcPTy = SrcTy->getElementType();
11776 }
11777
Dan Gohmana80e2712009-07-21 23:21:54 +000011778 if (IC.getTargetData() &&
11779 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011780 isa<VectorType>(SrcPTy)) &&
11781 // Do not allow turning this into a load of an integer, which is then
11782 // casted to a pointer, this pessimizes pointer analysis a lot.
11783 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000011784 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11785 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011786
11787 // Okay, we are casting from one integer or pointer type to another of
11788 // the same size. Instead of casting the pointer before the load, cast
11789 // the result of the loaded value.
Chris Lattnerad7516a2009-08-30 18:50:58 +000011790 Value *NewLoad =
11791 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011792 // Now cast the result of the load.
11793 return new BitCastInst(NewLoad, LI.getType());
11794 }
11795 }
11796 }
11797 return 0;
11798}
11799
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011800Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11801 Value *Op = LI.getOperand(0);
11802
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011803 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011804 if (TD) {
11805 unsigned KnownAlign =
11806 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11807 if (KnownAlign >
11808 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11809 LI.getAlignment()))
11810 LI.setAlignment(KnownAlign);
11811 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011812
Chris Lattnerf3a23592009-08-30 20:36:46 +000011813 // load (cast X) --> cast (load X) iff safe.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011814 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011815 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011816 return Res;
11817
11818 // None of the following transforms are legal for volatile loads.
11819 if (LI.isVolatile()) return 0;
11820
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011821 // Do really simple store-to-load forwarding and load CSE, to catch cases
11822 // where there are several consequtive memory accesses to the same location,
11823 // separated by a few arithmetic operations.
11824 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011825 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11826 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011827
Chris Lattner05274832009-10-22 06:25:11 +000011828 // load(gep null, ...) -> unreachable
Christopher Lamb2c175392007-12-29 07:56:53 +000011829 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11830 const Value *GEPI0 = GEPI->getOperand(0);
11831 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +000011832 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011833 // Insert a new store to null instruction before the load to indicate
11834 // that this code is not reachable. We do this instead of inserting
11835 // an unreachable instruction directly because we cannot modify the
11836 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011837 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011838 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011839 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011840 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011841 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011842
Chris Lattner05274832009-10-22 06:25:11 +000011843 // load null/undef -> unreachable
11844 // TODO: Consider a target hook for valid address spaces for this xform.
11845 if (isa<UndefValue>(Op) ||
11846 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11847 // Insert a new store to null instruction before the load to indicate that
11848 // this code is not reachable. We do this instead of inserting an
11849 // unreachable instruction directly because we cannot modify the CFG.
11850 new StoreInst(UndefValue::get(LI.getType()),
11851 Constant::getNullValue(Op->getType()), &LI);
11852 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011853 }
Chris Lattner05274832009-10-22 06:25:11 +000011854
11855 // Instcombine load (constantexpr_cast global) -> cast (load global)
11856 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11857 if (CE->isCast())
11858 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11859 return Res;
11860
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011861 if (Op->hasOneUse()) {
11862 // Change select and PHI nodes to select values instead of addresses: this
11863 // helps alias analysis out a lot, allows many others simplifications, and
11864 // exposes redundancy in the code.
11865 //
11866 // Note that we cannot do the transformation unless we know that the
11867 // introduced loads cannot trap! Something like this is valid as long as
11868 // the condition is always false: load (select bool %C, int* null, int* %G),
11869 // but it would not be valid if we transformed it to load from null
11870 // unconditionally.
11871 //
11872 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11873 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11874 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11875 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000011876 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11877 SI->getOperand(1)->getName()+".val");
11878 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11879 SI->getOperand(2)->getName()+".val");
Gabor Greifd6da1d02008-04-06 20:25:17 +000011880 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011881 }
11882
11883 // load (select (cond, null, P)) -> load P
11884 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11885 if (C->isNullValue()) {
11886 LI.setOperand(0, SI->getOperand(2));
11887 return &LI;
11888 }
11889
11890 // load (select (cond, P, null)) -> load P
11891 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11892 if (C->isNullValue()) {
11893 LI.setOperand(0, SI->getOperand(1));
11894 return &LI;
11895 }
11896 }
11897 }
11898 return 0;
11899}
11900
11901/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011902/// when possible. This makes it generally easy to do alias analysis and/or
11903/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011904static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11905 User *CI = cast<User>(SI.getOperand(1));
11906 Value *CastOp = CI->getOperand(0);
11907
11908 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011909 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11910 if (SrcTy == 0) return 0;
11911
11912 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011913
Chris Lattnera032c0e2009-01-16 20:08:59 +000011914 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11915 return 0;
11916
Chris Lattner54dddc72009-01-24 01:00:13 +000011917 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11918 /// to its first element. This allows us to handle things like:
11919 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11920 /// on 32-bit hosts.
11921 SmallVector<Value*, 4> NewGEPIndices;
11922
Chris Lattnera032c0e2009-01-16 20:08:59 +000011923 // If the source is an array, the code below will not succeed. Check to
11924 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11925 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011926 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11927 // Index through pointer.
Owen Anderson35b47072009-08-13 21:58:54 +000011928 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner54dddc72009-01-24 01:00:13 +000011929 NewGEPIndices.push_back(Zero);
11930
11931 while (1) {
11932 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011933 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011934 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011935 NewGEPIndices.push_back(Zero);
11936 SrcPTy = STy->getElementType(0);
11937 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11938 NewGEPIndices.push_back(Zero);
11939 SrcPTy = ATy->getElementType();
11940 } else {
11941 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011942 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011943 }
11944
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011945 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000011946 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011947
11948 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11949 return 0;
11950
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011951 // If the pointers point into different address spaces or if they point to
11952 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000011953 if (!IC.getTargetData() ||
11954 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011955 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000011956 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11957 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000011958 return 0;
11959
11960 // Okay, we are casting from one integer or pointer type to another of
11961 // the same size. Instead of casting the pointer before
11962 // the store, cast the value to be stored.
11963 Value *NewCast;
11964 Value *SIOp0 = SI.getOperand(0);
11965 Instruction::CastOps opcode = Instruction::BitCast;
11966 const Type* CastSrcTy = SIOp0->getType();
11967 const Type* CastDstTy = SrcPTy;
11968 if (isa<PointerType>(CastDstTy)) {
11969 if (CastSrcTy->isInteger())
11970 opcode = Instruction::IntToPtr;
11971 } else if (isa<IntegerType>(CastDstTy)) {
11972 if (isa<PointerType>(SIOp0->getType()))
11973 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011974 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011975
11976 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11977 // emit a GEP to index into its first field.
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011978 if (!NewGEPIndices.empty())
11979 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11980 NewGEPIndices.end());
Chris Lattner54dddc72009-01-24 01:00:13 +000011981
Chris Lattnerad7516a2009-08-30 18:50:58 +000011982 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11983 SIOp0->getName()+".c");
Chris Lattnera032c0e2009-01-16 20:08:59 +000011984 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011985}
11986
Chris Lattner6fd8c802008-11-27 08:56:30 +000011987/// equivalentAddressValues - Test if A and B will obviously have the same
11988/// value. This includes recognizing that %t0 and %t1 will have the same
11989/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000011990/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011991/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000011992/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011993/// %t2 = load i32* %t1
11994///
11995static bool equivalentAddressValues(Value *A, Value *B) {
11996 // Test if the values are trivially equivalent.
11997 if (A == B) return true;
11998
11999 // Test if the values come form identical arithmetic instructions.
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000012000 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12001 // its only used to compare two uses within the same basic block, which
12002 // means that they'll always either have the same value or one of them
12003 // will have an undefined value.
Chris Lattner6fd8c802008-11-27 08:56:30 +000012004 if (isa<BinaryOperator>(A) ||
12005 isa<CastInst>(A) ||
12006 isa<PHINode>(A) ||
12007 isa<GetElementPtrInst>(A))
12008 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000012009 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner6fd8c802008-11-27 08:56:30 +000012010 return true;
12011
12012 // Otherwise they may not be equivalent.
12013 return false;
12014}
12015
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012016// If this instruction has two uses, one of which is a llvm.dbg.declare,
12017// return the llvm.dbg.declare.
12018DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12019 if (!V->hasNUses(2))
12020 return 0;
12021 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12022 UI != E; ++UI) {
12023 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12024 return DI;
12025 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12026 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12027 return DI;
12028 }
12029 }
12030 return 0;
12031}
12032
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012033Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12034 Value *Val = SI.getOperand(0);
12035 Value *Ptr = SI.getOperand(1);
12036
12037 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
12038 EraseInstFromFunction(SI);
12039 ++NumCombined;
12040 return 0;
12041 }
12042
12043 // If the RHS is an alloca with a single use, zapify the store, making the
12044 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012045 // If the RHS is an alloca with a two uses, the other one being a
12046 // llvm.dbg.declare, zapify the store and the declare, making the
12047 // alloca dead. We must do this to prevent declare's from affecting
12048 // codegen.
12049 if (!SI.isVolatile()) {
12050 if (Ptr->hasOneUse()) {
12051 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012052 EraseInstFromFunction(SI);
12053 ++NumCombined;
12054 return 0;
12055 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012056 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12057 if (isa<AllocaInst>(GEP->getOperand(0))) {
12058 if (GEP->getOperand(0)->hasOneUse()) {
12059 EraseInstFromFunction(SI);
12060 ++NumCombined;
12061 return 0;
12062 }
12063 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12064 EraseInstFromFunction(*DI);
12065 EraseInstFromFunction(SI);
12066 ++NumCombined;
12067 return 0;
12068 }
12069 }
12070 }
12071 }
12072 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12073 EraseInstFromFunction(*DI);
12074 EraseInstFromFunction(SI);
12075 ++NumCombined;
12076 return 0;
12077 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012078 }
12079
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012080 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000012081 if (TD) {
12082 unsigned KnownAlign =
12083 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12084 if (KnownAlign >
12085 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12086 SI.getAlignment()))
12087 SI.setAlignment(KnownAlign);
12088 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012089
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012090 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012091 // stores to the same location, separated by a few arithmetic operations. This
12092 // situation often occurs with bitfield accesses.
12093 BasicBlock::iterator BBI = &SI;
12094 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12095 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000012096 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000012097 // Don't count debug info directives, lest they affect codegen,
12098 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12099 // It is necessary for correctness to skip those that feed into a
12100 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000012101 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000012102 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012103 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012104 continue;
12105 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012106
12107 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12108 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000012109 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12110 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012111 ++NumDeadStore;
12112 ++BBI;
12113 EraseInstFromFunction(*PrevSI);
12114 continue;
12115 }
12116 break;
12117 }
12118
12119 // If this is a load, we have to stop. However, if the loaded value is from
12120 // the pointer we're loading and is producing the pointer we're storing,
12121 // then *this* store is dead (X = load P; store X -> P).
12122 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000012123 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12124 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012125 EraseInstFromFunction(SI);
12126 ++NumCombined;
12127 return 0;
12128 }
12129 // Otherwise, this is a load from some other location. Stores before it
12130 // may not be dead.
12131 break;
12132 }
12133
12134 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000012135 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012136 break;
12137 }
12138
12139
12140 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
12141
12142 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner6807a242009-08-30 20:06:40 +000012143 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012144 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012145 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012146 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner3183fb62009-08-30 06:13:40 +000012147 Worklist.Add(U); // Dropped a use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012148 ++NumCombined;
12149 }
12150 return 0; // Do not modify these!
12151 }
12152
12153 // store undef, Ptr -> noop
12154 if (isa<UndefValue>(Val)) {
12155 EraseInstFromFunction(SI);
12156 ++NumCombined;
12157 return 0;
12158 }
12159
12160 // If the pointer destination is a cast, see if we can fold the cast into the
12161 // source instead.
12162 if (isa<CastInst>(Ptr))
12163 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12164 return Res;
12165 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
12166 if (CE->isCast())
12167 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12168 return Res;
12169
12170
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012171 // If this store is the last instruction in the basic block (possibly
12172 // excepting debug info instructions and the pointer bitcasts that feed
12173 // into them), and if the block ends with an unconditional branch, try
12174 // to move it to the successor block.
12175 BBI = &SI;
12176 do {
12177 ++BBI;
12178 } while (isa<DbgInfoIntrinsic>(BBI) ||
12179 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012180 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
12181 if (BI->isUnconditional())
12182 if (SimplifyStoreAtEndOfBlock(SI))
12183 return 0; // xform done!
12184
12185 return 0;
12186}
12187
12188/// SimplifyStoreAtEndOfBlock - Turn things like:
12189/// if () { *P = v1; } else { *P = v2 }
12190/// into a phi node with a store in the successor.
12191///
12192/// Simplify things like:
12193/// *P = v1; if () { *P = v2; }
12194/// into a phi node with a store in the successor.
12195///
12196bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12197 BasicBlock *StoreBB = SI.getParent();
12198
12199 // Check to see if the successor block has exactly two incoming edges. If
12200 // so, see if the other predecessor contains a store to the same location.
12201 // if so, insert a PHI node (if needed) and move the stores down.
12202 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12203
12204 // Determine whether Dest has exactly two predecessors and, if so, compute
12205 // the other predecessor.
12206 pred_iterator PI = pred_begin(DestBB);
12207 BasicBlock *OtherBB = 0;
12208 if (*PI != StoreBB)
12209 OtherBB = *PI;
12210 ++PI;
12211 if (PI == pred_end(DestBB))
12212 return false;
12213
12214 if (*PI != StoreBB) {
12215 if (OtherBB)
12216 return false;
12217 OtherBB = *PI;
12218 }
12219 if (++PI != pred_end(DestBB))
12220 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000012221
12222 // Bail out if all the relevant blocks aren't distinct (this can happen,
12223 // for example, if SI is in an infinite loop)
12224 if (StoreBB == DestBB || OtherBB == DestBB)
12225 return false;
12226
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012227 // Verify that the other block ends in a branch and is not otherwise empty.
12228 BasicBlock::iterator BBI = OtherBB->getTerminator();
12229 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12230 if (!OtherBr || BBI == OtherBB->begin())
12231 return false;
12232
12233 // If the other block ends in an unconditional branch, check for the 'if then
12234 // else' case. there is an instruction before the branch.
12235 StoreInst *OtherStore = 0;
12236 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012237 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012238 // Skip over debugging info.
12239 while (isa<DbgInfoIntrinsic>(BBI) ||
12240 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12241 if (BBI==OtherBB->begin())
12242 return false;
12243 --BBI;
12244 }
Chris Lattner69fa3f52009-11-02 02:06:37 +000012245 // If this isn't a store, isn't a store to the same location, or if the
12246 // alignments differ, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012247 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner69fa3f52009-11-02 02:06:37 +000012248 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12249 OtherStore->getAlignment() != SI.getAlignment())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012250 return false;
12251 } else {
12252 // Otherwise, the other block ended with a conditional branch. If one of the
12253 // destinations is StoreBB, then we have the if/then case.
12254 if (OtherBr->getSuccessor(0) != StoreBB &&
12255 OtherBr->getSuccessor(1) != StoreBB)
12256 return false;
12257
12258 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12259 // if/then triangle. See if there is a store to the same ptr as SI that
12260 // lives in OtherBB.
12261 for (;; --BBI) {
12262 // Check to see if we find the matching store.
12263 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner69fa3f52009-11-02 02:06:37 +000012264 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12265 OtherStore->getAlignment() != SI.getAlignment())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012266 return false;
12267 break;
12268 }
Eli Friedman3a311d52008-06-13 22:02:12 +000012269 // If we find something that may be using or overwriting the stored
12270 // value, or if we run out of instructions, we can't do the xform.
12271 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012272 BBI == OtherBB->begin())
12273 return false;
12274 }
12275
12276 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000012277 // make sure nothing reads or overwrites the stored value in
12278 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012279 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12280 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000012281 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012282 return false;
12283 }
12284 }
12285
12286 // Insert a PHI node now if we need it.
12287 Value *MergedVal = OtherStore->getOperand(0);
12288 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000012289 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012290 PN->reserveOperandSpace(2);
12291 PN->addIncoming(SI.getOperand(0), SI.getParent());
12292 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12293 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12294 }
12295
12296 // Advance to a place where it is safe to insert the new store and
12297 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000012298 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012299 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner69fa3f52009-11-02 02:06:37 +000012300 OtherStore->isVolatile(),
12301 SI.getAlignment()), *BBI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012302
12303 // Nuke the old stores.
12304 EraseInstFromFunction(SI);
12305 EraseInstFromFunction(*OtherStore);
12306 ++NumCombined;
12307 return true;
12308}
12309
12310
12311Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12312 // Change br (not X), label True, label False to: br X, label False, True
12313 Value *X = 0;
12314 BasicBlock *TrueDest;
12315 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +000012316 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012317 !isa<Constant>(X)) {
12318 // Swap Destinations and condition...
12319 BI.setCondition(X);
12320 BI.setSuccessor(0, FalseDest);
12321 BI.setSuccessor(1, TrueDest);
12322 return &BI;
12323 }
12324
12325 // Cannonicalize fcmp_one -> fcmp_oeq
12326 FCmpInst::Predicate FPred; Value *Y;
12327 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000012328 TrueDest, FalseDest)) &&
12329 BI.getCondition()->hasOneUse())
12330 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12331 FPred == FCmpInst::FCMP_OGE) {
12332 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12333 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12334
12335 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012336 BI.setSuccessor(0, FalseDest);
12337 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000012338 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012339 return &BI;
12340 }
12341
12342 // Cannonicalize icmp_ne -> icmp_eq
12343 ICmpInst::Predicate IPred;
12344 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000012345 TrueDest, FalseDest)) &&
12346 BI.getCondition()->hasOneUse())
12347 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12348 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12349 IPred == ICmpInst::ICMP_SGE) {
12350 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12351 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12352 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012353 BI.setSuccessor(0, FalseDest);
12354 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000012355 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012356 return &BI;
12357 }
12358
12359 return 0;
12360}
12361
12362Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12363 Value *Cond = SI.getCondition();
12364 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12365 if (I->getOpcode() == Instruction::Add)
12366 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12367 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12368 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012369 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +000012370 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012371 AddRHS));
12372 SI.setOperand(0, I->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +000012373 Worklist.Add(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012374 return &SI;
12375 }
12376 }
12377 return 0;
12378}
12379
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012380Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012381 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012382
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012383 if (!EV.hasIndices())
12384 return ReplaceInstUsesWith(EV, Agg);
12385
12386 if (Constant *C = dyn_cast<Constant>(Agg)) {
12387 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012388 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012389
12390 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +000012391 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012392
12393 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12394 // Extract the element indexed by the first index out of the constant
12395 Value *V = C->getOperand(*EV.idx_begin());
12396 if (EV.getNumIndices() > 1)
12397 // Extract the remaining indices out of the constant indexed by the
12398 // first index
12399 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12400 else
12401 return ReplaceInstUsesWith(EV, V);
12402 }
12403 return 0; // Can't handle other constants
12404 }
12405 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12406 // We're extracting from an insertvalue instruction, compare the indices
12407 const unsigned *exti, *exte, *insi, *inse;
12408 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12409 exte = EV.idx_end(), inse = IV->idx_end();
12410 exti != exte && insi != inse;
12411 ++exti, ++insi) {
12412 if (*insi != *exti)
12413 // The insert and extract both reference distinctly different elements.
12414 // This means the extract is not influenced by the insert, and we can
12415 // replace the aggregate operand of the extract with the aggregate
12416 // operand of the insert. i.e., replace
12417 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12418 // %E = extractvalue { i32, { i32 } } %I, 0
12419 // with
12420 // %E = extractvalue { i32, { i32 } } %A, 0
12421 return ExtractValueInst::Create(IV->getAggregateOperand(),
12422 EV.idx_begin(), EV.idx_end());
12423 }
12424 if (exti == exte && insi == inse)
12425 // Both iterators are at the end: Index lists are identical. Replace
12426 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12427 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12428 // with "i32 42"
12429 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12430 if (exti == exte) {
12431 // The extract list is a prefix of the insert list. i.e. replace
12432 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12433 // %E = extractvalue { i32, { i32 } } %I, 1
12434 // with
12435 // %X = extractvalue { i32, { i32 } } %A, 1
12436 // %E = insertvalue { i32 } %X, i32 42, 0
12437 // by switching the order of the insert and extract (though the
12438 // insertvalue should be left in, since it may have other uses).
Chris Lattnerad7516a2009-08-30 18:50:58 +000012439 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12440 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012441 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12442 insi, inse);
12443 }
12444 if (insi == inse)
12445 // The insert list is a prefix of the extract list
12446 // We can simply remove the common indices from the extract and make it
12447 // operate on the inserted value instead of the insertvalue result.
12448 // i.e., replace
12449 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12450 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12451 // with
12452 // %E extractvalue { i32 } { i32 42 }, 0
12453 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12454 exti, exte);
12455 }
Chris Lattner69a70752009-11-09 07:07:56 +000012456 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12457 // We're extracting from an intrinsic, see if we're the only user, which
12458 // allows us to simplify multiple result intrinsics to simpler things that
12459 // just get one value..
12460 if (II->hasOneUse()) {
12461 // Check if we're grabbing the overflow bit or the result of a 'with
12462 // overflow' intrinsic. If it's the latter we can remove the intrinsic
12463 // and replace it with a traditional binary instruction.
12464 switch (II->getIntrinsicID()) {
12465 case Intrinsic::uadd_with_overflow:
12466 case Intrinsic::sadd_with_overflow:
12467 if (*EV.idx_begin() == 0) { // Normal result.
12468 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12469 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12470 EraseInstFromFunction(*II);
12471 return BinaryOperator::CreateAdd(LHS, RHS);
12472 }
12473 break;
12474 case Intrinsic::usub_with_overflow:
12475 case Intrinsic::ssub_with_overflow:
12476 if (*EV.idx_begin() == 0) { // Normal result.
12477 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12478 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12479 EraseInstFromFunction(*II);
12480 return BinaryOperator::CreateSub(LHS, RHS);
12481 }
12482 break;
12483 case Intrinsic::umul_with_overflow:
12484 case Intrinsic::smul_with_overflow:
12485 if (*EV.idx_begin() == 0) { // Normal result.
12486 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12487 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12488 EraseInstFromFunction(*II);
12489 return BinaryOperator::CreateMul(LHS, RHS);
12490 }
12491 break;
12492 default:
12493 break;
12494 }
12495 }
12496 }
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012497 // Can't simplify extracts from other values. Note that nested extracts are
12498 // already simplified implicitely by the above (extract ( extract (insert) )
12499 // will be translated into extract ( insert ( extract ) ) first and then just
12500 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012501 return 0;
12502}
12503
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012504/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12505/// is to leave as a vector operation.
12506static bool CheapToScalarize(Value *V, bool isConstant) {
12507 if (isa<ConstantAggregateZero>(V))
12508 return true;
12509 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12510 if (isConstant) return true;
12511 // If all elts are the same, we can extract.
12512 Constant *Op0 = C->getOperand(0);
12513 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12514 if (C->getOperand(i) != Op0)
12515 return false;
12516 return true;
12517 }
12518 Instruction *I = dyn_cast<Instruction>(V);
12519 if (!I) return false;
12520
12521 // Insert element gets simplified to the inserted element or is deleted if
12522 // this is constant idx extract element and its a constant idx insertelt.
12523 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12524 isa<ConstantInt>(I->getOperand(2)))
12525 return true;
12526 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12527 return true;
12528 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12529 if (BO->hasOneUse() &&
12530 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12531 CheapToScalarize(BO->getOperand(1), isConstant)))
12532 return true;
12533 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12534 if (CI->hasOneUse() &&
12535 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12536 CheapToScalarize(CI->getOperand(1), isConstant)))
12537 return true;
12538
12539 return false;
12540}
12541
12542/// Read and decode a shufflevector mask.
12543///
12544/// It turns undef elements into values that are larger than the number of
12545/// elements in the input.
12546static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12547 unsigned NElts = SVI->getType()->getNumElements();
12548 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12549 return std::vector<unsigned>(NElts, 0);
12550 if (isa<UndefValue>(SVI->getOperand(2)))
12551 return std::vector<unsigned>(NElts, 2*NElts);
12552
12553 std::vector<unsigned> Result;
12554 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012555 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12556 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012557 Result.push_back(NElts*2); // undef -> 8
12558 else
Gabor Greif17396002008-06-12 21:37:33 +000012559 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012560 return Result;
12561}
12562
12563/// FindScalarElement - Given a vector and an element number, see if the scalar
12564/// value is already around as a register, for example if it were inserted then
12565/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012566static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012567 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012568 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12569 const VectorType *PTy = cast<VectorType>(V->getType());
12570 unsigned Width = PTy->getNumElements();
12571 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012572 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012573
12574 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012575 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012576 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +000012577 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012578 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12579 return CP->getOperand(EltNo);
12580 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12581 // If this is an insert to a variable element, we don't know what it is.
12582 if (!isa<ConstantInt>(III->getOperand(2)))
12583 return 0;
12584 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12585
12586 // If this is an insert to the element we are looking for, return the
12587 // inserted value.
12588 if (EltNo == IIElt)
12589 return III->getOperand(1);
12590
12591 // Otherwise, the insertelement doesn't modify the value, recurse on its
12592 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000012593 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012594 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012595 unsigned LHSWidth =
12596 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012597 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012598 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012599 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012600 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012601 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012602 else
Owen Andersonb99ecca2009-07-30 23:03:37 +000012603 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012604 }
12605
12606 // Otherwise, we don't know.
12607 return 0;
12608}
12609
12610Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012611 // If vector val is undef, replace extract with scalar undef.
12612 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012613 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012614
12615 // If vector val is constant 0, replace extract with scalar 0.
12616 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +000012617 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012618
12619 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012620 // If vector val is constant with all elements the same, replace EI with
12621 // that element. When the elements are not identical, we cannot replace yet
12622 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012623 Constant *op0 = C->getOperand(0);
Chris Lattner1ba36b72009-09-08 03:44:51 +000012624 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012625 if (C->getOperand(i) != op0) {
12626 op0 = 0;
12627 break;
12628 }
12629 if (op0)
12630 return ReplaceInstUsesWith(EI, op0);
12631 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000012632
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012633 // If extracting a specified index from the vector, see if we can recursively
12634 // find a previously computed scalar that was inserted into the vector.
12635 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12636 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner1ba36b72009-09-08 03:44:51 +000012637 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012638
12639 // If this is extracting an invalid index, turn this into undef, to avoid
12640 // crashing the code below.
12641 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +000012642 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012643
12644 // This instruction only demands the single element from the input vector.
12645 // If the input vector has a single use, simplify it based on this use
12646 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000012647 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012648 APInt UndefElts(VectorWidth, 0);
12649 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012650 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012651 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012652 EI.setOperand(0, V);
12653 return &EI;
12654 }
12655 }
12656
Owen Anderson24be4c12009-07-03 00:17:18 +000012657 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012658 return ReplaceInstUsesWith(EI, Elt);
12659
12660 // If the this extractelement is directly using a bitcast from a vector of
12661 // the same number of elements, see if we can find the source element from
12662 // it. In this case, we will end up needing to bitcast the scalars.
12663 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12664 if (const VectorType *VT =
12665 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12666 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012667 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12668 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012669 return new BitCastInst(Elt, EI.getType());
12670 }
12671 }
12672
12673 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattnera97bc602009-09-08 18:48:01 +000012674 // Push extractelement into predecessor operation if legal and
12675 // profitable to do so
12676 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12677 if (I->hasOneUse() &&
12678 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12679 Value *newEI0 =
12680 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12681 EI.getName()+".lhs");
12682 Value *newEI1 =
12683 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12684 EI.getName()+".rhs");
12685 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012686 }
Chris Lattnera97bc602009-09-08 18:48:01 +000012687 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012688 // Extracting the inserted element?
12689 if (IE->getOperand(2) == EI.getOperand(1))
12690 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12691 // If the inserted and extracted elements are constants, they must not
12692 // be the same value, extract from the pre-inserted value instead.
Chris Lattner78628292009-08-30 19:47:22 +000012693 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +000012694 Worklist.AddValue(EI.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012695 EI.setOperand(0, IE->getOperand(0));
12696 return &EI;
12697 }
12698 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12699 // If this is extracting an element from a shufflevector, figure out where
12700 // it came from and extract from the appropriate input element instead.
12701 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12702 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12703 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012704 unsigned LHSWidth =
12705 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12706
12707 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012708 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012709 else if (SrcIdx < LHSWidth*2) {
12710 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012711 Src = SVI->getOperand(1);
12712 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012713 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012714 }
Eric Christopher1ba36872009-07-25 02:28:41 +000012715 return ExtractElementInst::Create(Src,
Chris Lattner78628292009-08-30 19:47:22 +000012716 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12717 false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012718 }
12719 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000012720 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012721 }
12722 return 0;
12723}
12724
12725/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12726/// elements from either LHS or RHS, return the shuffle mask and true.
12727/// Otherwise, return false.
12728static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000012729 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012730 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012731 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12732 "Invalid CollectSingleShuffleElements");
12733 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12734
12735 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012736 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012737 return true;
12738 } else if (V == LHS) {
12739 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012740 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012741 return true;
12742 } else if (V == RHS) {
12743 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012744 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012745 return true;
12746 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12747 // If this is an insert of an extract from some other vector, include it.
12748 Value *VecOp = IEI->getOperand(0);
12749 Value *ScalarOp = IEI->getOperand(1);
12750 Value *IdxOp = IEI->getOperand(2);
12751
12752 if (!isa<ConstantInt>(IdxOp))
12753 return false;
12754 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12755
12756 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12757 // Okay, we can handle this if the vector we are insertinting into is
12758 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012759 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012760 // If so, update the mask to reflect the inserted undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012761 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012762 return true;
12763 }
12764 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12765 if (isa<ConstantInt>(EI->getOperand(1)) &&
12766 EI->getOperand(0)->getType() == V->getType()) {
12767 unsigned ExtractedIdx =
12768 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12769
12770 // This must be extracting from either LHS or RHS.
12771 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12772 // Okay, we can handle this if the vector we are insertinting into is
12773 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012774 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012775 // If so, update the mask to reflect the inserted value.
12776 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012777 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012778 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012779 } else {
12780 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012781 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012782 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012783
12784 }
12785 return true;
12786 }
12787 }
12788 }
12789 }
12790 }
12791 // TODO: Handle shufflevector here!
12792
12793 return false;
12794}
12795
12796/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12797/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12798/// that computes V and the LHS value of the shuffle.
12799static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012800 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012801 assert(isa<VectorType>(V->getType()) &&
12802 (RHS == 0 || V->getType() == RHS->getType()) &&
12803 "Invalid shuffle!");
12804 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12805
12806 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012807 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012808 return V;
12809 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012810 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012811 return V;
12812 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12813 // If this is an insert of an extract from some other vector, include it.
12814 Value *VecOp = IEI->getOperand(0);
12815 Value *ScalarOp = IEI->getOperand(1);
12816 Value *IdxOp = IEI->getOperand(2);
12817
12818 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12819 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12820 EI->getOperand(0)->getType() == V->getType()) {
12821 unsigned ExtractedIdx =
12822 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12823 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12824
12825 // Either the extracted from or inserted into vector must be RHSVec,
12826 // otherwise we'd end up with a shuffle of three inputs.
12827 if (EI->getOperand(0) == RHS || RHS == 0) {
12828 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000012829 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012830 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012831 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012832 return V;
12833 }
12834
12835 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012836 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12837 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012838 // Everything but the extracted element is replaced with the RHS.
12839 for (unsigned i = 0; i != NumElts; ++i) {
12840 if (i != InsertedIdx)
Owen Anderson35b47072009-08-13 21:58:54 +000012841 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012842 }
12843 return V;
12844 }
12845
12846 // If this insertelement is a chain that comes from exactly these two
12847 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000012848 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12849 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012850 return EI->getOperand(0);
12851
12852 }
12853 }
12854 }
12855 // TODO: Handle shufflevector here!
12856
12857 // Otherwise, can't do anything fancy. Return an identity vector.
12858 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012859 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012860 return V;
12861}
12862
12863Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12864 Value *VecOp = IE.getOperand(0);
12865 Value *ScalarOp = IE.getOperand(1);
12866 Value *IdxOp = IE.getOperand(2);
12867
12868 // Inserting an undef or into an undefined place, remove this.
12869 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12870 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000012871
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012872 // If the inserted element was extracted from some other vector, and if the
12873 // indexes are constant, try to turn this into a shufflevector operation.
12874 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12875 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12876 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000012877 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012878 unsigned ExtractedIdx =
12879 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12880 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12881
12882 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12883 return ReplaceInstUsesWith(IE, VecOp);
12884
12885 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012886 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012887
12888 // If we are extracting a value from a vector, then inserting it right
12889 // back into the same place, just use the input vector.
12890 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12891 return ReplaceInstUsesWith(IE, VecOp);
12892
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012893 // If this insertelement isn't used by some other insertelement, turn it
12894 // (and any insertelements it points to), into one big shuffle.
12895 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12896 std::vector<Constant*> Mask;
12897 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000012898 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Andersonb99ecca2009-07-30 23:03:37 +000012899 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012900 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000012901 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +000012902 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012903 }
12904 }
12905 }
12906
Eli Friedmanbefee262009-06-06 20:08:03 +000012907 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12908 APInt UndefElts(VWidth, 0);
12909 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12910 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12911 return &IE;
12912
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012913 return 0;
12914}
12915
12916
12917Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12918 Value *LHS = SVI.getOperand(0);
12919 Value *RHS = SVI.getOperand(1);
12920 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12921
12922 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012923
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012924 // Undefined shuffle mask -> undefined value.
12925 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012926 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012927
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012928 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012929
12930 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12931 return 0;
12932
Evan Cheng63295ab2009-02-03 10:05:09 +000012933 APInt UndefElts(VWidth, 0);
12934 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12935 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012936 LHS = SVI.getOperand(0);
12937 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012938 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012939 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012940
12941 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12942 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12943 if (LHS == RHS || isa<UndefValue>(LHS)) {
12944 if (isa<UndefValue>(LHS) && LHS == RHS) {
12945 // shuffle(undef,undef,mask) -> undef.
12946 return ReplaceInstUsesWith(SVI, LHS);
12947 }
12948
12949 // Remap any references to RHS to use LHS.
12950 std::vector<Constant*> Elts;
12951 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12952 if (Mask[i] >= 2*e)
Owen Anderson35b47072009-08-13 21:58:54 +000012953 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012954 else {
12955 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012956 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012957 Mask[i] = 2*e; // Turn into undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012958 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012959 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012960 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson35b47072009-08-13 21:58:54 +000012961 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012962 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012963 }
12964 }
12965 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +000012966 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +000012967 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012968 LHS = SVI.getOperand(0);
12969 RHS = SVI.getOperand(1);
12970 MadeChange = true;
12971 }
12972
12973 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12974 bool isLHSID = true, isRHSID = true;
12975
12976 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12977 if (Mask[i] >= e*2) continue; // Ignore undef values.
12978 // Is this an identity shuffle of the LHS value?
12979 isLHSID &= (Mask[i] == i);
12980
12981 // Is this an identity shuffle of the RHS value?
12982 isRHSID &= (Mask[i]-e == i);
12983 }
12984
12985 // Eliminate identity shuffles.
12986 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12987 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12988
12989 // If the LHS is a shufflevector itself, see if we can combine it with this
12990 // one without producing an unusual shuffle. Here we are really conservative:
12991 // we are absolutely afraid of producing a shuffle mask not in the input
12992 // program, because the code gen may not be smart enough to turn a merged
12993 // shuffle into two specific shuffles: it may produce worse code. As such,
12994 // we only merge two shuffles if the result is one of the two input shuffle
12995 // masks. In this case, merging the shuffles just removes one instruction,
12996 // which we know is safe. This is good for things like turning:
12997 // (splat(splat)) -> splat.
12998 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12999 if (isa<UndefValue>(RHS)) {
13000 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13001
13002 std::vector<unsigned> NewMask;
13003 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
13004 if (Mask[i] >= 2*e)
13005 NewMask.push_back(2*e);
13006 else
13007 NewMask.push_back(LHSMask[Mask[i]]);
13008
13009 // If the result mask is equal to the src shuffle or this shuffle mask, do
13010 // the replacement.
13011 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000013012 unsigned LHSInNElts =
13013 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013014 std::vector<Constant*> Elts;
13015 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000013016 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson35b47072009-08-13 21:58:54 +000013017 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013018 } else {
Owen Anderson35b47072009-08-13 21:58:54 +000013019 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013020 }
13021 }
13022 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13023 LHSSVI->getOperand(1),
Owen Anderson2f422e02009-07-28 21:19:26 +000013024 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013025 }
13026 }
13027 }
13028
13029 return MadeChange ? &SVI : 0;
13030}
13031
13032
13033
13034
13035/// TryToSinkInstruction - Try to move the specified instruction from its
13036/// current block into the beginning of DestBlock, which can only happen if it's
13037/// safe to move the instruction past all of the instructions between it and the
13038/// end of its block.
13039static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13040 assert(I->hasOneUse() && "Invariants didn't hold!");
13041
13042 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000013043 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000013044 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013045
13046 // Do not sink alloca instructions out of the entry block.
13047 if (isa<AllocaInst>(I) && I->getParent() ==
13048 &DestBlock->getParent()->getEntryBlock())
13049 return false;
13050
13051 // We can only sink load instructions if there is nothing between the load and
13052 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000013053 if (I->mayReadFromMemory()) {
13054 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013055 Scan != E; ++Scan)
13056 if (Scan->mayWriteToMemory())
13057 return false;
13058 }
13059
Dan Gohman514277c2008-05-23 21:05:58 +000013060 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013061
Dale Johannesen24339f12009-03-03 01:09:07 +000013062 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013063 I->moveBefore(InsertPos);
13064 ++NumSunkInst;
13065 return true;
13066}
13067
13068
13069/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13070/// all reachable code to the worklist.
13071///
13072/// This has a couple of tricks to make the code faster and more powerful. In
13073/// particular, we constant fold and DCE instructions as we go, to avoid adding
13074/// them to the worklist (this significantly speeds up instcombine on code where
13075/// many instructions are dead or constant). Additionally, if we find a branch
13076/// whose condition is a known constant, we only visit the reachable successors.
13077///
Chris Lattnerc4269e52009-10-15 04:59:28 +000013078static bool AddReachableCodeToWorklist(BasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013079 SmallPtrSet<BasicBlock*, 64> &Visited,
13080 InstCombiner &IC,
13081 const TargetData *TD) {
Chris Lattnerc4269e52009-10-15 04:59:28 +000013082 bool MadeIRChange = false;
Chris Lattnera06291a2008-08-15 04:03:01 +000013083 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013084 Worklist.push_back(BB);
Chris Lattnerb5663c72009-10-12 03:58:40 +000013085
13086 std::vector<Instruction*> InstrsForInstCombineWorklist;
13087 InstrsForInstCombineWorklist.reserve(128);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013088
Chris Lattnerc4269e52009-10-15 04:59:28 +000013089 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13090
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013091 while (!Worklist.empty()) {
13092 BB = Worklist.back();
13093 Worklist.pop_back();
13094
13095 // We have now visited this block! If we've already been here, ignore it.
13096 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000013097
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013098 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13099 Instruction *Inst = BBI++;
13100
13101 // DCE instruction if trivially dead.
13102 if (isInstructionTriviallyDead(Inst)) {
13103 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +000013104 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013105 Inst->eraseFromParent();
13106 continue;
13107 }
13108
13109 // ConstantProp instruction if trivially constant.
Chris Lattneree5839b2009-10-15 04:13:44 +000013110 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +000013111 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +000013112 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13113 << *Inst << '\n');
13114 Inst->replaceAllUsesWith(C);
13115 ++NumConstProp;
13116 Inst->eraseFromParent();
13117 continue;
13118 }
Chris Lattnerc4269e52009-10-15 04:59:28 +000013119
13120
13121
13122 if (TD) {
13123 // See if we can constant fold its operands.
13124 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13125 i != e; ++i) {
13126 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13127 if (CE == 0) continue;
13128
13129 // If we already folded this constant, don't try again.
13130 if (!FoldedConstants.insert(CE))
13131 continue;
13132
Chris Lattner6070c012009-11-06 04:27:31 +000013133 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattnerc4269e52009-10-15 04:59:28 +000013134 if (NewC && NewC != CE) {
13135 *i = NewC;
13136 MadeIRChange = true;
13137 }
13138 }
13139 }
13140
Devang Patel794140c2008-11-19 18:56:50 +000013141
Chris Lattnerb5663c72009-10-12 03:58:40 +000013142 InstrsForInstCombineWorklist.push_back(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013143 }
13144
13145 // Recursively visit successors. If this is a branch or switch on a
13146 // constant, only visit the reachable successor.
13147 TerminatorInst *TI = BB->getTerminator();
13148 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13149 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13150 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000013151 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000013152 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013153 continue;
13154 }
13155 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13156 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13157 // See if this is an explicit destination.
13158 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13159 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000013160 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000013161 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013162 continue;
13163 }
13164
13165 // Otherwise it is the default destination.
13166 Worklist.push_back(SI->getSuccessor(0));
13167 continue;
13168 }
13169 }
13170
13171 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13172 Worklist.push_back(TI->getSuccessor(i));
13173 }
Chris Lattnerb5663c72009-10-12 03:58:40 +000013174
13175 // Once we've found all of the instructions to add to instcombine's worklist,
13176 // add them in reverse order. This way instcombine will visit from the top
13177 // of the function down. This jives well with the way that it adds all uses
13178 // of instructions to the worklist after doing a transformation, thus avoiding
13179 // some N^2 behavior in pathological cases.
13180 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13181 InstrsForInstCombineWorklist.size());
Chris Lattnerc4269e52009-10-15 04:59:28 +000013182
13183 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013184}
13185
13186bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner21d79e22009-08-31 06:57:37 +000013187 MadeIRChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013188
Daniel Dunbar005975c2009-07-25 00:23:56 +000013189 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13190 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013191
13192 {
13193 // Do a depth-first traversal of the function, populate the worklist with
13194 // the reachable instructions. Ignore blocks that are not reachable. Keep
13195 // track of which blocks we visit.
13196 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerc4269e52009-10-15 04:59:28 +000013197 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013198
13199 // Do a quick scan over the function. If we find any blocks that are
13200 // unreachable, remove any instructions inside of them. This prevents
13201 // the instcombine code from having to deal with some bad special cases.
13202 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13203 if (!Visited.count(BB)) {
13204 Instruction *Term = BB->getTerminator();
13205 while (Term != BB->begin()) { // Remove instrs bottom-up
13206 BasicBlock::iterator I = Term; --I;
13207
Chris Lattner8a6411c2009-08-23 04:37:46 +000013208 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +000013209 // A debug intrinsic shouldn't force another iteration if we weren't
13210 // going to do one without it.
13211 if (!isa<DbgInfoIntrinsic>(I)) {
13212 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000013213 MadeIRChange = true;
Dale Johannesendf356c62009-03-10 21:19:49 +000013214 }
Devang Patele3829c82009-10-13 22:56:32 +000013215
Devang Patele3829c82009-10-13 22:56:32 +000013216 // If I is not void type then replaceAllUsesWith undef.
13217 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000013218 if (!I->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000013219 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013220 I->eraseFromParent();
13221 }
13222 }
13223 }
13224
Chris Lattner5119c702009-08-30 05:55:36 +000013225 while (!Worklist.isEmpty()) {
13226 Instruction *I = Worklist.RemoveOne();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013227 if (I == 0) continue; // skip null values.
13228
13229 // Check to see if we can DCE the instruction.
13230 if (isInstructionTriviallyDead(I)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000013231 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner3183fb62009-08-30 06:13:40 +000013232 EraseInstFromFunction(*I);
13233 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000013234 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013235 continue;
13236 }
13237
13238 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattneree5839b2009-10-15 04:13:44 +000013239 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +000013240 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +000013241 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013242
Chris Lattneree5839b2009-10-15 04:13:44 +000013243 // Add operands to the worklist.
13244 ReplaceInstUsesWith(*I, C);
13245 ++NumConstProp;
13246 EraseInstFromFunction(*I);
13247 MadeIRChange = true;
13248 continue;
13249 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013250
13251 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000013252 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013253 BasicBlock *BB = I->getParent();
Chris Lattnerf27a0432009-10-14 15:21:58 +000013254 Instruction *UserInst = cast<Instruction>(I->use_back());
13255 BasicBlock *UserParent;
13256
13257 // Get the block the use occurs in.
13258 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13259 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13260 else
13261 UserParent = UserInst->getParent();
13262
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013263 if (UserParent != BB) {
13264 bool UserIsSuccessor = false;
13265 // See if the user is one of our successors.
13266 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13267 if (*SI == UserParent) {
13268 UserIsSuccessor = true;
13269 break;
13270 }
13271
13272 // If the user is one of our immediate successors, and if that successor
13273 // only has us as a predecessors (we'd have to split the critical edge
13274 // otherwise), we can keep going.
Chris Lattnerf27a0432009-10-14 15:21:58 +000013275 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013276 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattner21d79e22009-08-31 06:57:37 +000013277 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013278 }
13279 }
13280
Chris Lattnerc7694852009-08-30 07:44:24 +000013281 // Now that we have an instruction, try combining it to simplify it.
13282 Builder->SetInsertPoint(I->getParent(), I);
13283
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013284#ifndef NDEBUG
13285 std::string OrigI;
13286#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +000013287 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000013288 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13289
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013290 if (Instruction *Result = visit(*I)) {
13291 ++NumCombined;
13292 // Should we replace the old instruction with a new one?
13293 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000013294 DEBUG(errs() << "IC: Old = " << *I << '\n'
13295 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013296
13297 // Everything uses the new instruction now.
13298 I->replaceAllUsesWith(Result);
13299
13300 // Push the new instruction and any users onto the worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +000013301 Worklist.Add(Result);
Chris Lattner4796b622009-08-30 06:22:51 +000013302 Worklist.AddUsersToWorkList(*Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013303
13304 // Move the name to the new instruction first.
13305 Result->takeName(I);
13306
13307 // Insert the new instruction into the basic block...
13308 BasicBlock *InstParent = I->getParent();
13309 BasicBlock::iterator InsertPos = I;
13310
13311 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13312 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13313 ++InsertPos;
13314
13315 InstParent->getInstList().insert(InsertPos, Result);
13316
Chris Lattner3183fb62009-08-30 06:13:40 +000013317 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013318 } else {
13319#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +000013320 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13321 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013322#endif
13323
13324 // If the instruction was modified, it's possible that it is now dead.
13325 // if so, remove it.
13326 if (isInstructionTriviallyDead(I)) {
Chris Lattner3183fb62009-08-30 06:13:40 +000013327 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013328 } else {
Chris Lattner3183fb62009-08-30 06:13:40 +000013329 Worklist.Add(I);
Chris Lattner4796b622009-08-30 06:22:51 +000013330 Worklist.AddUsersToWorkList(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013331 }
13332 }
Chris Lattner21d79e22009-08-31 06:57:37 +000013333 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013334 }
13335 }
13336
Chris Lattner5119c702009-08-30 05:55:36 +000013337 Worklist.Zap();
Chris Lattner21d79e22009-08-31 06:57:37 +000013338 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013339}
13340
13341
13342bool InstCombiner::runOnFunction(Function &F) {
13343 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000013344 Context = &F.getContext();
Chris Lattneree5839b2009-10-15 04:13:44 +000013345 TD = getAnalysisIfAvailable<TargetData>();
13346
Chris Lattnerc7694852009-08-30 07:44:24 +000013347
13348 /// Builder - This is an IRBuilder that automatically inserts new
13349 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +000013350 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattner002e65d2009-11-06 05:59:53 +000013351 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattnerc7694852009-08-30 07:44:24 +000013352 InstCombineIRInserter(Worklist));
13353 Builder = &TheBuilder;
13354
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013355 bool EverMadeChange = false;
13356
13357 // Iterate while there is work to do.
13358 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000013359 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013360 EverMadeChange = true;
Chris Lattnerc7694852009-08-30 07:44:24 +000013361
13362 Builder = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013363 return EverMadeChange;
13364}
13365
13366FunctionPass *llvm::createInstructionCombiningPass() {
13367 return new InstCombiner();
13368}