blob: c591ef841c0d7fcb9aaed3c0d95a0735c7a0b847 [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
Chris Lattner676c78e2009-01-31 08:15:18 +0000386 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
387 /// based on the demanded bits.
388 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
389 APInt& KnownZero, APInt& KnownOne,
390 unsigned Depth);
391 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000393 unsigned Depth=0);
394
395 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
396 /// SimplifyDemandedBits knows about. See if the instruction has any
397 /// properties that allow us to simplify its operands.
398 bool SimplifyDemandedInstructionBits(Instruction &Inst);
399
Evan Cheng63295ab2009-02-03 10:05:09 +0000400 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
401 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402
Chris Lattnerf7843b72009-09-27 19:57:57 +0000403 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
404 // which has a PHI node as operand #0, see if we can fold the instruction
405 // into the PHI (which is only possible if all operands to the PHI are
406 // constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +0000407 //
408 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
409 // that would normally be unprofitable because they strongly encourage jump
410 // threading.
411 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412
413 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
414 // operator and they all are only used by the PHI, PHI together their
415 // inputs, and do the operation once, to the result of the PHI.
416 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
417 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000418 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner38751f82009-11-01 20:04:24 +0000419 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000420
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421
422 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
423 ConstantInt *AndRHS, BinaryOperator &TheAnd);
424
425 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
426 bool isSub, Instruction &I);
427 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
428 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandezb1687302009-10-23 21:09:37 +0000429 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430 Instruction *MatchBSwap(BinaryOperator &I);
431 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000432 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000433 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000434
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000435
436 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000437
Dan Gohman8fd520a2009-06-15 22:12:54 +0000438 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000439 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000440 unsigned GetOrEnforceKnownAlignment(Value *V,
441 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000442
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443 };
Chris Lattner5119c702009-08-30 05:55:36 +0000444} // end anonymous namespace
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000445
Dan Gohman089efff2008-05-13 00:00:25 +0000446char InstCombiner::ID = 0;
447static RegisterPass<InstCombiner>
448X("instcombine", "Combine redundant instructions");
449
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000450// getComplexity: Assign a complexity or rank value to LLVM Values...
451// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman5d138f92009-08-29 23:39:38 +0000452static unsigned getComplexity(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000453 if (isa<Instruction>(V)) {
Owen Anderson76f49252009-07-13 22:18:28 +0000454 if (BinaryOperator::isNeg(V) ||
455 BinaryOperator::isFNeg(V) ||
Dan Gohman7ce405e2009-06-04 22:49:04 +0000456 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000457 return 3;
458 return 4;
459 }
460 if (isa<Argument>(V)) return 3;
461 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
462}
463
464// isOnlyUse - Return true if this instruction will be deleted if we stop using
465// it.
466static bool isOnlyUse(Value *V) {
467 return V->hasOneUse() || isa<Constant>(V);
468}
469
470// getPromotedType - Return the specified type promoted as it would be to pass
471// though a va_arg area...
472static const Type *getPromotedType(const Type *Ty) {
473 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
474 if (ITy->getBitWidth() < 32)
Owen Anderson35b47072009-08-13 21:58:54 +0000475 return Type::getInt32Ty(Ty->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000476 }
477 return Ty;
478}
479
Chris Lattnerd0011092009-11-10 07:23:37 +0000480/// ShouldChangeType - Return true if it is desirable to convert a computation
481/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
482/// type for example, or from a smaller to a larger illegal type.
483static bool ShouldChangeType(const Type *From, const Type *To,
484 const TargetData *TD) {
485 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
486
487 // If we don't have TD, we don't know if the source/dest are legal.
488 if (!TD) return false;
489
490 unsigned FromWidth = From->getPrimitiveSizeInBits();
491 unsigned ToWidth = To->getPrimitiveSizeInBits();
492 bool FromLegal = TD->isLegalInteger(FromWidth);
493 bool ToLegal = TD->isLegalInteger(ToWidth);
494
495 // If this is a legal integer from type, and the result would be an illegal
496 // type, don't do the transformation.
497 if (FromLegal && !ToLegal)
498 return false;
499
500 // Otherwise, if both are illegal, do not increase the size of the result. We
501 // do allow things like i160 -> i64, but not i64 -> i160.
502 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
503 return false;
504
505 return true;
506}
507
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000508/// getBitCastOperand - If the specified operand is a CastInst, a constant
509/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
510/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000511static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000512 if (Operator *O = dyn_cast<Operator>(V)) {
513 if (O->getOpcode() == Instruction::BitCast)
514 return O->getOperand(0);
515 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
516 if (GEP->hasAllZeroIndices())
517 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000518 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519 return 0;
520}
521
522/// This function is a wrapper around CastInst::isEliminableCastPair. It
523/// simply extracts arguments and returns what that function returns.
524static Instruction::CastOps
525isEliminableCastPair(
526 const CastInst *CI, ///< The first cast instruction
527 unsigned opcode, ///< The opcode of the second cast instruction
528 const Type *DstTy, ///< The target type for the second cast instruction
529 TargetData *TD ///< The target data for pointer size
530) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000531
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
533 const Type *MidTy = CI->getType(); // B from above
534
535 // Get the opcodes of the two Cast instructions
536 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
537 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
538
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000539 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmana80e2712009-07-21 23:21:54 +0000540 DstTy,
Owen Anderson35b47072009-08-13 21:58:54 +0000541 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000542
543 // We don't want to form an inttoptr or ptrtoint that converts to an integer
544 // type that differs from the pointer size.
Owen Anderson35b47072009-08-13 21:58:54 +0000545 if ((Res == Instruction::IntToPtr &&
Dan Gohman033445f2009-08-19 23:38:22 +0000546 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson35b47072009-08-13 21:58:54 +0000547 (Res == Instruction::PtrToInt &&
Dan Gohman033445f2009-08-19 23:38:22 +0000548 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000549 Res = 0;
550
551 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000552}
553
554/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
555/// in any code being generated. It does not require codegen if V is simple
556/// enough or if the cast can be folded into other casts.
557static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
558 const Type *Ty, TargetData *TD) {
559 if (V->getType() == Ty || isa<Constant>(V)) return false;
560
561 // If this is another cast that can be eliminated, it isn't codegen either.
562 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000563 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564 return false;
565 return true;
566}
567
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000568// SimplifyCommutative - This performs a few simplifications for commutative
569// operators:
570//
571// 1. Order operands such that they are listed from right (least complex) to
572// left (most complex). This puts constants before unary operators before
573// binary operators.
574//
575// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
576// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
577//
578bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
579 bool Changed = false;
Dan Gohman5d138f92009-08-29 23:39:38 +0000580 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000581 Changed = !I.swapOperands();
582
583 if (!I.isAssociative()) return Changed;
584 Instruction::BinaryOps Opcode = I.getOpcode();
585 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
586 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
587 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000588 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000589 cast<Constant>(I.getOperand(1)),
590 cast<Constant>(Op->getOperand(1)));
591 I.setOperand(0, Op->getOperand(0));
592 I.setOperand(1, Folded);
593 return true;
594 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
595 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
596 isOnlyUse(Op) && isOnlyUse(Op1)) {
597 Constant *C1 = cast<Constant>(Op->getOperand(1));
598 Constant *C2 = cast<Constant>(Op1->getOperand(1));
599
600 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000601 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000602 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603 Op1->getOperand(0),
604 Op1->getName(), &I);
Chris Lattner3183fb62009-08-30 06:13:40 +0000605 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 I.setOperand(0, New);
607 I.setOperand(1, Folded);
608 return true;
609 }
610 }
611 return Changed;
612}
613
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
615// if the LHS is a constant zero (which is the 'negate' form).
616//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000617static inline Value *dyn_castNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000618 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619 return BinaryOperator::getNegArgument(V);
620
621 // Constants can be considered to be negated values if they can be folded.
622 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000623 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000624
625 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
626 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000627 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000628
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629 return 0;
630}
631
Dan Gohman7ce405e2009-06-04 22:49:04 +0000632// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
633// instruction if the LHS is a constant negative zero (which is the 'negate'
634// form).
635//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000636static inline Value *dyn_castFNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000637 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000638 return BinaryOperator::getFNegArgument(V);
639
640 // Constants can be considered to be negated values if they can be folded.
641 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000642 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000643
644 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
645 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000646 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000647
648 return 0;
649}
650
Chris Lattner6e060db2009-10-26 15:40:07 +0000651/// isFreeToInvert - Return true if the specified value is free to invert (apply
652/// ~ to). This happens in cases where the ~ can be eliminated.
653static inline bool isFreeToInvert(Value *V) {
654 // ~(~(X)) -> X.
Evan Cheng5d4a07e2009-10-26 03:51:32 +0000655 if (BinaryOperator::isNot(V))
Chris Lattner6e060db2009-10-26 15:40:07 +0000656 return true;
657
658 // Constants can be considered to be not'ed values.
659 if (isa<ConstantInt>(V))
660 return true;
661
662 // Compares can be inverted if they have a single use.
663 if (CmpInst *CI = dyn_cast<CmpInst>(V))
664 return CI->hasOneUse();
665
666 return false;
667}
668
669static inline Value *dyn_castNotVal(Value *V) {
670 // If this is not(not(x)) don't return that this is a not: we want the two
671 // not's to be folded first.
672 if (BinaryOperator::isNot(V)) {
673 Value *Operand = BinaryOperator::getNotArgument(V);
674 if (!isFreeToInvert(Operand))
675 return Operand;
676 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677
678 // Constants can be considered to be not'ed values...
679 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000680 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681 return 0;
682}
683
Chris Lattner6e060db2009-10-26 15:40:07 +0000684
685
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686// dyn_castFoldableMul - If this value is a multiply that can be folded into
687// other computations (because it has a constant operand), return the
688// non-constant operand of the multiply, and set CST to point to the multiplier.
689// Otherwise, return null.
690//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000691static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692 if (V->hasOneUse() && V->getType()->isInteger())
693 if (Instruction *I = dyn_cast<Instruction>(V)) {
694 if (I->getOpcode() == Instruction::Mul)
695 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
696 return I->getOperand(0);
697 if (I->getOpcode() == Instruction::Shl)
698 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
699 // The multiplier is really 1 << CST.
700 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
701 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000702 CST = ConstantInt::get(V->getType()->getContext(),
703 APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704 return I->getOperand(0);
705 }
706 }
707 return 0;
708}
709
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000710/// AddOne - Add one to a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000711static Constant *AddOne(Constant *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000712 return ConstantExpr::getAdd(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000713 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714}
715/// SubOne - Subtract one from a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000716static Constant *SubOne(ConstantInt *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000717 return ConstantExpr::getSub(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000718 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000719}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000720/// MultiplyOverflows - True if the multiply can not be expressed in an int
721/// this size.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000722static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000723 uint32_t W = C1->getBitWidth();
724 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
725 if (sign) {
726 LHSExt.sext(W * 2);
727 RHSExt.sext(W * 2);
728 } else {
729 LHSExt.zext(W * 2);
730 RHSExt.zext(W * 2);
731 }
732
733 APInt MulExt = LHSExt * RHSExt;
734
735 if (sign) {
736 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
737 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
738 return MulExt.slt(Min) || MulExt.sgt(Max);
739 } else
740 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
741}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000742
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000743
744/// ShrinkDemandedConstant - Check to see if the specified operand of the
745/// specified instruction is a constant integer. If so, check to see if there
746/// are any bits set in the constant that are not demanded. If so, shrink the
747/// constant and return true.
748static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000749 APInt Demanded) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000750 assert(I && "No instruction?");
751 assert(OpNo < I->getNumOperands() && "Operand index too large");
752
753 // If the operand is not a constant integer, nothing to do.
754 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
755 if (!OpC) return false;
756
757 // If there are no bits set that aren't demanded, nothing to do.
758 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
759 if ((~Demanded & OpC->getValue()) == 0)
760 return false;
761
762 // This instruction is producing bits that are not demanded. Shrink the RHS.
763 Demanded &= OpC->getValue();
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000764 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000765 return true;
766}
767
768// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
769// set of known zero and one bits, compute the maximum and minimum values that
770// could have the specified known zero and known one bits, returning them in
771// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000772static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773 const APInt& KnownOne,
774 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000775 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
776 KnownZero.getBitWidth() == Min.getBitWidth() &&
777 KnownZero.getBitWidth() == Max.getBitWidth() &&
778 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000779 APInt UnknownBits = ~(KnownZero|KnownOne);
780
781 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
782 // bit if it is unknown.
783 Min = KnownOne;
784 Max = KnownOne|UnknownBits;
785
Dan Gohman7934d592009-04-25 17:12:48 +0000786 if (UnknownBits.isNegative()) { // Sign bit is unknown
787 Min.set(Min.getBitWidth()-1);
788 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000789 }
790}
791
792// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
793// a set of known zero and one bits, compute the maximum and minimum values that
794// could have the specified known zero and known one bits, returning them in
795// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000796static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000797 const APInt &KnownOne,
798 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000799 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
800 KnownZero.getBitWidth() == Min.getBitWidth() &&
801 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000802 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
803 APInt UnknownBits = ~(KnownZero|KnownOne);
804
805 // The minimum value is when the unknown bits are all zeros.
806 Min = KnownOne;
807 // The maximum value is when the unknown bits are all ones.
808 Max = KnownOne|UnknownBits;
809}
810
Chris Lattner676c78e2009-01-31 08:15:18 +0000811/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
812/// SimplifyDemandedBits knows about. See if the instruction has any
813/// properties that allow us to simplify its operands.
814bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000815 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000816 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
817 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
818
819 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
820 KnownZero, KnownOne, 0);
821 if (V == 0) return false;
822 if (V == &Inst) return true;
823 ReplaceInstUsesWith(Inst, V);
824 return true;
825}
826
827/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
828/// specified instruction operand if possible, updating it in place. It returns
829/// true if it made any change and false otherwise.
830bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
831 APInt &KnownZero, APInt &KnownOne,
832 unsigned Depth) {
833 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
834 KnownZero, KnownOne, Depth);
835 if (NewVal == 0) return false;
Dan Gohman3af2d412009-10-05 16:31:55 +0000836 U = NewVal;
Chris Lattner676c78e2009-01-31 08:15:18 +0000837 return true;
838}
839
840
841/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
842/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000843/// that only the bits set in DemandedMask of the result of V are ever used
844/// downstream. Consequently, depending on the mask and V, it may be possible
845/// to replace V with a constant or one of its operands. In such cases, this
846/// function does the replacement and returns true. In all other cases, it
847/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000848/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849/// to be zero in the expression. These are provided to potentially allow the
850/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
851/// the expression. KnownOne and KnownZero always follow the invariant that
852/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
853/// the bits in KnownOne and KnownZero may only be accurate for those bits set
854/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
855/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000856///
857/// This returns null if it did not change anything and it permits no
858/// simplification. This returns V itself if it did some simplification of V's
859/// operands based on the information about what bits are demanded. This returns
860/// some other non-null value if it found out that V is equal to another value
861/// in the context where the specified bits are demanded, but not for all users.
862Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
863 APInt &KnownZero, APInt &KnownOne,
864 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 assert(V != 0 && "Null pointer of Value???");
866 assert(Depth <= 6 && "Limit Search Depth");
867 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000868 const Type *VTy = V->getType();
869 assert((TD || !isa<PointerType>(VTy)) &&
870 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000871 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
872 (!VTy->isIntOrIntVector() ||
873 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000874 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000876 "Value *V, DemandedMask, KnownZero and KnownOne "
877 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000878 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
879 // We know all of the bits for a constant!
880 KnownOne = CI->getValue() & DemandedMask;
881 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000882 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000883 }
Dan Gohman7934d592009-04-25 17:12:48 +0000884 if (isa<ConstantPointerNull>(V)) {
885 // We know all of the bits for a constant!
886 KnownOne.clear();
887 KnownZero = DemandedMask;
888 return 0;
889 }
890
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000891 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000893 if (DemandedMask == 0) { // Not demanding any bits from V.
894 if (isa<UndefValue>(V))
895 return 0;
Owen Andersonb99ecca2009-07-30 23:03:37 +0000896 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 }
898
Chris Lattner08817332009-01-31 08:24:16 +0000899 if (Depth == 6) // Limit search depth.
900 return 0;
901
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000902 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
903 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
904
Dan Gohman7934d592009-04-25 17:12:48 +0000905 Instruction *I = dyn_cast<Instruction>(V);
906 if (!I) {
907 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
908 return 0; // Only analyze instructions.
909 }
910
Chris Lattner08817332009-01-31 08:24:16 +0000911 // If there are multiple uses of this value and we aren't at the root, then
912 // we can't do any simplifications of the operands, because DemandedMask
913 // only reflects the bits demanded by *one* of the users.
914 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000915 // Despite the fact that we can't simplify this instruction in all User's
916 // context, we can at least compute the knownzero/knownone bits, and we can
917 // do simplifications that apply to *just* the one user if we know that
918 // this instruction has a simpler value in that context.
919 if (I->getOpcode() == Instruction::And) {
920 // If either the LHS or the RHS are Zero, the result is zero.
921 ComputeMaskedBits(I->getOperand(1), DemandedMask,
922 RHSKnownZero, RHSKnownOne, Depth+1);
923 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
924 LHSKnownZero, LHSKnownOne, Depth+1);
925
926 // If all of the demanded bits are known 1 on one side, return the other.
927 // These bits cannot contribute to the result of the 'and' in this
928 // context.
929 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
930 (DemandedMask & ~LHSKnownZero))
931 return I->getOperand(0);
932 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
933 (DemandedMask & ~RHSKnownZero))
934 return I->getOperand(1);
935
936 // If all of the demanded bits in the inputs are known zeros, return zero.
937 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000938 return Constant::getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000939
940 } else if (I->getOpcode() == Instruction::Or) {
941 // We can simplify (X|Y) -> X or Y in the user's context if we know that
942 // only bits from X or Y are demanded.
943
944 // If either the LHS or the RHS are One, the result is One.
945 ComputeMaskedBits(I->getOperand(1), DemandedMask,
946 RHSKnownZero, RHSKnownOne, Depth+1);
947 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
948 LHSKnownZero, LHSKnownOne, Depth+1);
949
950 // If all of the demanded bits are known zero on one side, return the
951 // other. These bits cannot contribute to the result of the 'or' in this
952 // context.
953 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
954 (DemandedMask & ~LHSKnownOne))
955 return I->getOperand(0);
956 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
957 (DemandedMask & ~RHSKnownOne))
958 return I->getOperand(1);
959
960 // If all of the potentially set bits on one side are known to be set on
961 // the other side, just use the 'other' side.
962 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
963 (DemandedMask & (~RHSKnownZero)))
964 return I->getOperand(0);
965 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
966 (DemandedMask & (~LHSKnownZero)))
967 return I->getOperand(1);
968 }
969
Chris Lattner08817332009-01-31 08:24:16 +0000970 // Compute the KnownZero/KnownOne bits to simplify things downstream.
971 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
972 return 0;
973 }
974
975 // If this is the root being simplified, allow it to have multiple uses,
976 // just set the DemandedMask to all bits so that we can try to simplify the
977 // operands. This allows visitTruncInst (for example) to simplify the
978 // operand of a trunc without duplicating all the logic below.
979 if (Depth == 0 && !V->hasOneUse())
980 DemandedMask = APInt::getAllOnesValue(BitWidth);
981
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000983 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000984 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000985 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 case Instruction::And:
987 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000988 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
989 RHSKnownZero, RHSKnownOne, Depth+1) ||
990 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000992 return I;
993 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
994 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000995
996 // If all of the demanded bits are known 1 on one side, return the other.
997 // These bits cannot contribute to the result of the 'and'.
998 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
999 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +00001000 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001001 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1002 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +00001003 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001004
1005 // If all of the demanded bits in the inputs are known zeros, return zero.
1006 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +00001007 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001008
1009 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001010 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +00001011 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012
1013 // Output known-1 bits are only known if set in both the LHS & RHS.
1014 RHSKnownOne &= LHSKnownOne;
1015 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1016 RHSKnownZero |= LHSKnownZero;
1017 break;
1018 case Instruction::Or:
1019 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +00001020 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1021 RHSKnownZero, RHSKnownOne, Depth+1) ||
1022 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001023 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001024 return I;
1025 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1026 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001027
1028 // If all of the demanded bits are known zero on one side, return the other.
1029 // These bits cannot contribute to the result of the 'or'.
1030 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1031 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +00001032 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001033 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1034 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +00001035 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001036
1037 // If all of the potentially set bits on one side are known to be set on
1038 // the other side, just use the 'other' side.
1039 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1040 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +00001041 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001042 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1043 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +00001044 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045
1046 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001047 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001048 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001049
1050 // Output known-0 bits are only known if clear in both the LHS & RHS.
1051 RHSKnownZero &= LHSKnownZero;
1052 // Output known-1 are known to be set if set in either the LHS | RHS.
1053 RHSKnownOne |= LHSKnownOne;
1054 break;
1055 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +00001056 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1057 RHSKnownZero, RHSKnownOne, Depth+1) ||
1058 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001060 return I;
1061 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1062 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001063
1064 // If all of the demanded bits are known zero on one side, return the other.
1065 // These bits cannot contribute to the result of the 'xor'.
1066 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001067 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001068 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001069 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070
1071 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1072 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1073 (RHSKnownOne & LHSKnownOne);
1074 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1075 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1076 (RHSKnownOne & LHSKnownZero);
1077
1078 // If all of the demanded bits are known to be zero on one side or the
1079 // other, turn this into an *inclusive* or.
1080 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneradba7ea2009-08-31 04:36:22 +00001081 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1082 Instruction *Or =
1083 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1084 I->getName());
1085 return InsertNewInstBefore(Or, *I);
1086 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087
1088 // If all of the demanded bits on one side are known, and all of the set
1089 // bits on that side are also known to be set on the other side, turn this
1090 // into an AND, as we know the bits will be cleared.
1091 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1092 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1093 // all known
1094 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohmancf2c9982009-08-03 22:07:33 +00001095 Constant *AndC = Constant::getIntegerValue(VTy,
1096 ~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001098 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001099 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100 }
1101 }
1102
1103 // If the RHS is a constant, see if we can simplify it.
1104 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001105 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001106 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001107
Chris Lattnereefa89c2009-10-11 22:22:13 +00001108 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1109 // are flipping are known to be set, then the xor is just resetting those
1110 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1111 // simplifying both of them.
1112 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1113 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1114 isa<ConstantInt>(I->getOperand(1)) &&
1115 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1116 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1117 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1118 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1119 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1120
1121 Constant *AndC =
1122 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1123 Instruction *NewAnd =
1124 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1125 InsertNewInstBefore(NewAnd, *I);
1126
1127 Constant *XorC =
1128 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1129 Instruction *NewXor =
1130 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1131 return InsertNewInstBefore(NewXor, *I);
1132 }
1133
1134
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 RHSKnownZero = KnownZeroOut;
1136 RHSKnownOne = KnownOneOut;
1137 break;
1138 }
1139 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001140 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1141 RHSKnownZero, RHSKnownOne, Depth+1) ||
1142 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001144 return I;
1145 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1146 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001147
1148 // If the operands are constants, see if we can simplify them.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001149 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1150 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001151 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001152
1153 // Only known if known in both the LHS and RHS.
1154 RHSKnownOne &= LHSKnownOne;
1155 RHSKnownZero &= LHSKnownZero;
1156 break;
1157 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001158 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001159 DemandedMask.zext(truncBf);
1160 RHSKnownZero.zext(truncBf);
1161 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001162 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001164 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165 DemandedMask.trunc(BitWidth);
1166 RHSKnownZero.trunc(BitWidth);
1167 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001168 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001169 break;
1170 }
1171 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001172 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001173 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001174
1175 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1176 if (const VectorType *SrcVTy =
1177 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1178 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1179 // Don't touch a bitcast between vectors of different element counts.
1180 return false;
1181 } else
1182 // Don't touch a scalar-to-vector bitcast.
1183 return false;
1184 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1185 // Don't touch a vector-to-scalar bitcast.
1186 return false;
1187
Chris Lattner676c78e2009-01-31 08:15:18 +00001188 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001189 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001190 return I;
1191 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001192 break;
1193 case Instruction::ZExt: {
1194 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001195 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001196
1197 DemandedMask.trunc(SrcBitWidth);
1198 RHSKnownZero.trunc(SrcBitWidth);
1199 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001200 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001202 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001203 DemandedMask.zext(BitWidth);
1204 RHSKnownZero.zext(BitWidth);
1205 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001206 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001207 // The top bits are known to be zero.
1208 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1209 break;
1210 }
1211 case Instruction::SExt: {
1212 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001213 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214
1215 APInt InputDemandedBits = DemandedMask &
1216 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1217
1218 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1219 // If any of the sign extended bits are demanded, we know that the sign
1220 // bit is demanded.
1221 if ((NewBits & DemandedMask) != 0)
1222 InputDemandedBits.set(SrcBitWidth-1);
1223
1224 InputDemandedBits.trunc(SrcBitWidth);
1225 RHSKnownZero.trunc(SrcBitWidth);
1226 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001227 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001228 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001229 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001230 InputDemandedBits.zext(BitWidth);
1231 RHSKnownZero.zext(BitWidth);
1232 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001233 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001234
1235 // If the sign bit of the input is known set or clear, then we know the
1236 // top bits of the result.
1237
1238 // If the input sign bit is known zero, or if the NewBits are not demanded
1239 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001240 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001241 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001242 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1243 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001244 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1245 RHSKnownOne |= NewBits;
1246 }
1247 break;
1248 }
1249 case Instruction::Add: {
1250 // Figure out what the input bits are. If the top bits of the and result
1251 // are not demanded, then the add doesn't demand them from its input
1252 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001253 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254
1255 // If there is a constant on the RHS, there are a variety of xformations
1256 // we can do.
1257 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1258 // If null, this should be simplified elsewhere. Some of the xforms here
1259 // won't work if the RHS is zero.
1260 if (RHS->isZero())
1261 break;
1262
1263 // If the top bit of the output is demanded, demand everything from the
1264 // input. Otherwise, we demand all the input bits except NLZ top bits.
1265 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1266
1267 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001268 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001270 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001271
1272 // If the RHS of the add has bits set that can't affect the input, reduce
1273 // the constant.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001274 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001275 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001276
1277 // Avoid excess work.
1278 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1279 break;
1280
1281 // Turn it into OR if input bits are zero.
1282 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1283 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001284 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001286 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001287 }
1288
1289 // We can say something about the output known-zero and known-one bits,
1290 // depending on potential carries from the input constant and the
1291 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1292 // bits set and the RHS constant is 0x01001, then we know we have a known
1293 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1294
1295 // To compute this, we first compute the potential carry bits. These are
1296 // the bits which may be modified. I'm not aware of a better way to do
1297 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001298 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001299 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1300
1301 // Now that we know which bits have carries, compute the known-1/0 sets.
1302
1303 // Bits are known one if they are known zero in one operand and one in the
1304 // other, and there is no input carry.
1305 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1306 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1307
1308 // Bits are known zero if they are known zero in both operands and there
1309 // is no input carry.
1310 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1311 } else {
1312 // If the high-bits of this ADD are not demanded, then it does not demand
1313 // the high bits of its LHS or RHS.
1314 if (DemandedMask[BitWidth-1] == 0) {
1315 // Right fill the mask of bits for this ADD to demand the most
1316 // significant bit and all those below it.
1317 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001318 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1319 LHSKnownZero, LHSKnownOne, Depth+1) ||
1320 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001322 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323 }
1324 }
1325 break;
1326 }
1327 case Instruction::Sub:
1328 // If the high-bits of this SUB are not demanded, then it does not demand
1329 // the high bits of its LHS or RHS.
1330 if (DemandedMask[BitWidth-1] == 0) {
1331 // Right fill the mask of bits for this SUB to demand the most
1332 // significant bit and all those below it.
1333 uint32_t NLZ = DemandedMask.countLeadingZeros();
1334 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001335 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1336 LHSKnownZero, LHSKnownOne, Depth+1) ||
1337 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001338 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001339 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001341 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1342 // the known zeros and ones.
1343 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344 break;
1345 case Instruction::Shl:
1346 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1347 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1348 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001349 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001350 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001351 return I;
1352 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001353 RHSKnownZero <<= ShiftAmt;
1354 RHSKnownOne <<= ShiftAmt;
1355 // low bits known zero.
1356 if (ShiftAmt)
1357 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1358 }
1359 break;
1360 case Instruction::LShr:
1361 // For a logical shift right
1362 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1363 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1364
1365 // Unsigned shift right.
1366 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001367 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001368 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001369 return I;
1370 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1372 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1373 if (ShiftAmt) {
1374 // Compute the new bits that are at the top now.
1375 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1376 RHSKnownZero |= HighBits; // high bits known zero.
1377 }
1378 }
1379 break;
1380 case Instruction::AShr:
1381 // If this is an arithmetic shift right and only the low-bit is set, we can
1382 // always convert this into a logical shr, even if the shift amount is
1383 // variable. The low bit of the shift cannot be an input sign bit unless
1384 // the shift amount is >= the size of the datatype, which is undefined.
1385 if (DemandedMask == 1) {
1386 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001387 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001389 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001390 }
1391
1392 // If the sign bit is the only bit demanded by this ashr, then there is no
1393 // need to do it, the shift doesn't change the high bit.
1394 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001395 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001396
1397 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1398 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1399
1400 // Signed shift right.
1401 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1402 // If any of the "high bits" are demanded, we should set the sign bit as
1403 // demanded.
1404 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1405 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001406 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001407 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001408 return I;
1409 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001410 // Compute the new bits that are at the top now.
1411 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1412 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1413 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1414
1415 // Handle the sign bits.
1416 APInt SignBit(APInt::getSignBit(BitWidth));
1417 // Adjust to where it is now in the mask.
1418 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1419
1420 // If the input sign bit is known to be zero, or if none of the top bits
1421 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001422 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001423 (HighBits & ~DemandedMask) == HighBits) {
1424 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001425 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001426 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001427 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001428 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1429 RHSKnownOne |= HighBits;
1430 }
1431 }
1432 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001433 case Instruction::SRem:
1434 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001435 APInt RA = Rem->getValue().abs();
1436 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001437 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001438 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001439
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001440 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001441 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001442 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001443 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001444 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001445
1446 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1447 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001448
1449 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001450
Chris Lattner676c78e2009-01-31 08:15:18 +00001451 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001452 }
1453 }
1454 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001455 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001456 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1457 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001458 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1459 KnownZero2, KnownOne2, Depth+1) ||
1460 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001461 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001462 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001463
Chris Lattneree5417c2009-01-21 18:09:24 +00001464 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001465 Leaders = std::max(Leaders,
1466 KnownZero2.countLeadingOnes());
1467 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001468 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001469 }
Chris Lattner989ba312008-06-18 04:33:20 +00001470 case Instruction::Call:
1471 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1472 switch (II->getIntrinsicID()) {
1473 default: break;
1474 case Intrinsic::bswap: {
1475 // If the only bits demanded come from one byte of the bswap result,
1476 // just shift the input byte into position to eliminate the bswap.
1477 unsigned NLZ = DemandedMask.countLeadingZeros();
1478 unsigned NTZ = DemandedMask.countTrailingZeros();
1479
1480 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1481 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1482 // have 14 leading zeros, round to 8.
1483 NLZ &= ~7;
1484 NTZ &= ~7;
1485 // If we need exactly one byte, we can do this transformation.
1486 if (BitWidth-NLZ-NTZ == 8) {
1487 unsigned ResultBit = NTZ;
1488 unsigned InputBit = BitWidth-NTZ-8;
1489
1490 // Replace this with either a left or right shift to get the byte into
1491 // the right place.
1492 Instruction *NewVal;
1493 if (InputBit > ResultBit)
1494 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001495 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001496 else
1497 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001498 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001499 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001500 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001501 }
1502
1503 // TODO: Could compute known zero/one bits based on the input.
1504 break;
1505 }
1506 }
1507 }
Chris Lattner4946e222008-06-18 18:11:55 +00001508 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001509 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001510 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001511
1512 // If the client is only demanding bits that we know, return the known
1513 // constant.
Dan Gohmancf2c9982009-08-03 22:07:33 +00001514 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1515 return Constant::getIntegerValue(VTy, RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001516 return false;
1517}
1518
1519
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001520/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001521/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001522/// actually used by the caller. This method analyzes which elements of the
1523/// operand are undef and returns that information in UndefElts.
1524///
1525/// If the information about demanded elements can be used to simplify the
1526/// operation, the operation is simplified, then the resultant value is
1527/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001528Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1529 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001530 unsigned Depth) {
1531 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001532 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001533 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001534
1535 if (isa<UndefValue>(V)) {
1536 // If the entire vector is undefined, just return this info.
1537 UndefElts = EltMask;
1538 return 0;
1539 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1540 UndefElts = EltMask;
Owen Andersonb99ecca2009-07-30 23:03:37 +00001541 return UndefValue::get(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001542 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001543
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001544 UndefElts = 0;
1545 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1546 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb99ecca2009-07-30 23:03:37 +00001547 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001548
1549 std::vector<Constant*> Elts;
1550 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001551 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001552 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001553 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001554 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1555 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001556 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001557 } else { // Otherwise, defined.
1558 Elts.push_back(CP->getOperand(i));
1559 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001560
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001561 // If we changed the constant, return it.
Owen Anderson2f422e02009-07-28 21:19:26 +00001562 Constant *NewCP = ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001563 return NewCP != CP ? NewCP : 0;
1564 } else if (isa<ConstantAggregateZero>(V)) {
1565 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1566 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001567
1568 // Check if this is identity. If so, return 0 since we are not simplifying
1569 // anything.
1570 if (DemandedElts == ((1ULL << VWidth) -1))
1571 return 0;
1572
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001573 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonaac28372009-07-31 20:28:14 +00001574 Constant *Zero = Constant::getNullValue(EltTy);
Owen Andersonb99ecca2009-07-30 23:03:37 +00001575 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001576 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001577 for (unsigned i = 0; i != VWidth; ++i) {
1578 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1579 Elts.push_back(Elt);
1580 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001581 UndefElts = DemandedElts ^ EltMask;
Owen Anderson2f422e02009-07-28 21:19:26 +00001582 return ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001583 }
1584
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001585 // Limit search depth.
1586 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001587 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001588
1589 // If multiple users are using the root value, procede with
1590 // simplification conservatively assuming that all elements
1591 // are needed.
1592 if (!V->hasOneUse()) {
1593 // Quit if we find multiple users of a non-root value though.
1594 // They'll be handled when it's their turn to be visited by
1595 // the main instcombine process.
1596 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001597 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001598 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001599
1600 // Conservatively assume that all elements are needed.
1601 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001602 }
1603
1604 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001605 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001606
1607 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001608 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001609 Value *TmpV;
1610 switch (I->getOpcode()) {
1611 default: break;
1612
1613 case Instruction::InsertElement: {
1614 // If this is a variable index, we don't know which element it overwrites.
1615 // demand exactly the same input as we produce.
1616 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1617 if (Idx == 0) {
1618 // Note that we can't propagate undef elt info, because we don't know
1619 // which elt is getting updated.
1620 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1621 UndefElts2, Depth+1);
1622 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1623 break;
1624 }
1625
1626 // If this is inserting an element that isn't demanded, remove this
1627 // insertelement.
1628 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner059cfc72009-08-30 06:20:05 +00001629 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1630 Worklist.Add(I);
1631 return I->getOperand(0);
1632 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001633
1634 // Otherwise, the element inserted overwrites whatever was there, so the
1635 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001636 APInt DemandedElts2 = DemandedElts;
1637 DemandedElts2.clear(IdxNo);
1638 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001639 UndefElts, Depth+1);
1640 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1641
1642 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001643 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001644 break;
1645 }
1646 case Instruction::ShuffleVector: {
1647 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001648 uint64_t LHSVWidth =
1649 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001650 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001651 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001652 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001653 unsigned MaskVal = Shuffle->getMaskValue(i);
1654 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001655 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001656 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001657 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001658 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001659 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001660 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001661 }
1662 }
1663 }
1664
Nate Begemanb4d176f2009-02-11 22:36:25 +00001665 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001666 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001667 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001668 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1669
Nate Begemanb4d176f2009-02-11 22:36:25 +00001670 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001671 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1672 UndefElts3, Depth+1);
1673 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1674
1675 bool NewUndefElts = false;
1676 for (unsigned i = 0; i < VWidth; i++) {
1677 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001678 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001679 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001680 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001681 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001682 NewUndefElts = true;
1683 UndefElts.set(i);
1684 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001685 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001686 if (UndefElts3[MaskVal - LHSVWidth]) {
1687 NewUndefElts = true;
1688 UndefElts.set(i);
1689 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001690 }
1691 }
1692
1693 if (NewUndefElts) {
1694 // Add additional discovered undefs.
1695 std::vector<Constant*> Elts;
1696 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001697 if (UndefElts[i])
Owen Anderson35b47072009-08-13 21:58:54 +00001698 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001699 else
Owen Anderson35b47072009-08-13 21:58:54 +00001700 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001701 Shuffle->getMaskValue(i)));
1702 }
Owen Anderson2f422e02009-07-28 21:19:26 +00001703 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001704 MadeChange = true;
1705 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001706 break;
1707 }
1708 case Instruction::BitCast: {
1709 // Vector->vector casts only.
1710 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1711 if (!VTy) break;
1712 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001713 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001714 unsigned Ratio;
1715
1716 if (VWidth == InVWidth) {
1717 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1718 // elements as are demanded of us.
1719 Ratio = 1;
1720 InputDemandedElts = DemandedElts;
1721 } else if (VWidth > InVWidth) {
1722 // Untested so far.
1723 break;
1724
1725 // If there are more elements in the result than there are in the source,
1726 // then an input element is live if any of the corresponding output
1727 // elements are live.
1728 Ratio = VWidth/InVWidth;
1729 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001730 if (DemandedElts[OutIdx])
1731 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001732 }
1733 } else {
1734 // Untested so far.
1735 break;
1736
1737 // If there are more elements in the source than there are in the result,
1738 // then an input element is live if the corresponding output element is
1739 // live.
1740 Ratio = InVWidth/VWidth;
1741 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001742 if (DemandedElts[InIdx/Ratio])
1743 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001744 }
1745
1746 // div/rem demand all inputs, because they don't want divide by zero.
1747 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1748 UndefElts2, Depth+1);
1749 if (TmpV) {
1750 I->setOperand(0, TmpV);
1751 MadeChange = true;
1752 }
1753
1754 UndefElts = UndefElts2;
1755 if (VWidth > InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001756 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001757 // If there are more elements in the result than there are in the source,
1758 // then an output element is undef if the corresponding input element is
1759 // undef.
1760 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001761 if (UndefElts2[OutIdx/Ratio])
1762 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001763 } else if (VWidth < InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001764 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001765 // If there are more elements in the source than there are in the result,
1766 // then a result element is undef if all of the corresponding input
1767 // elements are undef.
1768 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1769 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001770 if (!UndefElts2[InIdx]) // Not undef?
1771 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001772 }
1773 break;
1774 }
1775 case Instruction::And:
1776 case Instruction::Or:
1777 case Instruction::Xor:
1778 case Instruction::Add:
1779 case Instruction::Sub:
1780 case Instruction::Mul:
1781 // div/rem demand all inputs, because they don't want divide by zero.
1782 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1783 UndefElts, Depth+1);
1784 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1785 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1786 UndefElts2, Depth+1);
1787 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1788
1789 // Output elements are undefined if both are undefined. Consider things
1790 // like undef&0. The result is known zero, not undef.
1791 UndefElts &= UndefElts2;
1792 break;
1793
1794 case Instruction::Call: {
1795 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1796 if (!II) break;
1797 switch (II->getIntrinsicID()) {
1798 default: break;
1799
1800 // Binary vector operations that work column-wise. A dest element is a
1801 // function of the corresponding input elements from the two inputs.
1802 case Intrinsic::x86_sse_sub_ss:
1803 case Intrinsic::x86_sse_mul_ss:
1804 case Intrinsic::x86_sse_min_ss:
1805 case Intrinsic::x86_sse_max_ss:
1806 case Intrinsic::x86_sse2_sub_sd:
1807 case Intrinsic::x86_sse2_mul_sd:
1808 case Intrinsic::x86_sse2_min_sd:
1809 case Intrinsic::x86_sse2_max_sd:
1810 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1811 UndefElts, Depth+1);
1812 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1813 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1814 UndefElts2, Depth+1);
1815 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1816
1817 // If only the low elt is demanded and this is a scalarizable intrinsic,
1818 // scalarize it now.
1819 if (DemandedElts == 1) {
1820 switch (II->getIntrinsicID()) {
1821 default: break;
1822 case Intrinsic::x86_sse_sub_ss:
1823 case Intrinsic::x86_sse_mul_ss:
1824 case Intrinsic::x86_sse2_sub_sd:
1825 case Intrinsic::x86_sse2_mul_sd:
1826 // TODO: Lower MIN/MAX/ABS/etc
1827 Value *LHS = II->getOperand(1);
1828 Value *RHS = II->getOperand(2);
1829 // Extract the element as scalars.
Eric Christopher1ba36872009-07-25 02:28:41 +00001830 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001831 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christopher1ba36872009-07-25 02:28:41 +00001832 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001833 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001834
1835 switch (II->getIntrinsicID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001836 default: llvm_unreachable("Case stmts out of sync!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001837 case Intrinsic::x86_sse_sub_ss:
1838 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001839 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001840 II->getName()), *II);
1841 break;
1842 case Intrinsic::x86_sse_mul_ss:
1843 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001844 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001845 II->getName()), *II);
1846 break;
1847 }
1848
1849 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001850 InsertElementInst::Create(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001851 UndefValue::get(II->getType()), TmpV,
Owen Anderson35b47072009-08-13 21:58:54 +00001852 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001853 InsertNewInstBefore(New, *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001854 return New;
1855 }
1856 }
1857
1858 // Output elements are undefined if both are undefined. Consider things
1859 // like undef&0. The result is known zero, not undef.
1860 UndefElts &= UndefElts2;
1861 break;
1862 }
1863 break;
1864 }
1865 }
1866 return MadeChange ? I : 0;
1867}
1868
Dan Gohman5d56fd42008-05-19 22:14:15 +00001869
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001870/// AssociativeOpt - Perform an optimization on an associative operator. This
1871/// function is designed to check a chain of associative operators for a
1872/// potential to apply a certain optimization. Since the optimization may be
1873/// applicable if the expression was reassociated, this checks the chain, then
1874/// reassociates the expression as necessary to expose the optimization
1875/// opportunity. This makes use of a special Functor, which must define
1876/// 'shouldApply' and 'apply' methods.
1877///
1878template<typename Functor>
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001879static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001880 unsigned Opcode = Root.getOpcode();
1881 Value *LHS = Root.getOperand(0);
1882
1883 // Quick check, see if the immediate LHS matches...
1884 if (F.shouldApply(LHS))
1885 return F.apply(Root);
1886
1887 // Otherwise, if the LHS is not of the same opcode as the root, return.
1888 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1889 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1890 // Should we apply this transform to the RHS?
1891 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1892
1893 // If not to the RHS, check to see if we should apply to the LHS...
1894 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1895 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1896 ShouldApply = true;
1897 }
1898
1899 // If the functor wants to apply the optimization to the RHS of LHSI,
1900 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1901 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001902 // Now all of the instructions are in the current basic block, go ahead
1903 // and perform the reassociation.
1904 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1905
1906 // First move the selected RHS to the LHS of the root...
1907 Root.setOperand(0, LHSI->getOperand(1));
1908
1909 // Make what used to be the LHS of the root be the user of the root...
1910 Value *ExtraOperand = TmpLHSI->getOperand(1);
1911 if (&Root == TmpLHSI) {
Owen Andersonaac28372009-07-31 20:28:14 +00001912 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001913 return 0;
1914 }
1915 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1916 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001917 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001918 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001919 ARI = Root;
1920
1921 // Now propagate the ExtraOperand down the chain of instructions until we
1922 // get to LHSI.
1923 while (TmpLHSI != LHSI) {
1924 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1925 // Move the instruction to immediately before the chain we are
1926 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001927 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001928 ARI = NextLHSI;
1929
1930 Value *NextOp = NextLHSI->getOperand(1);
1931 NextLHSI->setOperand(1, ExtraOperand);
1932 TmpLHSI = NextLHSI;
1933 ExtraOperand = NextOp;
1934 }
1935
1936 // Now that the instructions are reassociated, have the functor perform
1937 // the transformation...
1938 return F.apply(Root);
1939 }
1940
1941 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1942 }
1943 return 0;
1944}
1945
Dan Gohman089efff2008-05-13 00:00:25 +00001946namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001947
Nick Lewycky27f6c132008-05-23 04:34:58 +00001948// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001949struct AddRHS {
1950 Value *RHS;
Dan Gohmancdff2122009-08-12 16:23:25 +00001951 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001952 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1953 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001954 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001955 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001956 }
1957};
1958
1959// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1960// iff C1&C2 == 0
1961struct AddMaskingAnd {
1962 Constant *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00001963 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001964 bool shouldApply(Value *LHS) const {
1965 ConstantInt *C1;
Dan Gohmancdff2122009-08-12 16:23:25 +00001966 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Anderson02b48c32009-07-29 18:55:55 +00001967 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001968 }
1969 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001970 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001971 }
1972};
1973
Dan Gohman089efff2008-05-13 00:00:25 +00001974}
1975
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001976static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1977 InstCombiner *IC) {
Chris Lattner78628292009-08-30 19:47:22 +00001978 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattnerd6164c22009-08-30 20:01:10 +00001979 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001980
1981 // Figure out if the constant is the left or the right argument.
1982 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1983 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1984
1985 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1986 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +00001987 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1988 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001989 }
1990
1991 Value *Op0 = SO, *Op1 = ConstOperand;
1992 if (!ConstIsRHS)
1993 std::swap(Op0, Op1);
Chris Lattnerc7694852009-08-30 07:44:24 +00001994
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001995 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattnerc7694852009-08-30 07:44:24 +00001996 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1997 SO->getName()+".op");
1998 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1999 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2000 SO->getName()+".cmp");
2001 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2002 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2003 SO->getName()+".cmp");
2004 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002005}
2006
2007// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2008// constant as the other operand, try to fold the binary operator into the
2009// select arguments. This also works for Cast instructions, which obviously do
2010// not have a second operand.
2011static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2012 InstCombiner *IC) {
2013 // Don't modify shared select instructions
2014 if (!SI->hasOneUse()) return 0;
2015 Value *TV = SI->getOperand(1);
2016 Value *FV = SI->getOperand(2);
2017
2018 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2019 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson35b47072009-08-13 21:58:54 +00002020 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002021
2022 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2023 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2024
Gabor Greifd6da1d02008-04-06 20:25:17 +00002025 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2026 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002027 }
2028 return 0;
2029}
2030
2031
Chris Lattnerf7843b72009-09-27 19:57:57 +00002032/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2033/// has a PHI node as operand #0, see if we can fold the instruction into the
2034/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +00002035///
2036/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2037/// that would normally be unprofitable because they strongly encourage jump
2038/// threading.
2039Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2040 bool AllowAggressive) {
2041 AllowAggressive = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002042 PHINode *PN = cast<PHINode>(I.getOperand(0));
2043 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner9b61abd2009-09-27 20:46:36 +00002044 if (NumPHIValues == 0 ||
2045 // We normally only transform phis with a single use, unless we're trying
2046 // hard to make jump threading happen.
2047 (!PN->hasOneUse() && !AllowAggressive))
2048 return 0;
2049
2050
Chris Lattnerf7843b72009-09-27 19:57:57 +00002051 // Check to see if all of the operands of the PHI are simple constants
2052 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002053 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2054 // bail out. We don't do arbitrary constant expressions here because moving
2055 // their computation can be expensive without a cost model.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002056 BasicBlock *NonConstBB = 0;
2057 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattnerf7843b72009-09-27 19:57:57 +00002058 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2059 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002060 if (NonConstBB) return 0; // More than one non-const value.
2061 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2062 NonConstBB = PN->getIncomingBlock(i);
2063
2064 // If the incoming non-constant value is in I's block, we have an infinite
2065 // loop.
2066 if (NonConstBB == I.getParent())
2067 return 0;
2068 }
2069
2070 // If there is exactly one non-constant value, we can insert a copy of the
2071 // operation in that block. However, if this is a critical edge, we would be
2072 // inserting the computation one some other paths (e.g. inside a loop). Only
2073 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9b61abd2009-09-27 20:46:36 +00002074 if (NonConstBB != 0 && !AllowAggressive) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002075 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2076 if (!BI || !BI->isUnconditional()) return 0;
2077 }
2078
2079 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002080 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002081 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner3980f9b2009-10-21 23:41:58 +00002082 InsertNewInstBefore(NewPN, *PN);
2083 NewPN->takeName(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002084
2085 // Next, add all of the operands to the PHI.
Chris Lattnerf7843b72009-09-27 19:57:57 +00002086 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2087 // We only currently try to fold the condition of a select when it is a phi,
2088 // not the true/false values.
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002089 Value *TrueV = SI->getTrueValue();
2090 Value *FalseV = SI->getFalseValue();
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002091 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerf7843b72009-09-27 19:57:57 +00002092 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002093 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattnerda3ee9c2009-09-28 06:49:44 +00002094 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2095 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002096 Value *InV = 0;
2097 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002098 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerf7843b72009-09-27 19:57:57 +00002099 } else {
2100 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002101 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2102 FalseVInPred,
Chris Lattnerf7843b72009-09-27 19:57:57 +00002103 "phitmp", NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +00002104 Worklist.Add(cast<Instruction>(InV));
Chris Lattnerf7843b72009-09-27 19:57:57 +00002105 }
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00002106 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +00002107 }
2108 } else if (I.getNumOperands() == 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002109 Constant *C = cast<Constant>(I.getOperand(1));
2110 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002111 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002112 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2113 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +00002114 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002115 else
Owen Anderson02b48c32009-07-29 18:55:55 +00002116 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002117 } else {
2118 assert(PN->getIncomingBlock(i) == NonConstBB);
2119 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002120 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002121 PN->getIncomingValue(i), C, "phitmp",
2122 NonConstBB->getTerminator());
2123 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +00002124 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002125 CI->getPredicate(),
2126 PN->getIncomingValue(i), C, "phitmp",
2127 NonConstBB->getTerminator());
2128 else
Edwin Törökbd448e32009-07-14 16:55:14 +00002129 llvm_unreachable("Unknown binop!");
Chris Lattner3980f9b2009-10-21 23:41:58 +00002130
2131 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002132 }
2133 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2134 }
2135 } else {
2136 CastInst *CI = cast<CastInst>(&I);
2137 const Type *RetTy = CI->getType();
2138 for (unsigned i = 0; i != NumPHIValues; ++i) {
2139 Value *InV;
2140 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002141 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002142 } else {
2143 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002144 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002145 I.getType(), "phitmp",
2146 NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +00002147 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002148 }
2149 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2150 }
2151 }
2152 return ReplaceInstUsesWith(I, NewPN);
2153}
2154
Chris Lattner55476162008-01-29 06:52:45 +00002155
Chris Lattner3554f972008-05-20 05:46:13 +00002156/// WillNotOverflowSignedAdd - Return true if we can prove that:
2157/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2158/// This basically requires proving that the add in the original type would not
2159/// overflow to change the sign bit or have a carry out.
2160bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2161 // There are different heuristics we can use for this. Here are some simple
2162 // ones.
2163
2164 // Add has the property that adding any two 2's complement numbers can only
2165 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner96076f72009-11-27 17:42:22 +00002166 // have at least two sign bits, we know that the addition of the two values
2167 // will sign extend fine.
Chris Lattner3554f972008-05-20 05:46:13 +00002168 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2169 return true;
2170
2171
2172 // If one of the operands only has one non-zero bit, and if the other operand
2173 // has a known-zero bit in a more significant place than it (not including the
2174 // sign bit) the ripple may go up to and fill the zero, but won't change the
2175 // sign. For example, (X & ~4) + 1.
2176
2177 // TODO: Implement.
2178
2179 return false;
2180}
2181
Chris Lattner55476162008-01-29 06:52:45 +00002182
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002183Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2184 bool Changed = SimplifyCommutative(I);
2185 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2186
Chris Lattner96076f72009-11-27 17:42:22 +00002187 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2188 I.hasNoUnsignedWrap(), TD))
2189 return ReplaceInstUsesWith(I, V);
2190
2191
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002192 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002193 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2194 // X + (signbit) --> X ^ signbit
2195 const APInt& Val = CI->getValue();
2196 uint32_t BitWidth = Val.getBitWidth();
2197 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002198 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002199
2200 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2201 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002202 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002203 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002204
Eli Friedmana21526d2009-07-13 22:27:52 +00002205 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +00002206 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson35b47072009-08-13 21:58:54 +00002207 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002208 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002209 }
2210
2211 if (isa<PHINode>(LHS))
2212 if (Instruction *NV = FoldOpIntoPhi(I))
2213 return NV;
2214
2215 ConstantInt *XorRHS = 0;
2216 Value *XorLHS = 0;
2217 if (isa<ConstantInt>(RHSC) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002218 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002219 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002220 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2221
2222 uint32_t Size = TySizeBits / 2;
2223 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2224 APInt CFF80Val(-C0080Val);
2225 do {
2226 if (TySizeBits > Size) {
2227 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2228 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2229 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2230 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2231 // This is a sign extend if the top bits are known zero.
2232 if (!MaskedValueIsZero(XorLHS,
2233 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2234 Size = 0; // Not a sign ext, but can't be any others either.
2235 break;
2236 }
2237 }
2238 Size >>= 1;
2239 C0080Val = APIntOps::lshr(C0080Val, Size);
2240 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2241 } while (Size >= 1);
2242
2243 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002244 // with funny bit widths then this switch statement should be removed. It
2245 // is just here to get the size of the "middle" type back up to something
2246 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002247 const Type *MiddleType = 0;
2248 switch (Size) {
2249 default: break;
Owen Anderson35b47072009-08-13 21:58:54 +00002250 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2251 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2252 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002253 }
2254 if (MiddleType) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002255 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002256 return new SExtInst(NewTrunc, I.getType(), I.getName());
2257 }
2258 }
2259 }
2260
Owen Anderson35b47072009-08-13 21:58:54 +00002261 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002262 return BinaryOperator::CreateXor(LHS, RHS);
2263
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002264 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002265 if (I.getType()->isInteger()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00002266 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Anderson24be4c12009-07-03 00:17:18 +00002267 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002268
2269 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2270 if (RHSI->getOpcode() == Instruction::Sub)
2271 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2272 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2273 }
2274 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2275 if (LHSI->getOpcode() == Instruction::Sub)
2276 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2277 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2278 }
2279 }
2280
2281 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002282 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002283 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002284 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002285 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002286 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohmancdff2122009-08-12 16:23:25 +00002287 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002288 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002289 }
2290
Gabor Greifa645dd32008-05-16 19:29:10 +00002291 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002292 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002293
2294 // A + -B --> A - B
2295 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002296 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002297 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002298
2299
2300 ConstantInt *C2;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002301 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002302 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002303 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002304
2305 // X*C1 + X*C2 --> X * (C1+C2)
2306 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002307 if (X == dyn_castFoldableMul(RHS, C1))
Owen Anderson02b48c32009-07-29 18:55:55 +00002308 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002309 }
2310
2311 // X + X*C --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002312 if (dyn_castFoldableMul(RHS, C2) == LHS)
2313 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002314
2315 // X + ~X --> -1 since ~X = -X-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002316 if (dyn_castNotVal(LHS) == RHS ||
2317 dyn_castNotVal(RHS) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +00002318 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002319
2320
2321 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00002322 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2323 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002324 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002325
2326 // A+B --> A|B iff A and B have no bits set in common.
2327 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2328 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2329 APInt LHSKnownOne(IT->getBitWidth(), 0);
2330 APInt LHSKnownZero(IT->getBitWidth(), 0);
2331 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2332 if (LHSKnownZero != 0) {
2333 APInt RHSKnownOne(IT->getBitWidth(), 0);
2334 APInt RHSKnownZero(IT->getBitWidth(), 0);
2335 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2336
2337 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002338 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002339 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002340 }
2341 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002342
Nick Lewycky83598a72008-02-03 07:42:09 +00002343 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002344 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002345 Value *W, *X, *Y, *Z;
Dan Gohmancdff2122009-08-12 16:23:25 +00002346 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2347 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002348 if (W != Y) {
2349 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002350 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002351 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002352 std::swap(W, X);
2353 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002354 std::swap(Y, Z);
2355 std::swap(W, X);
2356 }
2357 }
2358
2359 if (W == Y) {
Chris Lattnerc7694852009-08-30 07:44:24 +00002360 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002361 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002362 }
2363 }
2364 }
2365
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002366 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2367 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002368 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002369 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002370
2371 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002372 if (LHS->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002373 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002374 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002375 if (Anded == CRHS) {
2376 // See if all bits from the first bit set in the Add RHS up are included
2377 // in the mask. First, get the rightmost bit.
2378 const APInt& AddRHSV = CRHS->getValue();
2379
2380 // Form a mask of all bits from the lowest bit added through the top.
2381 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2382
2383 // See if the and mask includes all of these bits.
2384 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2385
2386 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2387 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattnerc7694852009-08-30 07:44:24 +00002388 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00002389 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002390 }
2391 }
2392 }
2393
2394 // Try to fold constant add into select arguments.
2395 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2396 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2397 return R;
2398 }
2399
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002400 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002401 {
2402 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002403 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002404 if (!SI) {
2405 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002406 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002407 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002408 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002409 Value *TV = SI->getTrueValue();
2410 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002411 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002412
2413 // Can we fold the add into the argument of the select?
2414 // We check both true and false select arguments for a matching subtract.
Dan Gohmancdff2122009-08-12 16:23:25 +00002415 if (match(FV, m_Zero()) &&
2416 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002417 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002418 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohmancdff2122009-08-12 16:23:25 +00002419 if (match(TV, m_Zero()) &&
2420 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002421 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002422 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002423 }
2424 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002425
Chris Lattner3554f972008-05-20 05:46:13 +00002426 // Check for (add (sext x), y), see if we can merge this into an
2427 // integer add followed by a sext.
2428 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2429 // (add (sext x), cst) --> (sext (add x, cst'))
2430 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2431 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002432 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002433 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002434 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002435 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2436 // Insert the new, smaller add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002437 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2438 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002439 return new SExtInst(NewAdd, I.getType());
2440 }
2441 }
2442
2443 // (add (sext x), (sext y)) --> (sext (add int x, y))
2444 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2445 // Only do this if x/y have the same type, if at last one of them has a
2446 // single use (so we don't increase the number of sexts), and if the
2447 // integer add will not overflow.
2448 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2449 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2450 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2451 RHSConv->getOperand(0))) {
2452 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002453 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2454 RHSConv->getOperand(0), "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002455 return new SExtInst(NewAdd, I.getType());
2456 }
2457 }
2458 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002459
2460 return Changed ? &I : 0;
2461}
2462
2463Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2464 bool Changed = SimplifyCommutative(I);
2465 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2466
2467 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2468 // X + 0 --> X
2469 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +00002470 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002471 (I.getType())->getValueAPF()))
2472 return ReplaceInstUsesWith(I, LHS);
2473 }
2474
2475 if (isa<PHINode>(LHS))
2476 if (Instruction *NV = FoldOpIntoPhi(I))
2477 return NV;
2478 }
2479
2480 // -A + B --> B - A
2481 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002482 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002483 return BinaryOperator::CreateFSub(RHS, LHSV);
2484
2485 // A + -B --> A - B
2486 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002487 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002488 return BinaryOperator::CreateFSub(LHS, V);
2489
2490 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2491 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2492 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2493 return ReplaceInstUsesWith(I, LHS);
2494
Chris Lattner3554f972008-05-20 05:46:13 +00002495 // Check for (add double (sitofp x), y), see if we can merge this into an
2496 // integer add followed by a promotion.
2497 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2498 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2499 // ... if the constant fits in the integer value. This is useful for things
2500 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2501 // requires a constant pool load, and generally allows the add to be better
2502 // instcombined.
2503 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2504 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002505 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002506 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002507 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002508 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2509 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002510 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2511 CI, "addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002512 return new SIToFPInst(NewAdd, I.getType());
2513 }
2514 }
2515
2516 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2517 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2518 // Only do this if x/y have the same type, if at last one of them has a
2519 // single use (so we don't increase the number of int->fp conversions),
2520 // and if the integer add will not overflow.
2521 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2522 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2523 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2524 RHSConv->getOperand(0))) {
2525 // Insert the new integer add.
Dan Gohman4dcf7c02009-10-26 22:14:22 +00002526 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner93e6ff92009-11-04 08:05:20 +00002527 RHSConv->getOperand(0),"addconv");
Chris Lattner3554f972008-05-20 05:46:13 +00002528 return new SIToFPInst(NewAdd, I.getType());
2529 }
2530 }
2531 }
2532
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002533 return Changed ? &I : 0;
2534}
2535
Chris Lattner93e6ff92009-11-04 08:05:20 +00002536
2537/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2538/// code necessary to compute the offset from the base pointer (without adding
2539/// in the base pointer). Return the result as a signed integer of intptr size.
2540static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2541 TargetData &TD = *IC.getTargetData();
2542 gep_type_iterator GTI = gep_type_begin(GEP);
2543 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2544 Value *Result = Constant::getNullValue(IntPtrTy);
2545
2546 // Build a mask for high order bits.
2547 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2548 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2549
2550 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2551 ++i, ++GTI) {
2552 Value *Op = *i;
2553 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2554 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2555 if (OpC->isZero()) continue;
2556
2557 // Handle a struct index, which adds its field offset to the pointer.
2558 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2559 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2560
2561 Result = IC.Builder->CreateAdd(Result,
2562 ConstantInt::get(IntPtrTy, Size),
2563 GEP->getName()+".offs");
2564 continue;
2565 }
2566
2567 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2568 Constant *OC =
2569 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2570 Scale = ConstantExpr::getMul(OC, Scale);
2571 // Emit an add instruction.
2572 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2573 continue;
2574 }
2575 // Convert to correct type.
2576 if (Op->getType() != IntPtrTy)
2577 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2578 if (Size != 1) {
2579 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2580 // We'll let instcombine(mul) convert this to a shl if possible.
2581 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2582 }
2583
2584 // Emit an add instruction.
2585 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2586 }
2587 return Result;
2588}
2589
2590
2591/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2592/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2593/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2594/// be complex, and scales are involved. The above expression would also be
2595/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2596/// This later form is less amenable to optimization though, and we are allowed
2597/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2598///
2599/// If we can't emit an optimized form for this expression, this returns null.
2600///
2601static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2602 InstCombiner &IC) {
2603 TargetData &TD = *IC.getTargetData();
2604 gep_type_iterator GTI = gep_type_begin(GEP);
2605
2606 // Check to see if this gep only has a single variable index. If so, and if
2607 // any constant indices are a multiple of its scale, then we can compute this
2608 // in terms of the scale of the variable index. For example, if the GEP
2609 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2610 // because the expression will cross zero at the same point.
2611 unsigned i, e = GEP->getNumOperands();
2612 int64_t Offset = 0;
2613 for (i = 1; i != e; ++i, ++GTI) {
2614 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2615 // Compute the aggregate offset of constant indices.
2616 if (CI->isZero()) continue;
2617
2618 // Handle a struct index, which adds its field offset to the pointer.
2619 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2620 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2621 } else {
2622 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2623 Offset += Size*CI->getSExtValue();
2624 }
2625 } else {
2626 // Found our variable index.
2627 break;
2628 }
2629 }
2630
2631 // If there are no variable indices, we must have a constant offset, just
2632 // evaluate it the general way.
2633 if (i == e) return 0;
2634
2635 Value *VariableIdx = GEP->getOperand(i);
2636 // Determine the scale factor of the variable element. For example, this is
2637 // 4 if the variable index is into an array of i32.
2638 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2639
2640 // Verify that there are no other variable indices. If so, emit the hard way.
2641 for (++i, ++GTI; i != e; ++i, ++GTI) {
2642 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2643 if (!CI) return 0;
2644
2645 // Compute the aggregate offset of constant indices.
2646 if (CI->isZero()) continue;
2647
2648 // Handle a struct index, which adds its field offset to the pointer.
2649 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2650 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2651 } else {
2652 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2653 Offset += Size*CI->getSExtValue();
2654 }
2655 }
2656
2657 // Okay, we know we have a single variable index, which must be a
2658 // pointer/array/vector index. If there is no offset, life is simple, return
2659 // the index.
2660 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2661 if (Offset == 0) {
2662 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2663 // we don't need to bother extending: the extension won't affect where the
2664 // computation crosses zero.
2665 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2666 VariableIdx = new TruncInst(VariableIdx,
2667 TD.getIntPtrType(VariableIdx->getContext()),
2668 VariableIdx->getName(), &I);
2669 return VariableIdx;
2670 }
2671
2672 // Otherwise, there is an index. The computation we will do will be modulo
2673 // the pointer size, so get it.
2674 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2675
2676 Offset &= PtrSizeMask;
2677 VariableScale &= PtrSizeMask;
2678
2679 // To do this transformation, any constant index must be a multiple of the
2680 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2681 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2682 // multiple of the variable scale.
2683 int64_t NewOffs = Offset / (int64_t)VariableScale;
2684 if (Offset != NewOffs*(int64_t)VariableScale)
2685 return 0;
2686
2687 // Okay, we can do this evaluation. Start by converting the index to intptr.
2688 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2689 if (VariableIdx->getType() != IntPtrTy)
2690 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2691 true /*SExt*/,
2692 VariableIdx->getName(), &I);
2693 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2694 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2695}
2696
2697
2698/// Optimize pointer differences into the same array into a size. Consider:
2699/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2700/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2701///
2702Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2703 const Type *Ty) {
2704 assert(TD && "Must have target data info for this");
2705
2706 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2707 // this.
2708 bool Swapped;
2709 GetElementPtrInst *GEP;
2710
2711 if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2712 GEP->getOperand(0) == RHS)
2713 Swapped = false;
2714 else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2715 GEP->getOperand(0) == LHS)
2716 Swapped = true;
2717 else
2718 return 0;
2719
2720 // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2721
2722 // Emit the offset of the GEP and an intptr_t.
2723 Value *Result = EmitGEPOffset(GEP, *this);
2724
2725 // If we have p - gep(p, ...) then we have to negate the result.
2726 if (Swapped)
2727 Result = Builder->CreateNeg(Result, "diff.neg");
2728
2729 return Builder->CreateIntCast(Result, Ty, true);
2730}
2731
2732
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002733Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2734 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2735
Dan Gohman7ce405e2009-06-04 22:49:04 +00002736 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002737 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002738
Chris Lattner93e6ff92009-11-04 08:05:20 +00002739 // If this is a 'B = x-(-A)', change to B = x+A.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002740 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002741 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002742
2743 if (isa<UndefValue>(Op0))
2744 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2745 if (isa<UndefValue>(Op1))
2746 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner93e6ff92009-11-04 08:05:20 +00002747 if (I.getType() == Type::getInt1Ty(*Context))
2748 return BinaryOperator::CreateXor(Op0, Op1);
2749
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002750 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner93e6ff92009-11-04 08:05:20 +00002751 // Replace (-1 - A) with (~A).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002752 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00002753 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002754
2755 // C - ~X == X + (1+C)
2756 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002757 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002758 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002759
2760 // -(X >>u 31) -> (X >>s 31)
2761 // -(X >>s 31) -> (X >>u 31)
2762 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002763 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002764 if (SI->getOpcode() == Instruction::LShr) {
2765 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 AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002770 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002771 SI->getOperand(0), CU, SI->getName());
2772 }
2773 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00002774 } else if (SI->getOpcode() == Instruction::AShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002775 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2776 // Check to see if we are shifting out everything but the sign bit.
2777 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2778 SI->getType()->getPrimitiveSizeInBits()-1) {
2779 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002780 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002781 SI->getOperand(0), CU, SI->getName());
2782 }
2783 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002784 }
2785 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002786 }
2787
2788 // Try to fold constant sub into select arguments.
2789 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2790 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2791 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002792
2793 // C - zext(bool) -> bool ? C - 1 : C
2794 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson35b47072009-08-13 21:58:54 +00002795 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002796 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002797 }
2798
2799 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002800 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002801 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002802 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002803 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002804 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002805 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002806 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002807 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2808 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2809 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002810 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002811 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002812 }
2813 }
2814
2815 if (Op1I->hasOneUse()) {
2816 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2817 // is not used by anyone else...
2818 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002819 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002820 // Swap the two operands of the subexpr...
2821 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2822 Op1I->setOperand(0, IIOp1);
2823 Op1I->setOperand(1, IIOp0);
2824
2825 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002826 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002827 }
2828
2829 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2830 //
2831 if (Op1I->getOpcode() == Instruction::And &&
2832 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2833 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2834
Chris Lattnerc7694852009-08-30 07:44:24 +00002835 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greifa645dd32008-05-16 19:29:10 +00002836 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002837 }
2838
2839 // 0 - (X sdiv C) -> (X sdiv -C)
2840 if (Op1I->getOpcode() == Instruction::SDiv)
2841 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2842 if (CSI->isZero())
2843 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002844 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002845 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002846
2847 // X - X*C --> X * (1-C)
2848 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002849 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002850 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00002851 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002852 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002853 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002854 }
2855 }
2856 }
2857
Dan Gohman7ce405e2009-06-04 22:49:04 +00002858 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2859 if (Op0I->getOpcode() == Instruction::Add) {
2860 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2861 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2862 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2863 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2864 } else if (Op0I->getOpcode() == Instruction::Sub) {
2865 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002866 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002867 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002868 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002869 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002870
2871 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002872 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002873 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002874 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002875
2876 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002877 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00002878 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002879 }
Chris Lattner93e6ff92009-11-04 08:05:20 +00002880
2881 // Optimize pointer differences into the same array into a size. Consider:
2882 // &A[10] - &A[0]: we should compile this to "10".
2883 if (TD) {
2884 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2885 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2886 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2887 RHS->getOperand(0),
2888 I.getType()))
2889 return ReplaceInstUsesWith(I, Res);
2890
2891 // trunc(p)-trunc(q) -> trunc(p-q)
2892 if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2893 if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2894 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2895 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2896 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2897 RHS->getOperand(0),
2898 I.getType()))
2899 return ReplaceInstUsesWith(I, Res);
2900 }
2901
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002902 return 0;
2903}
2904
Dan Gohman7ce405e2009-06-04 22:49:04 +00002905Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2906 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2907
2908 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002909 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002910 return BinaryOperator::CreateFAdd(Op0, V);
2911
2912 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2913 if (Op1I->getOpcode() == Instruction::FAdd) {
2914 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002915 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002916 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002917 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002918 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002919 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002920 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002921 }
2922
2923 return 0;
2924}
2925
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002926/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2927/// comparison only checks the sign bit. If it only checks the sign bit, set
2928/// TrueIfSigned if the result of the comparison is true when the input value is
2929/// signed.
2930static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2931 bool &TrueIfSigned) {
2932 switch (pred) {
2933 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2934 TrueIfSigned = true;
2935 return RHS->isZero();
2936 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2937 TrueIfSigned = true;
2938 return RHS->isAllOnesValue();
2939 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2940 TrueIfSigned = false;
2941 return RHS->isAllOnesValue();
2942 case ICmpInst::ICMP_UGT:
2943 // True if LHS u> RHS and RHS == high-bit-mask - 1
2944 TrueIfSigned = true;
2945 return RHS->getValue() ==
2946 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2947 case ICmpInst::ICMP_UGE:
2948 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2949 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002950 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002951 default:
2952 return false;
2953 }
2954}
2955
2956Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2957 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00002958 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002959
Chris Lattner3508c5c2009-10-11 21:36:10 +00002960 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002961 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002962
Chris Lattner6438c582009-10-11 07:53:15 +00002963 // Simplify mul instructions with a constant RHS.
Chris Lattner3508c5c2009-10-11 21:36:10 +00002964 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2965 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002966
2967 // ((X << C1)*C2) == (X * (C2 << C1))
2968 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2969 if (SI->getOpcode() == Instruction::Shl)
2970 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002971 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002972 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002973
2974 if (CI->isZero())
Chris Lattner3508c5c2009-10-11 21:36:10 +00002975 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002976 if (CI->equalsInt(1)) // X * 1 == X
2977 return ReplaceInstUsesWith(I, Op0);
2978 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002979 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002980
2981 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2982 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002983 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002984 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002985 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00002986 } else if (isa<VectorType>(Op1C->getType())) {
2987 if (Op1C->isNullValue())
2988 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky94418732008-11-27 20:21:08 +00002989
Chris Lattner3508c5c2009-10-11 21:36:10 +00002990 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky94418732008-11-27 20:21:08 +00002991 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002992 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00002993
2994 // As above, vector X*splat(1.0) -> X in all defined cases.
2995 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002996 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2997 if (CI->equalsInt(1))
2998 return ReplaceInstUsesWith(I, Op0);
2999 }
3000 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003001 }
3002
3003 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3004 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00003005 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003006 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner3508c5c2009-10-11 21:36:10 +00003007 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3008 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greifa645dd32008-05-16 19:29:10 +00003009 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003010
3011 }
3012
3013 // Try to fold constant mul into select arguments.
3014 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3015 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3016 return R;
3017
3018 if (isa<PHINode>(Op0))
3019 if (Instruction *NV = FoldOpIntoPhi(I))
3020 return NV;
3021 }
3022
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003023 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00003024 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00003025 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003026
Nick Lewycky1c246402008-11-21 07:33:58 +00003027 // (X / Y) * Y = X - (X % Y)
3028 // (X / Y) * -Y = (X % Y) - X
3029 {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003030 Value *Op1C = Op1;
Nick Lewycky1c246402008-11-21 07:33:58 +00003031 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3032 if (!BO ||
3033 (BO->getOpcode() != Instruction::UDiv &&
3034 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003035 Op1C = Op0;
3036 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00003037 }
Chris Lattner3508c5c2009-10-11 21:36:10 +00003038 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky1c246402008-11-21 07:33:58 +00003039 if (BO && BO->hasOneUse() &&
Chris Lattner3508c5c2009-10-11 21:36:10 +00003040 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky1c246402008-11-21 07:33:58 +00003041 (BO->getOpcode() == Instruction::UDiv ||
3042 BO->getOpcode() == Instruction::SDiv)) {
3043 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3044
Dan Gohman07878902009-08-12 16:33:09 +00003045 // If the division is exact, X % Y is zero.
3046 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3047 if (SDiv->isExact()) {
Chris Lattner3508c5c2009-10-11 21:36:10 +00003048 if (Op1BO == Op1C)
Dan Gohman07878902009-08-12 16:33:09 +00003049 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattner3508c5c2009-10-11 21:36:10 +00003050 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohman07878902009-08-12 16:33:09 +00003051 }
3052
Chris Lattnerc7694852009-08-30 07:44:24 +00003053 Value *Rem;
Nick Lewycky1c246402008-11-21 07:33:58 +00003054 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattnerc7694852009-08-30 07:44:24 +00003055 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003056 else
Chris Lattnerc7694852009-08-30 07:44:24 +00003057 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003058 Rem->takeName(BO);
3059
Chris Lattner3508c5c2009-10-11 21:36:10 +00003060 if (Op1BO == Op1C)
Nick Lewycky1c246402008-11-21 07:33:58 +00003061 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattnerc7694852009-08-30 07:44:24 +00003062 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky1c246402008-11-21 07:33:58 +00003063 }
3064 }
3065
Chris Lattner6438c582009-10-11 07:53:15 +00003066 /// i1 mul -> i1 and.
Owen Anderson35b47072009-08-13 21:58:54 +00003067 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003068 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003069
Chris Lattner6438c582009-10-11 07:53:15 +00003070 // X*(1 << Y) --> X << Y
3071 // (1 << Y)*X --> X << Y
3072 {
3073 Value *Y;
3074 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003075 return BinaryOperator::CreateShl(Op1, Y);
3076 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner6438c582009-10-11 07:53:15 +00003077 return BinaryOperator::CreateShl(Op0, Y);
3078 }
3079
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003080 // If one of the operands of the multiply is a cast from a boolean value, then
3081 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattner4ca76f72009-10-11 21:29:45 +00003082 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3083 if (!isa<VectorType>(I.getType())) {
3084 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenb5887062009-10-12 18:45:32 +00003085 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner291872e2009-10-11 21:22:21 +00003086
Chris Lattner4ca76f72009-10-11 21:29:45 +00003087 Value *BoolCast = 0, *OtherOp = 0;
3088 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattner3508c5c2009-10-11 21:36:10 +00003089 BoolCast = Op0, OtherOp = Op1;
3090 else if (MaskedValueIsZero(Op1, Negative2))
3091 BoolCast = Op1, OtherOp = Op0;
Chris Lattner4ca76f72009-10-11 21:29:45 +00003092
Chris Lattner291872e2009-10-11 21:22:21 +00003093 if (BoolCast) {
Chris Lattner291872e2009-10-11 21:22:21 +00003094 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3095 BoolCast, "tmp");
3096 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003097 }
3098 }
3099
3100 return Changed ? &I : 0;
3101}
3102
Dan Gohman7ce405e2009-06-04 22:49:04 +00003103Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3104 bool Changed = SimplifyCommutative(I);
Chris Lattner3508c5c2009-10-11 21:36:10 +00003105 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohman7ce405e2009-06-04 22:49:04 +00003106
3107 // Simplify mul instructions with a constant RHS...
Chris Lattner3508c5c2009-10-11 21:36:10 +00003108 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3109 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00003110 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3111 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3112 if (Op1F->isExactlyValue(1.0))
3113 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattner3508c5c2009-10-11 21:36:10 +00003114 } else if (isa<VectorType>(Op1C->getType())) {
3115 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00003116 // As above, vector X*splat(1.0) -> X in all defined cases.
3117 if (Constant *Splat = Op1V->getSplatValue()) {
3118 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3119 if (F->isExactlyValue(1.0))
3120 return ReplaceInstUsesWith(I, Op0);
3121 }
3122 }
3123 }
3124
3125 // Try to fold constant mul into select arguments.
3126 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3127 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3128 return R;
3129
3130 if (isa<PHINode>(Op0))
3131 if (Instruction *NV = FoldOpIntoPhi(I))
3132 return NV;
3133 }
3134
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003135 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattner3508c5c2009-10-11 21:36:10 +00003136 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00003137 return BinaryOperator::CreateFMul(Op0v, Op1v);
3138
3139 return Changed ? &I : 0;
3140}
3141
Chris Lattner76972db2008-07-14 00:15:52 +00003142/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3143/// instruction.
3144bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3145 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3146
3147 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3148 int NonNullOperand = -1;
3149 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3150 if (ST->isNullValue())
3151 NonNullOperand = 2;
3152 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3153 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3154 if (ST->isNullValue())
3155 NonNullOperand = 1;
3156
3157 if (NonNullOperand == -1)
3158 return false;
3159
3160 Value *SelectCond = SI->getOperand(0);
3161
3162 // Change the div/rem to use 'Y' instead of the select.
3163 I.setOperand(1, SI->getOperand(NonNullOperand));
3164
3165 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3166 // problem. However, the select, or the condition of the select may have
3167 // multiple uses. Based on our knowledge that the operand must be non-zero,
3168 // propagate the known value for the select into other uses of it, and
3169 // propagate a known value of the condition into its other users.
3170
3171 // If the select and condition only have a single use, don't bother with this,
3172 // early exit.
3173 if (SI->use_empty() && SelectCond->hasOneUse())
3174 return true;
3175
3176 // Scan the current block backward, looking for other uses of SI.
3177 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3178
3179 while (BBI != BBFront) {
3180 --BBI;
3181 // If we found a call to a function, we can't assume it will return, so
3182 // information from below it cannot be propagated above it.
3183 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3184 break;
3185
3186 // Replace uses of the select or its condition with the known values.
3187 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3188 I != E; ++I) {
3189 if (*I == SI) {
3190 *I = SI->getOperand(NonNullOperand);
Chris Lattner3183fb62009-08-30 06:13:40 +00003191 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00003192 } else if (*I == SelectCond) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00003193 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3194 ConstantInt::getFalse(*Context);
Chris Lattner3183fb62009-08-30 06:13:40 +00003195 Worklist.Add(BBI);
Chris Lattner76972db2008-07-14 00:15:52 +00003196 }
3197 }
3198
3199 // If we past the instruction, quit looking for it.
3200 if (&*BBI == SI)
3201 SI = 0;
3202 if (&*BBI == SelectCond)
3203 SelectCond = 0;
3204
3205 // If we ran out of things to eliminate, break out of the loop.
3206 if (SelectCond == 0 && SI == 0)
3207 break;
3208
3209 }
3210 return true;
3211}
3212
3213
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003214/// This function implements the transforms on div instructions that work
3215/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3216/// used by the visitors to those instructions.
3217/// @brief Transforms common to all three div instructions
3218Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3219 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3220
Chris Lattner653ef3c2008-02-19 06:12:18 +00003221 // undef / X -> 0 for integer.
3222 // undef / X -> undef for FP (the undef could be a snan).
3223 if (isa<UndefValue>(Op0)) {
3224 if (Op0->getType()->isFPOrFPVector())
3225 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00003226 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003227 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003228
3229 // X / undef -> undef
3230 if (isa<UndefValue>(Op1))
3231 return ReplaceInstUsesWith(I, Op1);
3232
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003233 return 0;
3234}
3235
3236/// This function implements the transforms common to both integer division
3237/// instructions (udiv and sdiv). It is called by the visitors to those integer
3238/// division instructions.
3239/// @brief Common integer divide transforms
3240Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3241 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3242
Chris Lattnercefb36c2008-05-16 02:59:42 +00003243 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00003244 if (Op0 == Op1) {
3245 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00003246 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00003247 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00003248 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00003249 }
3250
Owen Andersoneacb44d2009-07-24 23:12:02 +00003251 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00003252 return ReplaceInstUsesWith(I, CI);
3253 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00003254
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003255 if (Instruction *Common = commonDivTransforms(I))
3256 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00003257
3258 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3259 // This does not apply for fdiv.
3260 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3261 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003262
3263 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3264 // div X, 1 == X
3265 if (RHS->equalsInt(1))
3266 return ReplaceInstUsesWith(I, Op0);
3267
3268 // (X / C1) / C2 -> X / (C1*C2)
3269 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3270 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3271 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00003272 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003273 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00003274 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00003275 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003276 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00003277 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003278 }
3279
3280 if (!RHS->isZero()) { // avoid X udiv 0
3281 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3282 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3283 return R;
3284 if (isa<PHINode>(Op0))
3285 if (Instruction *NV = FoldOpIntoPhi(I))
3286 return NV;
3287 }
3288 }
3289
3290 // 0 / X == 0, we don't need to preserve faults!
3291 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3292 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00003293 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003294
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003295 // It can't be division by zero, hence it must be division by one.
Owen Anderson35b47072009-08-13 21:58:54 +00003296 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003297 return ReplaceInstUsesWith(I, Op0);
3298
Nick Lewycky94418732008-11-27 20:21:08 +00003299 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3300 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3301 // div X, 1 == X
3302 if (X->isOne())
3303 return ReplaceInstUsesWith(I, Op0);
3304 }
3305
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003306 return 0;
3307}
3308
3309Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3310 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3311
3312 // Handle the integer div common cases
3313 if (Instruction *Common = commonIDivTransforms(I))
3314 return Common;
3315
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003316 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00003317 // X udiv C^2 -> X >> C
3318 // Check to see if this is an unsigned division with an exact power of 2,
3319 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003320 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003321 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003322 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003323
3324 // X udiv C, where C >= signbit
3325 if (C->getValue().isNegative()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003326 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersonaac28372009-07-31 20:28:14 +00003327 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003328 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003329 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003330 }
3331
3332 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3333 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3334 if (RHSI->getOpcode() == Instruction::Shl &&
3335 isa<ConstantInt>(RHSI->getOperand(0))) {
3336 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3337 if (C1.isPowerOf2()) {
3338 Value *N = RHSI->getOperand(1);
3339 const Type *NTy = N->getType();
Chris Lattnerc7694852009-08-30 07:44:24 +00003340 if (uint32_t C2 = C1.logBase2())
3341 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003342 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003343 }
3344 }
3345 }
3346
3347 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3348 // where C1&C2 are powers of two.
3349 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3350 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3351 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3352 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3353 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3354 // Compute the shift amounts
3355 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3356 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003357 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003358 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003359
3360 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003361 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattnerc7694852009-08-30 07:44:24 +00003362 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003363
3364 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003365 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003366 }
3367 }
3368 return 0;
3369}
3370
3371Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3372 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3373
3374 // Handle the integer div common cases
3375 if (Instruction *Common = commonIDivTransforms(I))
3376 return Common;
3377
3378 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3379 // sdiv X, -1 == -X
3380 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00003381 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00003382
Dan Gohman07878902009-08-12 16:33:09 +00003383 // sdiv X, C --> ashr X, log2(C)
Dan Gohman31b6b132009-08-11 20:47:47 +00003384 if (cast<SDivOperator>(&I)->isExact() &&
3385 RHS->getValue().isNonNegative() &&
3386 RHS->getValue().isPowerOf2()) {
3387 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3388 RHS->getValue().exactLogBase2());
3389 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3390 }
Dan Gohman5ce93b32009-08-12 16:37:02 +00003391
3392 // -X/C --> X/-C provided the negation doesn't overflow.
3393 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3394 if (isa<Constant>(Sub->getOperand(0)) &&
3395 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohmanb5ed4492009-08-20 17:11:38 +00003396 Sub->hasNoSignedWrap())
Dan Gohman5ce93b32009-08-12 16:37:02 +00003397 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3398 ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003399 }
3400
3401 // If the sign bits of both operands are zero (i.e. we can prove they are
3402 // unsigned inputs), turn this into a udiv.
3403 if (I.getType()->isInteger()) {
3404 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003405 if (MaskedValueIsZero(Op0, Mask)) {
3406 if (MaskedValueIsZero(Op1, Mask)) {
3407 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3408 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3409 }
3410 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00003411 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00003412 ShiftedInt->getValue().isPowerOf2()) {
3413 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3414 // Safe because the only negative value (1 << Y) can take on is
3415 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3416 // the sign bit set.
3417 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3418 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003419 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003420 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003421
3422 return 0;
3423}
3424
3425Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3426 return commonDivTransforms(I);
3427}
3428
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003429/// This function implements the transforms on rem instructions that work
3430/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3431/// is used by the visitors to those instructions.
3432/// @brief Transforms common to all three rem instructions
3433Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3434 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3435
Chris Lattner653ef3c2008-02-19 06:12:18 +00003436 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3437 if (I.getType()->isFPOrFPVector())
3438 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00003439 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003440 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003441 if (isa<UndefValue>(Op1))
3442 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3443
3444 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003445 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3446 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003447
3448 return 0;
3449}
3450
3451/// This function implements the transforms common to both integer remainder
3452/// instructions (urem and srem). It is called by the visitors to those integer
3453/// remainder instructions.
3454/// @brief Common integer remainder transforms
3455Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3456 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3457
3458 if (Instruction *common = commonRemTransforms(I))
3459 return common;
3460
Dale Johannesena51f7372009-01-21 00:35:19 +00003461 // 0 % X == 0 for integer, we don't need to preserve faults!
3462 if (Constant *LHS = dyn_cast<Constant>(Op0))
3463 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00003464 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003465
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003466 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3467 // X % 0 == undef, we don't need to preserve faults!
3468 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003469 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003470
3471 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003472 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003473
3474 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3475 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3476 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3477 return R;
3478 } else if (isa<PHINode>(Op0I)) {
3479 if (Instruction *NV = FoldOpIntoPhi(I))
3480 return NV;
3481 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003482
3483 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003484 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003485 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003486 }
3487 }
3488
3489 return 0;
3490}
3491
3492Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3493 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3494
3495 if (Instruction *common = commonIRemTransforms(I))
3496 return common;
3497
3498 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3499 // X urem C^2 -> X and C
3500 // Check to see if this is an unsigned remainder with an exact power of 2,
3501 // if so, convert to a bitwise and.
3502 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3503 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003504 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003505 }
3506
3507 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3508 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3509 if (RHSI->getOpcode() == Instruction::Shl &&
3510 isa<ConstantInt>(RHSI->getOperand(0))) {
3511 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00003512 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00003513 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00003514 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003515 }
3516 }
3517 }
3518
3519 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3520 // where C1&C2 are powers of two.
3521 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3522 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3523 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3524 // STO == 0 and SFO == 0 handled above.
3525 if ((STO->getValue().isPowerOf2()) &&
3526 (SFO->getValue().isPowerOf2())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00003527 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3528 SI->getName()+".t");
3529 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3530 SI->getName()+".f");
Gabor Greifd6da1d02008-04-06 20:25:17 +00003531 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003532 }
3533 }
3534 }
3535
3536 return 0;
3537}
3538
3539Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3540 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3541
Dan Gohmandb3dd962007-11-05 23:16:33 +00003542 // Handle the integer rem common cases
Chris Lattner4796b622009-08-30 06:22:51 +00003543 if (Instruction *Common = commonIRemTransforms(I))
3544 return Common;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003545
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003546 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003547 if (!isa<Constant>(RHSNeg) ||
3548 (isa<ConstantInt>(RHSNeg) &&
3549 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003550 // X % -Y -> X % Y
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003551 Worklist.AddValue(I.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003552 I.setOperand(1, RHSNeg);
3553 return &I;
3554 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003555
Dan Gohmandb3dd962007-11-05 23:16:33 +00003556 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003557 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003558 if (I.getType()->isInteger()) {
3559 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3560 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3561 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003562 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003563 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003564 }
3565
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003566 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003567 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3568 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003569
Nick Lewyckyfd746832008-12-20 16:48:00 +00003570 bool hasNegative = false;
3571 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3572 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3573 if (RHS->getValue().isNegative())
3574 hasNegative = true;
3575
3576 if (hasNegative) {
3577 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003578 for (unsigned i = 0; i != VWidth; ++i) {
3579 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3580 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00003581 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003582 else
3583 Elts[i] = RHS;
3584 }
3585 }
3586
Owen Anderson2f422e02009-07-28 21:19:26 +00003587 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003588 if (NewRHSV != RHSV) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +00003589 Worklist.AddValue(I.getOperand(1));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003590 I.setOperand(1, NewRHSV);
3591 return &I;
3592 }
3593 }
3594 }
3595
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003596 return 0;
3597}
3598
3599Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3600 return commonRemTransforms(I);
3601}
3602
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003603// isOneBitSet - Return true if there is exactly one bit set in the specified
3604// constant.
3605static bool isOneBitSet(const ConstantInt *CI) {
3606 return CI->getValue().isPowerOf2();
3607}
3608
3609// isHighOnes - Return true if the constant is of the form 1+0+.
3610// This is the same as lowones(~X).
3611static bool isHighOnes(const ConstantInt *CI) {
3612 return (~CI->getValue() + 1).isPowerOf2();
3613}
3614
3615/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3616/// are carefully arranged to allow folding of expressions such as:
3617///
3618/// (A < B) | (A > B) --> (A != B)
3619///
3620/// Note that this is only valid if the first and second predicates have the
3621/// same sign. Is illegal to do: (A u< B) | (A s> B)
3622///
3623/// Three bits are used to represent the condition, as follows:
3624/// 0 A > B
3625/// 1 A == B
3626/// 2 A < B
3627///
3628/// <=> Value Definition
3629/// 000 0 Always false
3630/// 001 1 A > B
3631/// 010 2 A == B
3632/// 011 3 A >= B
3633/// 100 4 A < B
3634/// 101 5 A != B
3635/// 110 6 A <= B
3636/// 111 7 Always true
3637///
3638static unsigned getICmpCode(const ICmpInst *ICI) {
3639 switch (ICI->getPredicate()) {
3640 // False -> 0
3641 case ICmpInst::ICMP_UGT: return 1; // 001
3642 case ICmpInst::ICMP_SGT: return 1; // 001
3643 case ICmpInst::ICMP_EQ: return 2; // 010
3644 case ICmpInst::ICMP_UGE: return 3; // 011
3645 case ICmpInst::ICMP_SGE: return 3; // 011
3646 case ICmpInst::ICMP_ULT: return 4; // 100
3647 case ICmpInst::ICMP_SLT: return 4; // 100
3648 case ICmpInst::ICMP_NE: return 5; // 101
3649 case ICmpInst::ICMP_ULE: return 6; // 110
3650 case ICmpInst::ICMP_SLE: return 6; // 110
3651 // True -> 7
3652 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003653 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003654 return 0;
3655 }
3656}
3657
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003658/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3659/// predicate into a three bit mask. It also returns whether it is an ordered
3660/// predicate by reference.
3661static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3662 isOrdered = false;
3663 switch (CC) {
3664 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3665 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003666 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3667 case FCmpInst::FCMP_UGT: return 1; // 001
3668 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3669 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003670 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3671 case FCmpInst::FCMP_UGE: return 3; // 011
3672 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3673 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003674 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3675 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003676 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3677 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003678 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003679 default:
3680 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003681 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003682 return 0;
3683 }
3684}
3685
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003686/// getICmpValue - This is the complement of getICmpCode, which turns an
3687/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003688/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003689/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003690static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003691 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003692 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003693 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson4f720fa2009-07-31 17:39:07 +00003694 case 0: return ConstantInt::getFalse(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003695 case 1:
3696 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003697 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003698 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003699 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3700 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003701 case 3:
3702 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003703 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003704 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003705 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003706 case 4:
3707 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003708 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003709 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003710 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3711 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003712 case 6:
3713 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003714 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003715 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003716 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003717 case 7: return ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003718 }
3719}
3720
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003721/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3722/// opcode and two operands into either a FCmp instruction. isordered is passed
3723/// in to determine which kind of predicate to use in the new fcmp instruction.
3724static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003725 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003726 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003727 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003728 case 0:
3729 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003730 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003731 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003732 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003733 case 1:
3734 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003735 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003736 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003737 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003738 case 2:
3739 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003740 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003741 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003742 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003743 case 3:
3744 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003745 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003746 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003747 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003748 case 4:
3749 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003750 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003751 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003752 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003753 case 5:
3754 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003755 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003756 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003757 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003758 case 6:
3759 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003760 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003761 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003762 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003763 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003764 }
3765}
3766
Chris Lattner2972b822008-11-16 04:55:20 +00003767/// PredicatesFoldable - Return true if both predicates match sign or if at
3768/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003769static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003770 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3771 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3772 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003773}
3774
3775namespace {
3776// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3777struct FoldICmpLogical {
3778 InstCombiner &IC;
3779 Value *LHS, *RHS;
3780 ICmpInst::Predicate pred;
3781 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3782 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3783 pred(ICI->getPredicate()) {}
3784 bool shouldApply(Value *V) const {
3785 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3786 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003787 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3788 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003789 return false;
3790 }
3791 Instruction *apply(Instruction &Log) const {
3792 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3793 if (ICI->getOperand(0) != LHS) {
3794 assert(ICI->getOperand(1) == LHS);
3795 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3796 }
3797
3798 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3799 unsigned LHSCode = getICmpCode(ICI);
3800 unsigned RHSCode = getICmpCode(RHSICI);
3801 unsigned Code;
3802 switch (Log.getOpcode()) {
3803 case Instruction::And: Code = LHSCode & RHSCode; break;
3804 case Instruction::Or: Code = LHSCode | RHSCode; break;
3805 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003806 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003807 }
3808
Nick Lewyckyb0796c62009-10-25 05:20:17 +00003809 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Anderson24be4c12009-07-03 00:17:18 +00003810 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003811 if (Instruction *I = dyn_cast<Instruction>(RV))
3812 return I;
3813 // Otherwise, it's a constant boolean value...
3814 return IC.ReplaceInstUsesWith(Log, RV);
3815 }
3816};
3817} // end anonymous namespace
3818
3819// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3820// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3821// guaranteed to be a binary operator.
3822Instruction *InstCombiner::OptAndOp(Instruction *Op,
3823 ConstantInt *OpRHS,
3824 ConstantInt *AndRHS,
3825 BinaryOperator &TheAnd) {
3826 Value *X = Op->getOperand(0);
3827 Constant *Together = 0;
3828 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00003829 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003830
3831 switch (Op->getOpcode()) {
3832 case Instruction::Xor:
3833 if (Op->hasOneUse()) {
3834 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattnerc7694852009-08-30 07:44:24 +00003835 Value *And = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003836 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003837 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003838 }
3839 break;
3840 case Instruction::Or:
3841 if (Together == AndRHS) // (X | C) & C --> C
3842 return ReplaceInstUsesWith(TheAnd, AndRHS);
3843
3844 if (Op->hasOneUse() && Together != OpRHS) {
3845 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattnerc7694852009-08-30 07:44:24 +00003846 Value *Or = Builder->CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003847 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003848 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003849 }
3850 break;
3851 case Instruction::Add:
3852 if (Op->hasOneUse()) {
3853 // Adding a one to a single bit bit-field should be turned into an XOR
3854 // of the bit. First thing to check is to see if this AND is with a
3855 // single bit constant.
3856 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3857
3858 // If there is only one bit set...
3859 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3860 // Ok, at this point, we know that we are masking the result of the
3861 // ADD down to exactly one bit. If the constant we are adding has
3862 // no bits set below this bit, then we can eliminate the ADD.
3863 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3864
3865 // Check to see if any bits below the one bit set in AndRHSV are set.
3866 if ((AddRHS & (AndRHSV-1)) == 0) {
3867 // If not, the only thing that can effect the output of the AND is
3868 // the bit specified by AndRHSV. If that bit is set, the effect of
3869 // the XOR is to toggle the bit. If it is clear, then the ADD has
3870 // no effect.
3871 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3872 TheAnd.setOperand(0, X);
3873 return &TheAnd;
3874 } else {
3875 // Pull the XOR out of the AND.
Chris Lattnerc7694852009-08-30 07:44:24 +00003876 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003877 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003878 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003879 }
3880 }
3881 }
3882 }
3883 break;
3884
3885 case Instruction::Shl: {
3886 // We know that the AND will not produce any of the bits shifted in, so if
3887 // the anded constant includes them, clear them now!
3888 //
3889 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3890 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3891 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003892 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003893
3894 if (CI->getValue() == ShlMask) {
3895 // Masking out bits that the shift already masks
3896 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3897 } else if (CI != AndRHS) { // Reducing bits set in and.
3898 TheAnd.setOperand(1, CI);
3899 return &TheAnd;
3900 }
3901 break;
3902 }
3903 case Instruction::LShr:
3904 {
3905 // We know that the AND will not produce any of the bits shifted in, so if
3906 // the anded constant includes them, clear them now! This only applies to
3907 // unsigned shifts, because a signed shr may bring in set bits!
3908 //
3909 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3910 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3911 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003912 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003913
3914 if (CI->getValue() == ShrMask) {
3915 // Masking out bits that the shift already masks.
3916 return ReplaceInstUsesWith(TheAnd, Op);
3917 } else if (CI != AndRHS) {
3918 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3919 return &TheAnd;
3920 }
3921 break;
3922 }
3923 case Instruction::AShr:
3924 // Signed shr.
3925 // See if this is shifting in some sign extension, then masking it out
3926 // with an and.
3927 if (Op->hasOneUse()) {
3928 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3929 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3930 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003931 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003932 if (C == AndRHS) { // Masking out bits shifted in.
3933 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3934 // Make the argument unsigned.
3935 Value *ShVal = Op->getOperand(0);
Chris Lattnerc7694852009-08-30 07:44:24 +00003936 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00003937 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003938 }
3939 }
3940 break;
3941 }
3942 return 0;
3943}
3944
3945
3946/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3947/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3948/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3949/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3950/// insert new instructions.
3951Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3952 bool isSigned, bool Inside,
3953 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003954 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003955 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3956 "Lo is not <= Hi in range emission code!");
3957
3958 if (Inside) {
3959 if (Lo == Hi) // Trivially false.
Dan Gohmane6803b82009-08-25 23:17:54 +00003960 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003961
3962 // V >= Min && V < Hi --> V < Hi
3963 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3964 ICmpInst::Predicate pred = (isSigned ?
3965 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003966 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003967 }
3968
3969 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00003970 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattnerc7694852009-08-30 07:44:24 +00003971 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003972 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003973 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003974 }
3975
3976 if (Lo == Hi) // Trivially true.
Dan Gohmane6803b82009-08-25 23:17:54 +00003977 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003978
3979 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003980 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003981 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3982 ICmpInst::Predicate pred = (isSigned ?
3983 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003984 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003985 }
3986
3987 // Emit V-Lo >u Hi-1-Lo
3988 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00003989 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattnerc7694852009-08-30 07:44:24 +00003990 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Anderson02b48c32009-07-29 18:55:55 +00003991 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003992 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003993}
3994
3995// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3996// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3997// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3998// not, since all 1s are not contiguous.
3999static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
4000 const APInt& V = Val->getValue();
4001 uint32_t BitWidth = Val->getType()->getBitWidth();
4002 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
4003
4004 // look for the first zero bit after the run of ones
4005 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
4006 // look for the first non-zero bit
4007 ME = V.getActiveBits();
4008 return true;
4009}
4010
4011/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4012/// where isSub determines whether the operator is a sub. If we can fold one of
4013/// the following xforms:
4014///
4015/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4016/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4017/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4018///
4019/// return (A +/- B).
4020///
4021Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
4022 ConstantInt *Mask, bool isSub,
4023 Instruction &I) {
4024 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4025 if (!LHSI || LHSI->getNumOperands() != 2 ||
4026 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4027
4028 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4029
4030 switch (LHSI->getOpcode()) {
4031 default: return 0;
4032 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00004033 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004034 // If the AndRHS is a power of two minus one (0+1+), this is simple.
4035 if ((Mask->getValue().countLeadingZeros() +
4036 Mask->getValue().countPopulation()) ==
4037 Mask->getValue().getBitWidth())
4038 break;
4039
4040 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4041 // part, we don't need any explicit masks to take them out of A. If that
4042 // is all N is, ignore it.
4043 uint32_t MB = 0, ME = 0;
4044 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
4045 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4046 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4047 if (MaskedValueIsZero(RHS, Mask))
4048 break;
4049 }
4050 }
4051 return 0;
4052 case Instruction::Or:
4053 case Instruction::Xor:
4054 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4055 if ((Mask->getValue().countLeadingZeros() +
4056 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00004057 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004058 break;
4059 return 0;
4060 }
4061
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004062 if (isSub)
Chris Lattnerc7694852009-08-30 07:44:24 +00004063 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4064 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004065}
4066
Chris Lattner0631ea72008-11-16 05:06:21 +00004067/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4068Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4069 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00004070 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00004071 ConstantInt *LHSCst, *RHSCst;
4072 ICmpInst::Predicate LHSCC, RHSCC;
4073
Chris Lattnerf3803482008-11-16 05:10:52 +00004074 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004075 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004076 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004077 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004078 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00004079 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00004080
4081 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4082 // where C is a power of 2
4083 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
4084 LHSCst->getValue().isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004085 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohmane6803b82009-08-25 23:17:54 +00004086 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerf3803482008-11-16 05:10:52 +00004087 }
4088
4089 // From here on, we only handle:
4090 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4091 if (Val != Val2) return 0;
4092
Chris Lattner0631ea72008-11-16 05:06:21 +00004093 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4094 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4095 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4096 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4097 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4098 return 0;
4099
4100 // We can't fold (ugt x, C) & (sgt x, C2).
4101 if (!PredicatesFoldable(LHSCC, RHSCC))
4102 return 0;
4103
4104 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00004105 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004106 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0631ea72008-11-16 05:06:21 +00004107 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004108 CmpInst::isSigned(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00004109 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00004110 else
Chris Lattner665298f2008-11-16 05:14:43 +00004111 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4112
4113 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00004114 std::swap(LHS, RHS);
4115 std::swap(LHSCst, RHSCst);
4116 std::swap(LHSCC, RHSCC);
4117 }
4118
4119 // At this point, we know we have have two icmp instructions
4120 // comparing a value against two constants and and'ing the result
4121 // together. Because of the above check, we know that we only have
4122 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4123 // (from the FoldICmpLogical check above), that the two constants
4124 // are not equal and that the larger constant is on the RHS
4125 assert(LHSCst != RHSCst && "Compares not folded above?");
4126
4127 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004128 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004129 case ICmpInst::ICMP_EQ:
4130 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004131 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004132 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4133 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4134 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004135 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004136 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4137 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4138 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4139 return ReplaceInstUsesWith(I, LHS);
4140 }
4141 case ICmpInst::ICMP_NE:
4142 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004143 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004144 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004145 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00004146 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004147 break; // (X != 13 & X u< 15) -> no change
4148 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004149 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00004150 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004151 break; // (X != 13 & X s< 15) -> no change
4152 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4153 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4154 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4155 return ReplaceInstUsesWith(I, RHS);
4156 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004157 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00004158 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004159 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmane6803b82009-08-25 23:17:54 +00004160 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004161 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00004162 }
4163 break; // (X != 13 & X != 15) -> no change
4164 }
4165 break;
4166 case ICmpInst::ICMP_ULT:
4167 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004168 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004169 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4170 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004171 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004172 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4173 break;
4174 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4175 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4176 return ReplaceInstUsesWith(I, LHS);
4177 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4178 break;
4179 }
4180 break;
4181 case ICmpInst::ICMP_SLT:
4182 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004183 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004184 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4185 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00004186 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00004187 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4188 break;
4189 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4190 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4191 return ReplaceInstUsesWith(I, LHS);
4192 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4193 break;
4194 }
4195 break;
4196 case ICmpInst::ICMP_UGT:
4197 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004198 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004199 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4200 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4201 return ReplaceInstUsesWith(I, RHS);
4202 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4203 break;
4204 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004205 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00004206 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004207 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00004208 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004209 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004210 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00004211 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4212 break;
4213 }
4214 break;
4215 case ICmpInst::ICMP_SGT:
4216 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004217 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00004218 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4219 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4220 return ReplaceInstUsesWith(I, RHS);
4221 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4222 break;
4223 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004224 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00004225 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00004226 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00004227 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004228 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004229 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00004230 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4231 break;
4232 }
4233 break;
4234 }
Chris Lattner0631ea72008-11-16 05:06:21 +00004235
4236 return 0;
4237}
4238
Chris Lattner93a359a2009-07-23 05:14:02 +00004239Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4240 FCmpInst *RHS) {
4241
4242 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4243 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4244 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4245 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4246 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4247 // If either of the constants are nans, then the whole thing returns
4248 // false.
4249 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004250 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00004251 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner93a359a2009-07-23 05:14:02 +00004252 LHS->getOperand(0), RHS->getOperand(0));
4253 }
Chris Lattnercf373552009-07-23 05:32:17 +00004254
4255 // Handle vector zeros. This occurs because the canonical form of
4256 // "fcmp ord x,x" is "fcmp ord x, 0".
4257 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4258 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004259 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnercf373552009-07-23 05:32:17 +00004260 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00004261 return 0;
4262 }
4263
4264 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4265 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4266 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4267
4268
4269 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4270 // Swap RHS operands to match LHS.
4271 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4272 std::swap(Op1LHS, Op1RHS);
4273 }
4274
4275 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4276 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4277 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004278 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +00004279
4280 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004281 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004282 if (Op0CC == FCmpInst::FCMP_TRUE)
4283 return ReplaceInstUsesWith(I, RHS);
4284 if (Op1CC == FCmpInst::FCMP_TRUE)
4285 return ReplaceInstUsesWith(I, LHS);
4286
4287 bool Op0Ordered;
4288 bool Op1Ordered;
4289 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4290 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4291 if (Op1Pred == 0) {
4292 std::swap(LHS, RHS);
4293 std::swap(Op0Pred, Op1Pred);
4294 std::swap(Op0Ordered, Op1Ordered);
4295 }
4296 if (Op0Pred == 0) {
4297 // uno && ueq -> uno && (uno || eq) -> ueq
4298 // ord && olt -> ord && (ord && lt) -> olt
4299 if (Op0Ordered == Op1Ordered)
4300 return ReplaceInstUsesWith(I, RHS);
4301
4302 // uno && oeq -> uno && (ord && eq) -> false
4303 // uno && ord -> false
4304 if (!Op0Ordered)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004305 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004306 // ord && ueq -> ord && (uno || eq) -> oeq
4307 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4308 Op0LHS, Op0RHS, Context));
4309 }
4310 }
4311
4312 return 0;
4313}
4314
Chris Lattner0631ea72008-11-16 05:06:21 +00004315
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004316Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4317 bool Changed = SimplifyCommutative(I);
4318 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4319
Chris Lattnera3e46f62009-11-10 00:55:12 +00004320 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4321 return ReplaceInstUsesWith(I, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004322
4323 // See if we can simplify any instructions used by the instruction whose sole
4324 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004325 if (SimplifyDemandedInstructionBits(I))
4326 return &I;
Chris Lattnera3e46f62009-11-10 00:55:12 +00004327
Dan Gohman8fd520a2009-06-15 22:12:54 +00004328
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004329 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00004330 const APInt &AndRHSMask = AndRHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004331 APInt NotAndRHS(~AndRHSMask);
4332
4333 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner4580d452009-10-11 22:00:32 +00004334 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004335 Value *Op0LHS = Op0I->getOperand(0);
4336 Value *Op0RHS = Op0I->getOperand(1);
4337 switch (Op0I->getOpcode()) {
Chris Lattner4580d452009-10-11 22:00:32 +00004338 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004339 case Instruction::Xor:
4340 case Instruction::Or:
4341 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner4580d452009-10-11 22:00:32 +00004342 if (!Op0I->hasOneUse()) break;
4343
4344 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4345 // Not masking anything out for the LHS, move to RHS.
4346 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4347 Op0RHS->getName()+".masked");
4348 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4349 }
4350 if (!isa<Constant>(Op0RHS) &&
4351 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4352 // Not masking anything out for the RHS, move to LHS.
4353 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4354 Op0LHS->getName()+".masked");
4355 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004356 }
4357
4358 break;
4359 case Instruction::Add:
4360 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4361 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4362 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4363 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004364 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004365 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004366 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004367 break;
4368
4369 case Instruction::Sub:
4370 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4371 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4372 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4373 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004374 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004375
Nick Lewyckya349ba42008-07-10 05:51:40 +00004376 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4377 // has 1's for all bits that the subtraction with A might affect.
4378 if (Op0I->hasOneUse()) {
4379 uint32_t BitWidth = AndRHSMask.getBitWidth();
4380 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4381 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4382
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004383 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004384 if (!(A && A->isZero()) && // avoid infinite recursion.
4385 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004386 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004387 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4388 }
4389 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004390 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004391
4392 case Instruction::Shl:
4393 case Instruction::LShr:
4394 // (1 << x) & 1 --> zext(x == 0)
4395 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004396 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004397 Value *NewICmp =
4398 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004399 return new ZExtInst(NewICmp, I.getType());
4400 }
4401 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004402 }
4403
4404 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4405 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4406 return Res;
4407 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4408 // If this is an integer truncation or change from signed-to-unsigned, and
4409 // if the source is an and/or with immediate, transform it. This
4410 // frequently occurs for bitfield accesses.
4411 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4412 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4413 CastOp->getNumOperands() == 2)
Chris Lattner6e060db2009-10-26 15:40:07 +00004414 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004415 if (CastOp->getOpcode() == Instruction::And) {
4416 // Change: and (cast (and X, C1) to T), C2
4417 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4418 // This will fold the two constants together, which may allow
4419 // other simplifications.
Chris Lattnerc7694852009-08-30 07:44:24 +00004420 Value *NewCast = Builder->CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004421 CastOp->getOperand(0), I.getType(),
4422 CastOp->getName()+".shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004423 // trunc_or_bitcast(C1)&C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004424 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004425 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004426 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004427 } else if (CastOp->getOpcode() == Instruction::Or) {
4428 // Change: and (cast (or X, C1) to T), C2
4429 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerc7694852009-08-30 07:44:24 +00004430 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Anderson02b48c32009-07-29 18:55:55 +00004431 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00004432 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004433 return ReplaceInstUsesWith(I, AndRHS);
4434 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004435 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004436 }
4437 }
4438
4439 // Try to fold constant and into select arguments.
4440 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4441 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4442 return R;
4443 if (isa<PHINode>(Op0))
4444 if (Instruction *NV = FoldOpIntoPhi(I))
4445 return NV;
4446 }
4447
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004448
4449 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnera3e46f62009-11-10 00:55:12 +00004450 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4451 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4452 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4453 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4454 I.getName()+".demorgan");
4455 return BinaryOperator::CreateNot(Or);
4456 }
4457
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004458 {
4459 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnera3e46f62009-11-10 00:55:12 +00004460 // (A|B) & ~(A&B) -> A^B
4461 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4462 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4463 ((A == C && B == D) || (A == D && B == C)))
4464 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004465
Chris Lattnera3e46f62009-11-10 00:55:12 +00004466 // ~(A&B) & (A|B) -> A^B
4467 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4468 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4469 ((A == C && B == D) || (A == D && B == C)))
4470 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004471
4472 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004473 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004474 if (A == Op1) { // (A^B)&A -> A&(A^B)
4475 I.swapOperands(); // Simplify below
4476 std::swap(Op0, Op1);
4477 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4478 cast<BinaryOperator>(Op0)->swapOperands();
4479 I.swapOperands(); // Simplify below
4480 std::swap(Op0, Op1);
4481 }
4482 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004483
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004484 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004485 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004486 if (B == Op0) { // B&(A^B) -> B&(B^A)
4487 cast<BinaryOperator>(Op1)->swapOperands();
4488 std::swap(A, B);
4489 }
Chris Lattnerc7694852009-08-30 07:44:24 +00004490 if (A == Op0) // A&(A^B) -> A & ~B
4491 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004492 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004493
4494 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00004495 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4496 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004497 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004498 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4499 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004500 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004501 }
4502
4503 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4504 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004505 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004506 return R;
4507
Chris Lattner0631ea72008-11-16 05:06:21 +00004508 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4509 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4510 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004511 }
4512
4513 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4514 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4515 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4516 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4517 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004518 if (SrcTy == Op1C->getOperand(0)->getType() &&
4519 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004520 // Only do this if the casts both really cause code to be generated.
4521 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4522 I.getType(), TD) &&
4523 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4524 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004525 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4526 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004527 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004528 }
4529 }
4530
4531 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4532 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4533 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4534 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4535 SI0->getOperand(1) == SI1->getOperand(1) &&
4536 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004537 Value *NewOp =
4538 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4539 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00004540 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004541 SI1->getOperand(1));
4542 }
4543 }
4544
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004545 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004546 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004547 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4548 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4549 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004550 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004551
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004552 return Changed ? &I : 0;
4553}
4554
Chris Lattner567f5112008-10-05 02:13:19 +00004555/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4556/// capable of providing pieces of a bswap. The subexpression provides pieces
4557/// of a bswap if it is proven that each of the non-zero bytes in the output of
4558/// the expression came from the corresponding "byte swapped" byte in some other
4559/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4560/// we know that the expression deposits the low byte of %X into the high byte
4561/// of the bswap result and that all other bytes are zero. This expression is
4562/// accepted, the high byte of ByteValues is set to X to indicate a correct
4563/// match.
4564///
4565/// This function returns true if the match was unsuccessful and false if so.
4566/// On entry to the function the "OverallLeftShift" is a signed integer value
4567/// indicating the number of bytes that the subexpression is later shifted. For
4568/// example, if the expression is later right shifted by 16 bits, the
4569/// OverallLeftShift value would be -2 on entry. This is used to specify which
4570/// byte of ByteValues is actually being set.
4571///
4572/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4573/// byte is masked to zero by a user. For example, in (X & 255), X will be
4574/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4575/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4576/// always in the local (OverallLeftShift) coordinate space.
4577///
4578static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4579 SmallVector<Value*, 8> &ByteValues) {
4580 if (Instruction *I = dyn_cast<Instruction>(V)) {
4581 // If this is an or instruction, it may be an inner node of the bswap.
4582 if (I->getOpcode() == Instruction::Or) {
4583 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4584 ByteValues) ||
4585 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4586 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004587 }
Chris Lattner567f5112008-10-05 02:13:19 +00004588
4589 // If this is a logical shift by a constant multiple of 8, recurse with
4590 // OverallLeftShift and ByteMask adjusted.
4591 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4592 unsigned ShAmt =
4593 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4594 // Ensure the shift amount is defined and of a byte value.
4595 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4596 return true;
4597
4598 unsigned ByteShift = ShAmt >> 3;
4599 if (I->getOpcode() == Instruction::Shl) {
4600 // X << 2 -> collect(X, +2)
4601 OverallLeftShift += ByteShift;
4602 ByteMask >>= ByteShift;
4603 } else {
4604 // X >>u 2 -> collect(X, -2)
4605 OverallLeftShift -= ByteShift;
4606 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004607 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004608 }
4609
4610 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4611 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4612
4613 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4614 ByteValues);
4615 }
4616
4617 // If this is a logical 'and' with a mask that clears bytes, clear the
4618 // corresponding bytes in ByteMask.
4619 if (I->getOpcode() == Instruction::And &&
4620 isa<ConstantInt>(I->getOperand(1))) {
4621 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4622 unsigned NumBytes = ByteValues.size();
4623 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4624 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4625
4626 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4627 // If this byte is masked out by a later operation, we don't care what
4628 // the and mask is.
4629 if ((ByteMask & (1 << i)) == 0)
4630 continue;
4631
4632 // If the AndMask is all zeros for this byte, clear the bit.
4633 APInt MaskB = AndMask & Byte;
4634 if (MaskB == 0) {
4635 ByteMask &= ~(1U << i);
4636 continue;
4637 }
4638
4639 // If the AndMask is not all ones for this byte, it's not a bytezap.
4640 if (MaskB != Byte)
4641 return true;
4642
4643 // Otherwise, this byte is kept.
4644 }
4645
4646 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4647 ByteValues);
4648 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004649 }
4650
Chris Lattner567f5112008-10-05 02:13:19 +00004651 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4652 // the input value to the bswap. Some observations: 1) if more than one byte
4653 // is demanded from this input, then it could not be successfully assembled
4654 // into a byteswap. At least one of the two bytes would not be aligned with
4655 // their ultimate destination.
4656 if (!isPowerOf2_32(ByteMask)) return true;
4657 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004658
Chris Lattner567f5112008-10-05 02:13:19 +00004659 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4660 // is demanded, it needs to go into byte 0 of the result. This means that the
4661 // byte needs to be shifted until it lands in the right byte bucket. The
4662 // shift amount depends on the position: if the byte is coming from the high
4663 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4664 // low part, it must be shifted left.
4665 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4666 if (InputByteNo < ByteValues.size()/2) {
4667 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4668 return true;
4669 } else {
4670 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4671 return true;
4672 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004673
4674 // If the destination byte value is already defined, the values are or'd
4675 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004676 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004677 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004678 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004679 return false;
4680}
4681
4682/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4683/// If so, insert the new bswap intrinsic and return it.
4684Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4685 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004686 if (!ITy || ITy->getBitWidth() % 16 ||
4687 // ByteMask only allows up to 32-byte values.
4688 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004689 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4690
4691 /// ByteValues - For each byte of the result, we keep track of which value
4692 /// defines each byte.
4693 SmallVector<Value*, 8> ByteValues;
4694 ByteValues.resize(ITy->getBitWidth()/8);
4695
4696 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004697 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4698 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004699 return 0;
4700
4701 // Check to see if all of the bytes come from the same value.
4702 Value *V = ByteValues[0];
4703 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4704
4705 // Check to make sure that all of the bytes come from the same value.
4706 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4707 if (ByteValues[i] != V)
4708 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004709 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004710 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004711 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004712 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004713}
4714
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004715/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4716/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4717/// we can simplify this expression to "cond ? C : D or B".
4718static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004719 Value *C, Value *D,
4720 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004721 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004722 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004723 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004724 return 0;
4725
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004726 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00004727 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004728 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00004729 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004730 return SelectInst::Create(Cond, C, B);
4731 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00004732 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004733 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00004734 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004735 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004736 return 0;
4737}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004738
Chris Lattner0c678e52008-11-16 05:20:07 +00004739/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4740Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4741 ICmpInst *LHS, ICmpInst *RHS) {
4742 Value *Val, *Val2;
4743 ConstantInt *LHSCst, *RHSCst;
4744 ICmpInst::Predicate LHSCC, RHSCC;
4745
4746 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004747 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004748 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004749 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004750 m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00004751 return 0;
4752
4753 // From here on, we only handle:
4754 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4755 if (Val != Val2) return 0;
4756
4757 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4758 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4759 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4760 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4761 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4762 return 0;
4763
4764 // We can't fold (ugt x, C) | (sgt x, C2).
4765 if (!PredicatesFoldable(LHSCC, RHSCC))
4766 return 0;
4767
4768 // Ensure that the larger constant is on the RHS.
4769 bool ShouldSwap;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004770 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner0c678e52008-11-16 05:20:07 +00004771 (ICmpInst::isEquality(LHSCC) &&
Nick Lewyckyb0796c62009-10-25 05:20:17 +00004772 CmpInst::isSigned(RHSCC)))
Chris Lattner0c678e52008-11-16 05:20:07 +00004773 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4774 else
4775 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4776
4777 if (ShouldSwap) {
4778 std::swap(LHS, RHS);
4779 std::swap(LHSCst, RHSCst);
4780 std::swap(LHSCC, RHSCC);
4781 }
4782
4783 // At this point, we know we have have two icmp instructions
4784 // comparing a value against two constants and or'ing the result
4785 // together. Because of the above check, we know that we only have
4786 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4787 // FoldICmpLogical check above), that the two constants are not
4788 // equal.
4789 assert(LHSCst != RHSCst && "Compares not folded above?");
4790
4791 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004792 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004793 case ICmpInst::ICMP_EQ:
4794 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004795 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004796 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004797 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004798 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00004799 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattnerc7694852009-08-30 07:44:24 +00004800 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004801 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohmane6803b82009-08-25 23:17:54 +00004802 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004803 }
4804 break; // (X == 13 | X == 15) -> no change
4805 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4806 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4807 break;
4808 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4809 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4810 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4811 return ReplaceInstUsesWith(I, RHS);
4812 }
4813 break;
4814 case ICmpInst::ICMP_NE:
4815 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004816 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004817 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4818 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4819 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4820 return ReplaceInstUsesWith(I, LHS);
4821 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4822 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4823 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004824 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004825 }
4826 break;
4827 case ICmpInst::ICMP_ULT:
4828 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004829 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004830 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4831 break;
4832 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4833 // If RHSCst is [us]MAXINT, it is always false. Not handling
4834 // this can cause overflow.
4835 if (RHSCst->isMaxValue(false))
4836 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004837 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004838 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004839 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4840 break;
4841 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4842 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4843 return ReplaceInstUsesWith(I, RHS);
4844 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4845 break;
4846 }
4847 break;
4848 case ICmpInst::ICMP_SLT:
4849 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004850 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004851 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4852 break;
4853 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4854 // If RHSCst is [us]MAXINT, it is always false. Not handling
4855 // this can cause overflow.
4856 if (RHSCst->isMaxValue(true))
4857 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004858 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004859 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004860 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4861 break;
4862 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4863 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4864 return ReplaceInstUsesWith(I, RHS);
4865 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4866 break;
4867 }
4868 break;
4869 case ICmpInst::ICMP_UGT:
4870 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004871 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004872 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4873 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4874 return ReplaceInstUsesWith(I, LHS);
4875 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4876 break;
4877 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4878 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004879 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004880 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4881 break;
4882 }
4883 break;
4884 case ICmpInst::ICMP_SGT:
4885 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004886 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004887 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4888 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4889 return ReplaceInstUsesWith(I, LHS);
4890 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4891 break;
4892 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4893 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004894 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004895 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4896 break;
4897 }
4898 break;
4899 }
4900 return 0;
4901}
4902
Chris Lattner57e66fa2009-07-23 05:46:22 +00004903Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4904 FCmpInst *RHS) {
4905 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4906 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4907 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4908 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4909 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4910 // If either of the constants are nans, then the whole thing returns
4911 // true.
4912 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004913 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004914
4915 // Otherwise, no need to compare the two constants, compare the
4916 // rest.
Dan Gohmane6803b82009-08-25 23:17:54 +00004917 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004918 LHS->getOperand(0), RHS->getOperand(0));
4919 }
4920
4921 // Handle vector zeros. This occurs because the canonical form of
4922 // "fcmp uno x,x" is "fcmp uno x, 0".
4923 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4924 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004925 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004926 LHS->getOperand(0), RHS->getOperand(0));
4927
4928 return 0;
4929 }
4930
4931 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4932 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4933 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4934
4935 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4936 // Swap RHS operands to match LHS.
4937 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4938 std::swap(Op1LHS, Op1RHS);
4939 }
4940 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4941 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4942 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004943 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004944 Op0LHS, Op0RHS);
4945 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004946 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004947 if (Op0CC == FCmpInst::FCMP_FALSE)
4948 return ReplaceInstUsesWith(I, RHS);
4949 if (Op1CC == FCmpInst::FCMP_FALSE)
4950 return ReplaceInstUsesWith(I, LHS);
4951 bool Op0Ordered;
4952 bool Op1Ordered;
4953 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4954 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4955 if (Op0Ordered == Op1Ordered) {
4956 // If both are ordered or unordered, return a new fcmp with
4957 // or'ed predicates.
4958 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4959 Op0LHS, Op0RHS, Context);
4960 if (Instruction *I = dyn_cast<Instruction>(RV))
4961 return I;
4962 // Otherwise, it's a constant boolean value...
4963 return ReplaceInstUsesWith(I, RV);
4964 }
4965 }
4966 return 0;
4967}
4968
Bill Wendlingdae376a2008-12-01 08:23:25 +00004969/// FoldOrWithConstants - This helper function folds:
4970///
Bill Wendling236a1192008-12-02 05:09:00 +00004971/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004972///
4973/// into:
4974///
Bill Wendling236a1192008-12-02 05:09:00 +00004975/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004976///
Bill Wendling236a1192008-12-02 05:09:00 +00004977/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004978Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004979 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004980 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4981 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004982
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004983 Value *V1 = 0;
4984 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004985 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004986
Bill Wendling86ee3162008-12-02 06:18:11 +00004987 APInt Xor = CI1->getValue() ^ CI2->getValue();
4988 if (!Xor.isAllOnesValue()) return 0;
4989
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004990 if (V1 == A || V1 == B) {
Chris Lattnerc7694852009-08-30 07:44:24 +00004991 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004992 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004993 }
4994
4995 return 0;
4996}
4997
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004998Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4999 bool Changed = SimplifyCommutative(I);
5000 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5001
Chris Lattnera3e46f62009-11-10 00:55:12 +00005002 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5003 return ReplaceInstUsesWith(I, V);
5004
5005
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005006 // See if we can simplify any instructions used by the instruction whose sole
5007 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005008 if (SimplifyDemandedInstructionBits(I))
5009 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005010
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005011 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5012 ConstantInt *C1 = 0; Value *X = 0;
5013 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00005014 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005015 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005016 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005017 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005018 return BinaryOperator::CreateAnd(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005019 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005020 }
5021
5022 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00005023 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005024 isOnlyUse(Op0)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005025 Value *Or = Builder->CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005026 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005027 return BinaryOperator::CreateXor(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005028 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005029 }
5030
5031 // Try to fold constant and into select arguments.
5032 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5033 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5034 return R;
5035 if (isa<PHINode>(Op0))
5036 if (Instruction *NV = FoldOpIntoPhi(I))
5037 return NV;
5038 }
5039
5040 Value *A = 0, *B = 0;
5041 ConstantInt *C1 = 0, *C2 = 0;
5042
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005043 // (A | B) | C and A | (B | C) -> bswap if possible.
5044 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00005045 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5046 match(Op1, m_Or(m_Value(), m_Value())) ||
5047 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5048 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005049 if (Instruction *BSwap = MatchBSwap(I))
5050 return BSwap;
5051 }
5052
5053 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00005054 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005055 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005056 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005057 Value *NOr = Builder->CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005058 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005059 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005060 }
5061
5062 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00005063 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005064 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005065 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005066 Value *NOr = Builder->CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005067 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00005068 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005069 }
5070
5071 // (A & C)|(B & D)
5072 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00005073 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5074 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005075 Value *V1 = 0, *V2 = 0, *V3 = 0;
5076 C1 = dyn_cast<ConstantInt>(C);
5077 C2 = dyn_cast<ConstantInt>(D);
5078 if (C1 && C2) { // (A & C1)|(B & C2)
5079 // If we have: ((V + N) & C1) | (V & C2)
5080 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5081 // replace with V+N.
5082 if (C1->getValue() == ~C2->getValue()) {
5083 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohmancdff2122009-08-12 16:23:25 +00005084 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005085 // Add commutes, try both ways.
5086 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5087 return ReplaceInstUsesWith(I, A);
5088 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5089 return ReplaceInstUsesWith(I, A);
5090 }
5091 // Or commutes, try both ways.
5092 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005093 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005094 // Add commutes, try both ways.
5095 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5096 return ReplaceInstUsesWith(I, B);
5097 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5098 return ReplaceInstUsesWith(I, B);
5099 }
5100 }
5101 V1 = 0; V2 = 0; V3 = 0;
5102 }
5103
5104 // Check to see if we have any common things being and'ed. If so, find the
5105 // terms for V1 & (V2|V3).
5106 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5107 if (A == B) // (A & C)|(A & D) == A & (C|D)
5108 V1 = A, V2 = C, V3 = D;
5109 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5110 V1 = A, V2 = B, V3 = C;
5111 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5112 V1 = C, V2 = A, V3 = D;
5113 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5114 V1 = C, V2 = A, V3 = B;
5115
5116 if (V1) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005117 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00005118 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005119 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005120 }
Dan Gohman279952c2008-10-28 22:38:57 +00005121
Dan Gohman35b76162008-10-30 20:40:10 +00005122 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00005123 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005124 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005125 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005126 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005127 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005128 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00005129 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00005130 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00005131
Bill Wendling22ca8352008-11-30 13:52:49 +00005132 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005133 if ((match(C, m_Not(m_Specific(D))) &&
5134 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005135 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00005136 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005137 if ((match(A, m_Not(m_Specific(D))) &&
5138 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005139 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00005140 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005141 if ((match(C, m_Not(m_Specific(B))) &&
5142 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005143 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00005144 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00005145 if ((match(A, m_Not(m_Specific(B))) &&
5146 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00005147 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005148 }
5149
5150 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
5151 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5152 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5153 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
5154 SI0->getOperand(1) == SI1->getOperand(1) &&
5155 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005156 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5157 SI0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005158 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005159 SI1->getOperand(1));
5160 }
5161 }
5162
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005163 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00005164 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5165 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00005166 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005167 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005168 }
5169 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00005170 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5171 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00005172 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00005173 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00005174 }
5175
Chris Lattnera3e46f62009-11-10 00:55:12 +00005176 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5177 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5178 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5179 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5180 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5181 I.getName()+".demorgan");
5182 return BinaryOperator::CreateNot(And);
5183 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005184
5185 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5186 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005187 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005188 return R;
5189
Chris Lattner0c678e52008-11-16 05:20:07 +00005190 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5191 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5192 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005193 }
5194
5195 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005196 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005197 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5198 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00005199 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5200 !isa<ICmpInst>(Op1C->getOperand(0))) {
5201 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00005202 if (SrcTy == Op1C->getOperand(0)->getType() &&
5203 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00005204 // Only do this if the casts both really cause code to be
5205 // generated.
5206 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5207 I.getType(), TD) &&
5208 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5209 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005210 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5211 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005212 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00005213 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005214 }
5215 }
Chris Lattner91882432007-10-24 05:38:08 +00005216 }
5217
5218
5219 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5220 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00005221 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5222 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5223 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00005224 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005225
5226 return Changed ? &I : 0;
5227}
5228
Dan Gohman089efff2008-05-13 00:00:25 +00005229namespace {
5230
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005231// XorSelf - Implements: X ^ X --> 0
5232struct XorSelf {
5233 Value *RHS;
5234 XorSelf(Value *rhs) : RHS(rhs) {}
5235 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5236 Instruction *apply(BinaryOperator &Xor) const {
5237 return &Xor;
5238 }
5239};
5240
Dan Gohman089efff2008-05-13 00:00:25 +00005241}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005242
5243Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5244 bool Changed = SimplifyCommutative(I);
5245 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5246
Evan Chenge5cd8032008-03-25 20:07:13 +00005247 if (isa<UndefValue>(Op1)) {
5248 if (isa<UndefValue>(Op0))
5249 // Handle undef ^ undef -> 0 special case. This is a common
5250 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00005251 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005252 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005253 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005254
5255 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005256 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005257 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00005258 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005259 }
5260
5261 // See if we can simplify any instructions used by the instruction whose sole
5262 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005263 if (SimplifyDemandedInstructionBits(I))
5264 return &I;
5265 if (isa<VectorType>(I.getType()))
5266 if (isa<ConstantAggregateZero>(Op1))
5267 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005268
5269 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005270 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005271 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5272 if (Op0I->getOpcode() == Instruction::And ||
5273 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner6e060db2009-10-26 15:40:07 +00005274 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5275 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5276 if (dyn_castNotVal(Op0I->getOperand(1)))
5277 Op0I->swapOperands();
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005278 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005279 Value *NotY =
5280 Builder->CreateNot(Op0I->getOperand(1),
5281 Op0I->getOperand(1)->getName()+".not");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005282 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005283 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattnerc7694852009-08-30 07:44:24 +00005284 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005285 }
Chris Lattner6e060db2009-10-26 15:40:07 +00005286
5287 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5288 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5289 if (isFreeToInvert(Op0I->getOperand(0)) &&
5290 isFreeToInvert(Op0I->getOperand(1))) {
5291 Value *NotX =
5292 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5293 Value *NotY =
5294 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5295 if (Op0I->getOpcode() == Instruction::And)
5296 return BinaryOperator::CreateOr(NotX, NotY);
5297 return BinaryOperator::CreateAnd(NotX, NotY);
5298 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005299 }
5300 }
5301 }
5302
5303
5304 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4580d452009-10-11 22:00:32 +00005305 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005306 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005307 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005308 return new ICmpInst(ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005309 ICI->getOperand(0), ICI->getOperand(1));
5310
Nick Lewycky1405e922007-08-06 20:04:16 +00005311 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005312 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005313 FCI->getOperand(0), FCI->getOperand(1));
5314 }
5315
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005316 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5317 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5318 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5319 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5320 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattnerc7694852009-08-30 07:44:24 +00005321 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5322 (RHS == ConstantExpr::getCast(Opcode,
5323 ConstantInt::getTrue(*Context),
5324 Op0C->getDestTy()))) {
5325 CI->setPredicate(CI->getInversePredicate());
5326 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005327 }
5328 }
5329 }
5330 }
5331
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005332 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5333 // ~(c-X) == X-c-1 == X+(-c-1)
5334 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5335 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005336 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5337 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005338 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005339 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005340 }
5341
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005342 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005343 if (Op0I->getOpcode() == Instruction::Add) {
5344 // ~(X-c) --> (-c-1)-X
5345 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005346 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005347 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00005348 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005349 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00005350 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005351 } else if (RHS->getValue().isSignBit()) {
5352 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005353 Constant *C = ConstantInt::get(*Context,
5354 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005355 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005356
5357 }
5358 } else if (Op0I->getOpcode() == Instruction::Or) {
5359 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5360 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005361 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005362 // Anything in both C1 and C2 is known to be zero, remove it from
5363 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00005364 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5365 NewRHS = ConstantExpr::getAnd(NewRHS,
5366 ConstantExpr::getNot(CommonBits));
Chris Lattner3183fb62009-08-30 06:13:40 +00005367 Worklist.Add(Op0I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005368 I.setOperand(0, Op0I->getOperand(0));
5369 I.setOperand(1, NewRHS);
5370 return &I;
5371 }
5372 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005373 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005374 }
5375
5376 // Try to fold constant and into select arguments.
5377 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5378 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5379 return R;
5380 if (isa<PHINode>(Op0))
5381 if (Instruction *NV = FoldOpIntoPhi(I))
5382 return NV;
5383 }
5384
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005385 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005386 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00005387 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005388
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005389 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005390 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00005391 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005392
5393
5394 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5395 if (Op1I) {
5396 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005397 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005398 if (A == Op0) { // B^(B|A) == (A|B)^B
5399 Op1I->swapOperands();
5400 I.swapOperands();
5401 std::swap(Op0, Op1);
5402 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5403 I.swapOperands(); // Simplified below.
5404 std::swap(Op0, Op1);
5405 }
Dan Gohmancdff2122009-08-12 16:23:25 +00005406 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005407 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005408 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005409 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005410 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005411 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005412 if (A == Op0) { // A^(A&B) -> A^(B&A)
5413 Op1I->swapOperands();
5414 std::swap(A, B);
5415 }
5416 if (B == Op0) { // A^(B&A) -> (B&A)^A
5417 I.swapOperands(); // Simplified below.
5418 std::swap(Op0, Op1);
5419 }
5420 }
5421 }
5422
5423 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5424 if (Op0I) {
5425 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005426 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005427 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005428 if (A == Op1) // (B|A)^B == (A|B)^B
5429 std::swap(A, B);
Chris Lattnerc7694852009-08-30 07:44:24 +00005430 if (B == Op1) // (A|B)^B == A & ~B
5431 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohmancdff2122009-08-12 16:23:25 +00005432 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005433 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005434 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005435 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005436 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005437 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005438 if (A == Op1) // (A&B)^A -> (B&A)^A
5439 std::swap(A, B);
5440 if (B == Op1 && // (B&A)^A == ~B & A
5441 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerc7694852009-08-30 07:44:24 +00005442 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005443 }
5444 }
5445 }
5446
5447 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5448 if (Op0I && Op1I && Op0I->isShift() &&
5449 Op0I->getOpcode() == Op1I->getOpcode() &&
5450 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5451 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005452 Value *NewOp =
5453 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5454 Op0I->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005455 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005456 Op1I->getOperand(1));
5457 }
5458
5459 if (Op0I && Op1I) {
5460 Value *A, *B, *C, *D;
5461 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005462 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5463 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005464 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005465 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005466 }
5467 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005468 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5469 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005470 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005471 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005472 }
5473
5474 // (A & B)^(C & D)
5475 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005476 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5477 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005478 // (X & Y)^(X & Y) -> (Y^Z) & X
5479 Value *X = 0, *Y = 0, *Z = 0;
5480 if (A == C)
5481 X = A, Y = B, Z = D;
5482 else if (A == D)
5483 X = A, Y = B, Z = C;
5484 else if (B == C)
5485 X = B, Y = A, Z = D;
5486 else if (B == D)
5487 X = B, Y = A, Z = C;
5488
5489 if (X) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005490 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005491 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005492 }
5493 }
5494 }
5495
5496 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5497 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005498 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005499 return R;
5500
5501 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005502 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005503 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5504 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5505 const Type *SrcTy = Op0C->getOperand(0)->getType();
5506 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5507 // Only do this if the casts both really cause code to be generated.
5508 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5509 I.getType(), TD) &&
5510 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5511 I.getType(), TD)) {
Chris Lattnerc7694852009-08-30 07:44:24 +00005512 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5513 Op1C->getOperand(0), I.getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00005514 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005515 }
5516 }
Chris Lattner91882432007-10-24 05:38:08 +00005517 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005518
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005519 return Changed ? &I : 0;
5520}
5521
Owen Anderson24be4c12009-07-03 00:17:18 +00005522static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005523 LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005524 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005525}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005526
Dan Gohman8fd520a2009-06-15 22:12:54 +00005527static bool HasAddOverflow(ConstantInt *Result,
5528 ConstantInt *In1, ConstantInt *In2,
5529 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005530 if (IsSigned)
5531 if (In2->getValue().isNegative())
5532 return Result->getValue().sgt(In1->getValue());
5533 else
5534 return Result->getValue().slt(In1->getValue());
5535 else
5536 return Result->getValue().ult(In1->getValue());
5537}
5538
Dan Gohman8fd520a2009-06-15 22:12:54 +00005539/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005540/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005541static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005542 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005543 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005544 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005545
Dan Gohman8fd520a2009-06-15 22:12:54 +00005546 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5547 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005548 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005549 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5550 ExtractElement(In1, Idx, Context),
5551 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005552 IsSigned))
5553 return true;
5554 }
5555 return false;
5556 }
5557
5558 return HasAddOverflow(cast<ConstantInt>(Result),
5559 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5560 IsSigned);
5561}
5562
5563static bool HasSubOverflow(ConstantInt *Result,
5564 ConstantInt *In1, ConstantInt *In2,
5565 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005566 if (IsSigned)
5567 if (In2->getValue().isNegative())
5568 return Result->getValue().slt(In1->getValue());
5569 else
5570 return Result->getValue().sgt(In1->getValue());
5571 else
5572 return Result->getValue().ugt(In1->getValue());
5573}
5574
Dan Gohman8fd520a2009-06-15 22:12:54 +00005575/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5576/// overflowed for this type.
5577static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005578 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005579 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005580 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005581
5582 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5583 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson35b47072009-08-13 21:58:54 +00005584 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005585 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5586 ExtractElement(In1, Idx, Context),
5587 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005588 IsSigned))
5589 return true;
5590 }
5591 return false;
5592 }
5593
5594 return HasSubOverflow(cast<ConstantInt>(Result),
5595 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5596 IsSigned);
5597}
5598
Chris Lattnereba75862008-04-22 02:53:33 +00005599
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005600/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5601/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohman17f46f72009-07-28 01:40:03 +00005602Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005603 ICmpInst::Predicate Cond,
5604 Instruction &I) {
Chris Lattnereba75862008-04-22 02:53:33 +00005605 // Look through bitcasts.
5606 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5607 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005608
5609 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohman17f46f72009-07-28 01:40:03 +00005610 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005611 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005612 // This transformation (ignoring the base and scales) is valid because we
Dan Gohman17f46f72009-07-28 01:40:03 +00005613 // know pointers can't overflow since the gep is inbounds. See if we can
5614 // output an optimized form.
Chris Lattnereba75862008-04-22 02:53:33 +00005615 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5616
5617 // If not, synthesize the offset the hard way.
5618 if (Offset == 0)
Chris Lattner93e6ff92009-11-04 08:05:20 +00005619 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005620 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonaac28372009-07-31 20:28:14 +00005621 Constant::getNullValue(Offset->getType()));
Dan Gohman17f46f72009-07-28 01:40:03 +00005622 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005623 // If the base pointers are different, but the indices are the same, just
5624 // compare the base pointer.
5625 if (PtrBase != GEPRHS->getOperand(0)) {
5626 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5627 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5628 GEPRHS->getOperand(0)->getType();
5629 if (IndicesTheSame)
5630 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5631 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5632 IndicesTheSame = false;
5633 break;
5634 }
5635
5636 // If all indices are the same, just compare the base pointers.
5637 if (IndicesTheSame)
Dan Gohmane6803b82009-08-25 23:17:54 +00005638 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005639 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5640
5641 // Otherwise, the base pointers are different and the indices are
5642 // different, bail out.
5643 return 0;
5644 }
5645
5646 // If one of the GEPs has all zero indices, recurse.
5647 bool AllZeros = true;
5648 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5649 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5650 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5651 AllZeros = false;
5652 break;
5653 }
5654 if (AllZeros)
5655 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5656 ICmpInst::getSwappedPredicate(Cond), I);
5657
5658 // If the other GEP has all zero indices, recurse.
5659 AllZeros = true;
5660 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5661 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5662 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5663 AllZeros = false;
5664 break;
5665 }
5666 if (AllZeros)
5667 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5668
5669 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5670 // If the GEPs only differ by one index, compare it.
5671 unsigned NumDifferences = 0; // Keep track of # differences.
5672 unsigned DiffOperand = 0; // The operand that differs.
5673 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5674 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5675 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5676 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5677 // Irreconcilable differences.
5678 NumDifferences = 2;
5679 break;
5680 } else {
5681 if (NumDifferences++) break;
5682 DiffOperand = i;
5683 }
5684 }
5685
5686 if (NumDifferences == 0) // SAME GEP?
5687 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson35b47072009-08-13 21:58:54 +00005688 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005689 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005690
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005691 else if (NumDifferences == 1) {
5692 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5693 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5694 // Make sure we do a signed comparison here.
Dan Gohmane6803b82009-08-25 23:17:54 +00005695 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005696 }
5697 }
5698
5699 // Only lower this if the icmp is the only user of the GEP or if we expect
5700 // the result to fold to a constant!
Dan Gohmana80e2712009-07-21 23:21:54 +00005701 if (TD &&
5702 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005703 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5704 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner93e6ff92009-11-04 08:05:20 +00005705 Value *L = EmitGEPOffset(GEPLHS, *this);
5706 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005707 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005708 }
5709 }
5710 return 0;
5711}
5712
Chris Lattnere6b62d92008-05-19 20:18:56 +00005713/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5714///
5715Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5716 Instruction *LHSI,
5717 Constant *RHSC) {
5718 if (!isa<ConstantFP>(RHSC)) return 0;
5719 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5720
5721 // Get the width of the mantissa. We don't want to hack on conversions that
5722 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005723 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005724 if (MantissaWidth == -1) return 0; // Unknown.
5725
5726 // Check to see that the input is converted from an integer type that is small
5727 // enough that preserves all bits. TODO: check here for "known" sign bits.
5728 // 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 +00005729 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005730
5731 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005732 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5733 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005734 ++InputSize;
5735
5736 // If the conversion would lose info, don't hack on this.
5737 if ((int)InputSize > MantissaWidth)
5738 return 0;
5739
5740 // Otherwise, we can potentially simplify the comparison. We know that it
5741 // will always come through as an integer value and we know the constant is
5742 // not a NAN (it would have been previously simplified).
5743 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5744
5745 ICmpInst::Predicate Pred;
5746 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005747 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnere6b62d92008-05-19 20:18:56 +00005748 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005749 case FCmpInst::FCMP_OEQ:
5750 Pred = ICmpInst::ICMP_EQ;
5751 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005752 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005753 case FCmpInst::FCMP_OGT:
5754 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5755 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005756 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005757 case FCmpInst::FCMP_OGE:
5758 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5759 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005760 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005761 case FCmpInst::FCMP_OLT:
5762 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5763 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005764 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005765 case FCmpInst::FCMP_OLE:
5766 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5767 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005768 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005769 case FCmpInst::FCMP_ONE:
5770 Pred = ICmpInst::ICMP_NE;
5771 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005772 case FCmpInst::FCMP_ORD:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005773 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005774 case FCmpInst::FCMP_UNO:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005775 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005776 }
5777
5778 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5779
5780 // Now we know that the APFloat is a normal number, zero or inf.
5781
Chris Lattnerf13ff492008-05-20 03:50:52 +00005782 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005783 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005784 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005785
Bill Wendling20636df2008-11-09 04:26:50 +00005786 if (!LHSUnsigned) {
5787 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5788 // and large values.
5789 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5790 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5791 APFloat::rmNearestTiesToEven);
5792 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5793 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5794 Pred == ICmpInst::ICMP_SLE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005795 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5796 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005797 }
5798 } else {
5799 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5800 // +INF and large values.
5801 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5802 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5803 APFloat::rmNearestTiesToEven);
5804 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5805 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5806 Pred == ICmpInst::ICMP_ULE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005807 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5808 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005809 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005810 }
5811
Bill Wendling20636df2008-11-09 04:26:50 +00005812 if (!LHSUnsigned) {
5813 // See if the RHS value is < SignedMin.
5814 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5815 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5816 APFloat::rmNearestTiesToEven);
5817 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5818 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5819 Pred == ICmpInst::ICMP_SGE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005820 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5821 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005822 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005823 }
5824
Bill Wendling20636df2008-11-09 04:26:50 +00005825 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5826 // [0, UMAX], but it may still be fractional. See if it is fractional by
5827 // casting the FP value to the integer value and back, checking for equality.
5828 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005829 Constant *RHSInt = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005830 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5831 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005832 if (!RHS.isZero()) {
5833 bool Equal = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005834 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5835 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005836 if (!Equal) {
5837 // If we had a comparison against a fractional value, we have to adjust
5838 // the compare predicate and sometimes the value. RHSC is rounded towards
5839 // zero at this point.
5840 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005841 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng14118132009-05-22 23:10:53 +00005842 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005843 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005844 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00005845 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005846 case ICmpInst::ICMP_ULE:
5847 // (float)int <= 4.4 --> int <= 4
5848 // (float)int <= -4.4 --> false
5849 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005850 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005851 break;
5852 case ICmpInst::ICMP_SLE:
5853 // (float)int <= 4.4 --> int <= 4
5854 // (float)int <= -4.4 --> int < -4
5855 if (RHS.isNegative())
5856 Pred = ICmpInst::ICMP_SLT;
5857 break;
5858 case ICmpInst::ICMP_ULT:
5859 // (float)int < -4.4 --> false
5860 // (float)int < 4.4 --> int <= 4
5861 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005862 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005863 Pred = ICmpInst::ICMP_ULE;
5864 break;
5865 case ICmpInst::ICMP_SLT:
5866 // (float)int < -4.4 --> int < -4
5867 // (float)int < 4.4 --> int <= 4
5868 if (!RHS.isNegative())
5869 Pred = ICmpInst::ICMP_SLE;
5870 break;
5871 case ICmpInst::ICMP_UGT:
5872 // (float)int > 4.4 --> int > 4
5873 // (float)int > -4.4 --> true
5874 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005875 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005876 break;
5877 case ICmpInst::ICMP_SGT:
5878 // (float)int > 4.4 --> int > 4
5879 // (float)int > -4.4 --> int >= -4
5880 if (RHS.isNegative())
5881 Pred = ICmpInst::ICMP_SGE;
5882 break;
5883 case ICmpInst::ICMP_UGE:
5884 // (float)int >= -4.4 --> true
5885 // (float)int >= 4.4 --> int > 4
5886 if (!RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005887 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005888 Pred = ICmpInst::ICMP_UGT;
5889 break;
5890 case ICmpInst::ICMP_SGE:
5891 // (float)int >= -4.4 --> int >= -4
5892 // (float)int >= 4.4 --> int > 4
5893 if (!RHS.isNegative())
5894 Pred = ICmpInst::ICMP_SGT;
5895 break;
5896 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005897 }
5898 }
5899
5900 // Lower this FP comparison into an appropriate integer version of the
5901 // comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00005902 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00005903}
5904
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005905Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattner454d7a02009-11-09 23:31:49 +00005906 bool Changed = false;
5907
5908 /// Orders the operands of the compare so that they are listed from most
5909 /// complex to least complex. This puts constants before unary operators,
5910 /// before binary operators.
5911 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
5912 I.swapOperands();
5913 Changed = true;
5914 }
5915
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005916 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005917
Chris Lattner54c21352009-11-09 23:55:12 +00005918 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
5919 return ReplaceInstUsesWith(I, V);
5920
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005921 // Simplify 'fcmp pred X, X'
5922 if (Op0 == Op1) {
5923 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005924 default: llvm_unreachable("Unknown predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005925 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5926 case FCmpInst::FCMP_ULT: // True if unordered or less than
5927 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5928 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5929 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5930 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersonaac28372009-07-31 20:28:14 +00005931 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005932 return &I;
5933
5934 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5935 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5936 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5937 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5938 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5939 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersonaac28372009-07-31 20:28:14 +00005940 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005941 return &I;
5942 }
5943 }
5944
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005945 // Handle fcmp with constant RHS
5946 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5947 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5948 switch (LHSI->getOpcode()) {
5949 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005950 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5951 // block. If in the same block, we're encouraging jump threading. If
5952 // not, we are just pessimizing the code by making an i1 phi.
5953 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00005954 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00005955 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005956 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005957 case Instruction::SIToFP:
5958 case Instruction::UIToFP:
5959 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5960 return NV;
5961 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005962 case Instruction::Select:
5963 // If either operand of the select is a constant, we can fold the
5964 // comparison into the select arms, which will cause one to be
5965 // constant folded and the select turned into a bitwise or.
5966 Value *Op1 = 0, *Op2 = 0;
5967 if (LHSI->hasOneUse()) {
5968 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5969 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005970 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005971 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00005972 Op2 = Builder->CreateFCmp(I.getPredicate(),
5973 LHSI->getOperand(2), RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005974 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5975 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005976 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005977 // Insert a new FCmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00005978 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5979 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005980 }
5981 }
5982
5983 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005984 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005985 break;
5986 }
5987 }
5988
5989 return Changed ? &I : 0;
5990}
5991
5992Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattner454d7a02009-11-09 23:31:49 +00005993 bool Changed = false;
5994
5995 /// Orders the operands of the compare so that they are listed from most
5996 /// complex to least complex. This puts constants before unary operators,
5997 /// before binary operators.
5998 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
5999 I.swapOperands();
6000 Changed = true;
6001 }
6002
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006003 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lambf78cd322007-12-18 21:32:20 +00006004
Chris Lattner54c21352009-11-09 23:55:12 +00006005 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6006 return ReplaceInstUsesWith(I, V);
6007
6008 const Type *Ty = Op0->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006009
6010 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson35b47072009-08-13 21:58:54 +00006011 if (Ty == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006012 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006013 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00006014 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattnerc7694852009-08-30 07:44:24 +00006015 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmancdff2122009-08-12 16:23:25 +00006016 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006017 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006018 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00006019 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006020
6021 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00006022 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006023 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006024 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattnerc7694852009-08-30 07:44:24 +00006025 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00006026 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006027 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006028 case ICmpInst::ICMP_SGT:
6029 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006030 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006031 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00006032 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006033 return BinaryOperator::CreateAnd(Not, Op0);
6034 }
6035 case ICmpInst::ICMP_UGE:
6036 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6037 // FALL THROUGH
6038 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattnerc7694852009-08-30 07:44:24 +00006039 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greifa645dd32008-05-16 19:29:10 +00006040 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006041 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006042 case ICmpInst::ICMP_SGE:
6043 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6044 // FALL THROUGH
6045 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattnerc7694852009-08-30 07:44:24 +00006046 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006047 return BinaryOperator::CreateOr(Not, Op0);
6048 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006049 }
6050 }
6051
Dan Gohman7934d592009-04-25 17:12:48 +00006052 unsigned BitWidth = 0;
6053 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00006054 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6055 else if (Ty->isIntOrIntVector())
6056 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00006057
6058 bool isSignBit = false;
6059
Dan Gohman58c09632008-09-16 18:46:06 +00006060 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006061 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00006062 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00006063
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006064 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6065 if (I.isEquality() && CI->isNullValue() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006066 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006067 // (icmp cond A B) if cond is equality
Dan Gohmane6803b82009-08-25 23:17:54 +00006068 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00006069 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006070
Dan Gohman58c09632008-09-16 18:46:06 +00006071 // If we have an icmp le or icmp ge instruction, turn it into the
6072 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner54c21352009-11-09 23:55:12 +00006073 // them being folded in the code below. The SimplifyICmpInst code has
6074 // already handled the edge cases for us, so we just assert on them.
Chris Lattner62d0f232008-07-11 05:08:55 +00006075 switch (I.getPredicate()) {
6076 default: break;
6077 case ICmpInst::ICMP_ULE:
Chris Lattner54c21352009-11-09 23:55:12 +00006078 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006079 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006080 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006081 case ICmpInst::ICMP_SLE:
Chris Lattner54c21352009-11-09 23:55:12 +00006082 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006083 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006084 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006085 case ICmpInst::ICMP_UGE:
Chris Lattner54c21352009-11-09 23:55:12 +00006086 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006087 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006088 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006089 case ICmpInst::ICMP_SGE:
Chris Lattner54c21352009-11-09 23:55:12 +00006090 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohmane6803b82009-08-25 23:17:54 +00006091 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006092 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006093 }
6094
Chris Lattnera1308652008-07-11 05:40:05 +00006095 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006096 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006097 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006098 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6099 }
6100
6101 // See if we can fold the comparison based on range information we can get
6102 // by checking whether bits are known to be zero or one in the input.
6103 if (BitWidth != 0) {
6104 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6105 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6106
6107 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006108 isSignBit ? APInt::getSignBit(BitWidth)
6109 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006110 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006111 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006112 if (SimplifyDemandedBits(I.getOperandUse(1),
6113 APInt::getAllOnesValue(BitWidth),
6114 Op1KnownZero, Op1KnownOne, 0))
6115 return &I;
6116
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006117 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006118 // in. Compute the Min, Max and RHS values based on the known bits. For the
6119 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006120 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6121 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006122 if (I.isSigned()) {
Dan Gohman7934d592009-04-25 17:12:48 +00006123 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6124 Op0Min, Op0Max);
6125 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6126 Op1Min, Op1Max);
6127 } else {
6128 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6129 Op0Min, Op0Max);
6130 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6131 Op1Min, Op1Max);
6132 }
6133
Chris Lattnera1308652008-07-11 05:40:05 +00006134 // If Min and Max are known to be the same, then SimplifyDemandedBits
6135 // figured out that the LHS is a constant. Just constant fold this now so
6136 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006137 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006138 return new ICmpInst(I.getPredicate(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006139 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006140 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohmane6803b82009-08-25 23:17:54 +00006141 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006142 ConstantInt::get(*Context, Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006143
Chris Lattnera1308652008-07-11 05:40:05 +00006144 // Based on the range information we know about the LHS, see if we can
6145 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006146 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006147 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner62d0f232008-07-11 05:08:55 +00006148 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006149 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006150 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006151 break;
6152 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006153 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006154 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006155 break;
6156 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006157 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006158 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006159 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006160 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006161 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006162 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006163 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6164 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006165 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006166 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006167
6168 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6169 if (CI->isMinValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006170 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006171 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006172 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006173 break;
6174 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006175 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006176 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006177 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006178 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006179
6180 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006181 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006182 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6183 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006184 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006185 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006186
6187 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6188 if (CI->isMaxValue(true))
Dan Gohmane6803b82009-08-25 23:17:54 +00006189 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006190 Constant::getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006191 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006192 break;
6193 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006194 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006195 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006196 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006197 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006198 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006199 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006200 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6201 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006202 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006203 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006204 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006205 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006206 case ICmpInst::ICMP_SGT:
6207 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006208 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006209 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006210 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006211
6212 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohmane6803b82009-08-25 23:17:54 +00006213 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006214 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6215 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohmane6803b82009-08-25 23:17:54 +00006216 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006217 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006218 }
6219 break;
6220 case ICmpInst::ICMP_SGE:
6221 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6222 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006223 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006224 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006225 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006226 break;
6227 case ICmpInst::ICMP_SLE:
6228 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6229 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006230 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006231 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006232 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006233 break;
6234 case ICmpInst::ICMP_UGE:
6235 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6236 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006237 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006238 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006239 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006240 break;
6241 case ICmpInst::ICMP_ULE:
6242 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6243 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006244 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006245 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006246 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006247 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006248 }
Dan Gohman7934d592009-04-25 17:12:48 +00006249
6250 // Turn a signed comparison into an unsigned one if both operands
6251 // are known to have the same sign.
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006252 if (I.isSigned() &&
Dan Gohman7934d592009-04-25 17:12:48 +00006253 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6254 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohmane6803b82009-08-25 23:17:54 +00006255 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006256 }
6257
6258 // Test if the ICmpInst instruction is used exclusively by a select as
6259 // part of a minimum or maximum operation. If so, refrain from doing
6260 // any other folding. This helps out other analyses which understand
6261 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6262 // and CodeGen. And in this case, at least one of the comparison
6263 // operands has at least one user besides the compare (the select),
6264 // which would often largely negate the benefit of folding anyway.
6265 if (I.hasOneUse())
6266 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6267 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6268 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6269 return 0;
6270
6271 // See if we are doing a comparison between a constant and an instruction that
6272 // can be folded into the comparison.
6273 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006274 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6275 // instruction, see if that instruction also has constants so that the
6276 // instruction can be folded into the icmp
6277 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6278 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6279 return Res;
6280 }
6281
6282 // Handle icmp with constant (but not simple integer constant) RHS
6283 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6284 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6285 switch (LHSI->getOpcode()) {
6286 case Instruction::GetElementPtr:
6287 if (RHSC->isNullValue()) {
6288 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6289 bool isAllZeros = true;
6290 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6291 if (!isa<Constant>(LHSI->getOperand(i)) ||
6292 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6293 isAllZeros = false;
6294 break;
6295 }
6296 if (isAllZeros)
Dan Gohmane6803b82009-08-25 23:17:54 +00006297 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersonaac28372009-07-31 20:28:14 +00006298 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006299 }
6300 break;
6301
6302 case Instruction::PHI:
Chris Lattner9b61abd2009-09-27 20:46:36 +00006303 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattnera2417ba2008-06-08 20:52:11 +00006304 // block. If in the same block, we're encouraging jump threading. If
6305 // not, we are just pessimizing the code by making an i1 phi.
6306 if (LHSI->getParent() == I.getParent())
Chris Lattner9b61abd2009-09-27 20:46:36 +00006307 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattnera2417ba2008-06-08 20:52:11 +00006308 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006309 break;
6310 case Instruction::Select: {
6311 // If either operand of the select is a constant, we can fold the
6312 // comparison into the select arms, which will cause one to be
6313 // constant folded and the select turned into a bitwise or.
6314 Value *Op1 = 0, *Op2 = 0;
6315 if (LHSI->hasOneUse()) {
6316 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6317 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006318 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006319 // Insert a new ICmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006320 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6321 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006322 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6323 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006324 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006325 // Insert a new ICmp of the other select operand.
Chris Lattnerc7694852009-08-30 07:44:24 +00006326 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6327 RHSC, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006328 }
6329 }
6330
6331 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006332 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006333 break;
6334 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006335 case Instruction::Call:
6336 // If we have (malloc != null), and if the malloc has a single use, we
6337 // can assume it is successful and remove the malloc.
6338 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6339 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez67439f02009-10-21 19:11:40 +00006340 // Need to explicitly erase malloc call here, instead of adding it to
6341 // Worklist, because it won't get DCE'd from the Worklist since
6342 // isInstructionTriviallyDead() returns false for function calls.
6343 // It is OK to replace LHSI/MallocCall with Undef because the
6344 // instruction that uses it will be erased via Worklist.
6345 if (extractMallocCall(LHSI)) {
6346 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6347 EraseInstFromFunction(*LHSI);
6348 return ReplaceInstUsesWith(I,
Victor Hernandez48c3c542009-09-18 22:35:49 +00006349 ConstantInt::get(Type::getInt1Ty(*Context),
6350 !I.isTrueWhenEqual()));
Victor Hernandez67439f02009-10-21 19:11:40 +00006351 }
6352 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6353 if (MallocCall->hasOneUse()) {
6354 MallocCall->replaceAllUsesWith(
6355 UndefValue::get(MallocCall->getType()));
6356 EraseInstFromFunction(*MallocCall);
6357 Worklist.Add(LHSI); // The malloc's bitcast use.
6358 return ReplaceInstUsesWith(I,
6359 ConstantInt::get(Type::getInt1Ty(*Context),
6360 !I.isTrueWhenEqual()));
6361 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00006362 }
6363 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006364 }
6365 }
6366
6367 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohman17f46f72009-07-28 01:40:03 +00006368 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006369 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6370 return NI;
Dan Gohman17f46f72009-07-28 01:40:03 +00006371 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006372 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6373 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6374 return NI;
6375
6376 // Test to see if the operands of the icmp are casted versions of other
6377 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6378 // now.
6379 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6380 if (isa<PointerType>(Op0->getType()) &&
6381 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6382 // We keep moving the cast from the left operand over to the right
6383 // operand, where it can often be eliminated completely.
6384 Op0 = CI->getOperand(0);
6385
6386 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6387 // so eliminate it as well.
6388 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6389 Op1 = CI2->getOperand(0);
6390
6391 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006392 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006393 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00006394 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006395 } else {
6396 // Otherwise, cast the RHS right before the icmp
Chris Lattner78628292009-08-30 19:47:22 +00006397 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006398 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006399 }
Dan Gohmane6803b82009-08-25 23:17:54 +00006400 return new ICmpInst(I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006401 }
6402 }
6403
6404 if (isa<CastInst>(Op0)) {
6405 // Handle the special case of: icmp (cast bool to X), <cst>
6406 // This comes up when you have code like
6407 // int X = A < B;
6408 // if (X) ...
6409 // For generality, we handle any zero-extension of any operand comparison
6410 // with a constant or another cast from the same type.
6411 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6412 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6413 return R;
6414 }
6415
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006416 // See if it's the same type of instruction on the left and right.
6417 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6418 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006419 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006420 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006421 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006422 default: break;
6423 case Instruction::Add:
6424 case Instruction::Sub:
6425 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006426 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohmane6803b82009-08-25 23:17:54 +00006427 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006428 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006429 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6430 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6431 if (CI->getValue().isSignBit()) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006432 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006433 ? I.getUnsignedPredicate()
6434 : I.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006435 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006436 Op1I->getOperand(0));
6437 }
6438
6439 if (CI->getValue().isMaxSignedValue()) {
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006440 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006441 ? I.getUnsignedPredicate()
6442 : I.getSignedPredicate();
6443 Pred = I.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006444 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006445 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006446 }
6447 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006448 break;
6449 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006450 if (!I.isEquality())
6451 break;
6452
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006453 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6454 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6455 // Mask = -1 >> count-trailing-zeros(Cst).
6456 if (!CI->isZero() && !CI->isOne()) {
6457 const APInt &AP = CI->getValue();
Owen Andersoneacb44d2009-07-24 23:12:02 +00006458 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006459 APInt::getLowBitsSet(AP.getBitWidth(),
6460 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006461 AP.countTrailingZeros()));
Chris Lattnerc7694852009-08-30 07:44:24 +00006462 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6463 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohmane6803b82009-08-25 23:17:54 +00006464 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006465 }
6466 }
6467 break;
6468 }
6469 }
6470 }
6471 }
6472
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006473 // ~x < ~y --> y < x
6474 { Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00006475 if (match(Op0, m_Not(m_Value(A))) &&
6476 match(Op1, m_Not(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006477 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006478 }
6479
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006480 if (I.isEquality()) {
6481 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006482
6483 // -x == -y --> x == y
Dan Gohmancdff2122009-08-12 16:23:25 +00006484 if (match(Op0, m_Neg(m_Value(A))) &&
6485 match(Op1, m_Neg(m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006486 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006487
Dan Gohmancdff2122009-08-12 16:23:25 +00006488 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006489 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6490 Value *OtherVal = A == Op1 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006491 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006492 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006493 }
6494
Dan Gohmancdff2122009-08-12 16:23:25 +00006495 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006496 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006497 ConstantInt *C1, *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00006498 if (match(B, m_ConstantInt(C1)) &&
6499 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006500 Constant *NC =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006501 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnerc7694852009-08-30 07:44:24 +00006502 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6503 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattner3b874082008-11-16 05:38:51 +00006504 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006505
6506 // A^B == A^D -> B == D
Dan Gohmane6803b82009-08-25 23:17:54 +00006507 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6508 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6509 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6510 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006511 }
6512 }
6513
Dan Gohmancdff2122009-08-12 16:23:25 +00006514 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006515 (A == Op0 || B == Op0)) {
6516 // A == (A^B) -> B == 0
6517 Value *OtherVal = A == Op0 ? B : A;
Dan Gohmane6803b82009-08-25 23:17:54 +00006518 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006519 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006520 }
Chris Lattner3b874082008-11-16 05:38:51 +00006521
6522 // (A-B) == A -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006523 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006524 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006525 Constant::getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006526
6527 // A == (A-B) -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006528 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006529 return new ICmpInst(I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006530 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006531
6532 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6533 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006534 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6535 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006536 Value *X = 0, *Y = 0, *Z = 0;
6537
6538 if (A == C) {
6539 X = B; Y = D; Z = A;
6540 } else if (A == D) {
6541 X = B; Y = C; Z = A;
6542 } else if (B == C) {
6543 X = A; Y = D; Z = B;
6544 } else if (B == D) {
6545 X = A; Y = C; Z = B;
6546 }
6547
6548 if (X) { // Build (X^Y) & Z
Chris Lattnerc7694852009-08-30 07:44:24 +00006549 Op1 = Builder->CreateXor(X, Y, "tmp");
6550 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006551 I.setOperand(0, Op1);
Owen Andersonaac28372009-07-31 20:28:14 +00006552 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006553 return &I;
6554 }
6555 }
6556 }
6557 return Changed ? &I : 0;
6558}
6559
6560
6561/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6562/// and CmpRHS are both known to be integer constants.
6563Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6564 ConstantInt *DivRHS) {
6565 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6566 const APInt &CmpRHSV = CmpRHS->getValue();
6567
6568 // FIXME: If the operand types don't match the type of the divide
6569 // then don't attempt this transform. The code below doesn't have the
6570 // logic to deal with a signed divide and an unsigned compare (and
6571 // vice versa). This is because (x /s C1) <s C2 produces different
6572 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6573 // (x /u C1) <u C2. Simply casting the operands and result won't
6574 // work. :( The if statement below tests that condition and bails
6575 // if it finds it.
6576 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006577 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006578 return 0;
6579 if (DivRHS->isZero())
6580 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006581 if (DivIsSigned && DivRHS->isAllOnesValue())
6582 return 0; // The overflow computation also screws up here
6583 if (DivRHS->isOne())
6584 return 0; // Not worth bothering, and eliminates some funny cases
6585 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006586
6587 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6588 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6589 // C2 (CI). By solving for X we can turn this into a range check
6590 // instead of computing a divide.
Owen Anderson02b48c32009-07-29 18:55:55 +00006591 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006592
6593 // Determine if the product overflows by seeing if the product is
6594 // not equal to the divide. Make sure we do the same kind of divide
6595 // as in the LHS instruction that we're folding.
Owen Anderson02b48c32009-07-29 18:55:55 +00006596 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6597 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006598
6599 // Get the ICmp opcode
6600 ICmpInst::Predicate Pred = ICI.getPredicate();
6601
6602 // Figure out the interval that is being checked. For example, a comparison
6603 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6604 // Compute this interval based on the constants involved and the signedness of
6605 // the compare/divide. This computes a half-open interval, keeping track of
6606 // whether either value in the interval overflows. After analysis each
6607 // overflow variable is set to 0 if it's corresponding bound variable is valid
6608 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6609 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006610 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006611
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006612 if (!DivIsSigned) { // udiv
6613 // e.g. X/5 op 3 --> [15, 20)
6614 LoBound = Prod;
6615 HiOverflow = LoOverflow = ProdOV;
6616 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006617 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006618 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006619 if (CmpRHSV == 0) { // (X / pos) op 0
6620 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006621 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006622 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006623 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006624 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6625 HiOverflow = LoOverflow = ProdOV;
6626 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006627 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006628 } else { // (X / pos) op neg
6629 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006630 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006631 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6632 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006633 ConstantInt* DivNeg =
Owen Anderson02b48c32009-07-29 18:55:55 +00006634 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Anderson24be4c12009-07-03 00:17:18 +00006635 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006636 true) ? -1 : 0;
6637 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006638 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006639 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006640 if (CmpRHSV == 0) { // (X / neg) op 0
6641 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006642 LoBound = AddOne(DivRHS);
Owen Anderson02b48c32009-07-29 18:55:55 +00006643 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006644 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6645 HiOverflow = 1; // [INTMIN+1, overflow)
6646 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6647 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006648 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006649 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006650 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006651 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6652 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006653 LoOverflow = AddWithOverflow(LoBound, HiBound,
6654 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006655 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006656 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6657 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006658 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006659 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006660 }
6661
6662 // Dividing by a negative swaps the condition. LT <-> GT
6663 Pred = ICmpInst::getSwappedPredicate(Pred);
6664 }
6665
6666 Value *X = DivI->getOperand(0);
6667 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006668 default: llvm_unreachable("Unhandled icmp opcode!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006669 case ICmpInst::ICMP_EQ:
6670 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006671 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006672 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006673 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006674 ICmpInst::ICMP_UGE, X, LoBound);
6675 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006676 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006677 ICmpInst::ICMP_ULT, X, HiBound);
6678 else
6679 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6680 case ICmpInst::ICMP_NE:
6681 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006682 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006683 else if (HiOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006684 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006685 ICmpInst::ICMP_ULT, X, LoBound);
6686 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006687 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006688 ICmpInst::ICMP_UGE, X, HiBound);
6689 else
6690 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6691 case ICmpInst::ICMP_ULT:
6692 case ICmpInst::ICMP_SLT:
6693 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006694 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006695 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006696 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00006697 return new ICmpInst(Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006698 case ICmpInst::ICMP_UGT:
6699 case ICmpInst::ICMP_SGT:
6700 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006701 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006702 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006703 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006704 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohmane6803b82009-08-25 23:17:54 +00006705 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006706 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006707 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006708 }
6709}
6710
6711
6712/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6713///
6714Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6715 Instruction *LHSI,
6716 ConstantInt *RHS) {
6717 const APInt &RHSV = RHS->getValue();
6718
6719 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006720 case Instruction::Trunc:
6721 if (ICI.isEquality() && LHSI->hasOneUse()) {
6722 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6723 // of the high bits truncated out of x are known.
6724 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6725 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6726 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6727 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6728 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6729
6730 // If all the high bits are known, we can do this xform.
6731 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6732 // Pull in the high bits from known-ones set.
6733 APInt NewRHS(RHS->getValue());
6734 NewRHS.zext(SrcBits);
6735 NewRHS |= KnownOne;
Dan Gohmane6803b82009-08-25 23:17:54 +00006736 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006737 ConstantInt::get(*Context, NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00006738 }
6739 }
6740 break;
6741
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006742 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6743 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6744 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6745 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006746 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6747 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006748 Value *CompareVal = LHSI->getOperand(0);
6749
6750 // If the sign bit of the XorCST is not set, there is no change to
6751 // the operation, just stop using the Xor.
6752 if (!XorCST->getValue().isNegative()) {
6753 ICI.setOperand(0, CompareVal);
Chris Lattner3183fb62009-08-30 06:13:40 +00006754 Worklist.Add(LHSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006755 return &ICI;
6756 }
6757
6758 // Was the old condition true if the operand is positive?
6759 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6760
6761 // If so, the new one isn't.
6762 isTrueIfPositive ^= true;
6763
6764 if (isTrueIfPositive)
Dan Gohmane6803b82009-08-25 23:17:54 +00006765 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006766 SubOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006767 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006768 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006769 AddOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006770 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006771
6772 if (LHSI->hasOneUse()) {
6773 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6774 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6775 const APInt &SignBit = XorCST->getValue();
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006776 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewyckydac84332009-01-31 21:30:05 +00006777 ? ICI.getUnsignedPredicate()
6778 : ICI.getSignedPredicate();
Dan Gohmane6803b82009-08-25 23:17:54 +00006779 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006780 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006781 }
6782
6783 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006784 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006785 const APInt &NotSignBit = XorCST->getValue();
Nick Lewyckyb0796c62009-10-25 05:20:17 +00006786 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewyckydac84332009-01-31 21:30:05 +00006787 ? ICI.getUnsignedPredicate()
6788 : ICI.getSignedPredicate();
6789 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohmane6803b82009-08-25 23:17:54 +00006790 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006791 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006792 }
6793 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006794 }
6795 break;
6796 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6797 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6798 LHSI->getOperand(0)->hasOneUse()) {
6799 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6800
6801 // If the LHS is an AND of a truncating cast, we can widen the
6802 // and/compare to be the input width without changing the value
6803 // produced, eliminating a cast.
6804 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6805 // We can do this transformation if either the AND constant does not
6806 // have its sign bit set or if it is an equality comparison.
6807 // Extending a relational comparison when we're checking the sign
6808 // bit would not work.
6809 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006810 (ICI.isEquality() ||
6811 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006812 uint32_t BitWidth =
6813 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6814 APInt NewCST = AndCST->getValue();
6815 NewCST.zext(BitWidth);
6816 APInt NewCI = RHSV;
6817 NewCI.zext(BitWidth);
Chris Lattnerc7694852009-08-30 07:44:24 +00006818 Value *NewAnd =
6819 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006820 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00006821 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006822 ConstantInt::get(*Context, NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006823 }
6824 }
6825
6826 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6827 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6828 // happens a LOT in code produced by the C front-end, for bitfield
6829 // access.
6830 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6831 if (Shift && !Shift->isShift())
6832 Shift = 0;
6833
6834 ConstantInt *ShAmt;
6835 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6836 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6837 const Type *AndTy = AndCST->getType(); // Type of the and.
6838
6839 // We can fold this as long as we can't shift unknown bits
6840 // into the mask. This can only happen with signed shift
6841 // rights, as they sign-extend.
6842 if (ShAmt) {
6843 bool CanFold = Shift->isLogicalShift();
6844 if (!CanFold) {
6845 // To test for the bad case of the signed shr, see if any
6846 // of the bits shifted in could be tested after the mask.
6847 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6848 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6849
6850 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6851 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6852 AndCST->getValue()) == 0)
6853 CanFold = true;
6854 }
6855
6856 if (CanFold) {
6857 Constant *NewCst;
6858 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006859 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006860 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006861 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006862
6863 // Check to see if we are shifting out any of the bits being
6864 // compared.
Owen Anderson02b48c32009-07-29 18:55:55 +00006865 if (ConstantExpr::get(Shift->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00006866 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006867 // If we shifted bits out, the fold is not going to work out.
6868 // As a special case, check to see if this means that the
6869 // result is always true or false now.
6870 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006871 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006872 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006873 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006874 } else {
6875 ICI.setOperand(1, NewCst);
6876 Constant *NewAndCST;
6877 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006878 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006879 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006880 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006881 LHSI->setOperand(1, NewAndCST);
6882 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +00006883 Worklist.Add(Shift); // Shift is dead.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006884 return &ICI;
6885 }
6886 }
6887 }
6888
6889 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6890 // preferable because it allows the C<<Y expression to be hoisted out
6891 // of a loop if Y is invariant and X is not.
6892 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00006893 ICI.isEquality() && !Shift->isArithmeticShift() &&
6894 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006895 // Compute C << Y.
6896 Value *NS;
6897 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerc7694852009-08-30 07:44:24 +00006898 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006899 } else {
6900 // Insert a logical shift.
Chris Lattnerc7694852009-08-30 07:44:24 +00006901 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006902 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006903
6904 // Compute X & (C << Y).
Chris Lattnerc7694852009-08-30 07:44:24 +00006905 Value *NewAnd =
6906 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006907
6908 ICI.setOperand(0, NewAnd);
6909 return &ICI;
6910 }
6911 }
6912 break;
6913
6914 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6915 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6916 if (!ShAmt) break;
6917
6918 uint32_t TypeBits = RHSV.getBitWidth();
6919
6920 // Check that the shift amount is in range. If not, don't perform
6921 // undefined shifts. When the shift is visited it will be
6922 // simplified.
6923 if (ShAmt->uge(TypeBits))
6924 break;
6925
6926 if (ICI.isEquality()) {
6927 // If we are comparing against bits always shifted out, the
6928 // comparison cannot succeed.
6929 Constant *Comp =
Owen Anderson02b48c32009-07-29 18:55:55 +00006930 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Anderson24be4c12009-07-03 00:17:18 +00006931 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006932 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6933 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00006934 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006935 return ReplaceInstUsesWith(ICI, Cst);
6936 }
6937
6938 if (LHSI->hasOneUse()) {
6939 // Otherwise strength reduce the shift into an and.
6940 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6941 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006942 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Anderson24be4c12009-07-03 00:17:18 +00006943 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006944
Chris Lattnerc7694852009-08-30 07:44:24 +00006945 Value *And =
6946 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006947 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006948 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006949 }
6950 }
6951
6952 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6953 bool TrueIfSigned = false;
6954 if (LHSI->hasOneUse() &&
6955 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6956 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneacb44d2009-07-24 23:12:02 +00006957 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006958 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattnerc7694852009-08-30 07:44:24 +00006959 Value *And =
6960 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00006961 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00006962 And, Constant::getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006963 }
6964 break;
6965 }
6966
6967 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6968 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006969 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006970 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006971 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006972
Chris Lattner5ee84f82008-03-21 05:19:58 +00006973 // Check that the shift amount is in range. If not, don't perform
6974 // undefined shifts. When the shift is visited it will be
6975 // simplified.
6976 uint32_t TypeBits = RHSV.getBitWidth();
6977 if (ShAmt->uge(TypeBits))
6978 break;
6979
6980 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006981
Chris Lattner5ee84f82008-03-21 05:19:58 +00006982 // If we are comparing against bits always shifted out, the
6983 // comparison cannot succeed.
6984 APInt Comp = RHSV << ShAmtVal;
6985 if (LHSI->getOpcode() == Instruction::LShr)
6986 Comp = Comp.lshr(ShAmtVal);
6987 else
6988 Comp = Comp.ashr(ShAmtVal);
6989
6990 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6991 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00006992 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00006993 return ReplaceInstUsesWith(ICI, Cst);
6994 }
6995
6996 // Otherwise, check to see if the bits shifted out are known to be zero.
6997 // If so, we can compare against the unshifted value:
6998 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006999 if (LHSI->hasOneUse() &&
7000 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007001 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007002 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007003 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00007004 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007005
Evan Chengfb9292a2008-04-23 00:38:06 +00007006 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007007 // Otherwise strength reduce the shift into an and.
7008 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007009 Constant *Mask = ConstantInt::get(*Context, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007010
Chris Lattnerc7694852009-08-30 07:44:24 +00007011 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7012 Mask, LHSI->getName()+".mask");
Dan Gohmane6803b82009-08-25 23:17:54 +00007013 return new ICmpInst(ICI.getPredicate(), And,
Owen Anderson02b48c32009-07-29 18:55:55 +00007014 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007015 }
7016 break;
7017 }
7018
7019 case Instruction::SDiv:
7020 case Instruction::UDiv:
7021 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7022 // Fold this div into the comparison, producing a range check.
7023 // Determine, based on the divide type, what the range is being
7024 // checked. If there is an overflow on the low or high side, remember
7025 // it, otherwise compute the range [low, hi) bounding the new value.
7026 // See: InsertRangeTest above for the kinds of replacements possible.
7027 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7028 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7029 DivRHS))
7030 return R;
7031 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007032
7033 case Instruction::Add:
7034 // Fold: icmp pred (add, X, C1), C2
7035
7036 if (!ICI.isEquality()) {
7037 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7038 if (!LHSC) break;
7039 const APInt &LHSV = LHSC->getValue();
7040
7041 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7042 .subtract(LHSV);
7043
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007044 if (ICI.isSigned()) {
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007045 if (CR.getLower().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007046 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007047 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007048 } else if (CR.getUpper().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007049 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007050 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007051 }
7052 } else {
7053 if (CR.getLower().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007054 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007055 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007056 } else if (CR.getUpper().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007057 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007058 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007059 }
7060 }
7061 }
7062 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007063 }
7064
7065 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7066 if (ICI.isEquality()) {
7067 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7068
7069 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7070 // the second operand is a constant, simplify a bit.
7071 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7072 switch (BO->getOpcode()) {
7073 case Instruction::SRem:
7074 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7075 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7076 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7077 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007078 Value *NewRem =
7079 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7080 BO->getName());
Dan Gohmane6803b82009-08-25 23:17:54 +00007081 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersonaac28372009-07-31 20:28:14 +00007082 Constant::getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007083 }
7084 }
7085 break;
7086 case Instruction::Add:
7087 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7088 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7089 if (BO->hasOneUse())
Dan Gohmane6803b82009-08-25 23:17:54 +00007090 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007091 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007092 } else if (RHSV == 0) {
7093 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7094 // efficiently invertible, or if the add has just this one use.
7095 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7096
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007097 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohmane6803b82009-08-25 23:17:54 +00007098 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007099 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohmane6803b82009-08-25 23:17:54 +00007100 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007101 else if (BO->hasOneUse()) {
Chris Lattnerc7694852009-08-30 07:44:24 +00007102 Value *Neg = Builder->CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007103 Neg->takeName(BO);
Dan Gohmane6803b82009-08-25 23:17:54 +00007104 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007105 }
7106 }
7107 break;
7108 case Instruction::Xor:
7109 // For the xor case, we can xor two constants together, eliminating
7110 // the explicit xor.
7111 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00007112 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007113 ConstantExpr::getXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007114
7115 // FALLTHROUGH
7116 case Instruction::Sub:
7117 // Replace (([sub|xor] A, B) != 0) with (A != B)
7118 if (RHSV == 0)
Dan Gohmane6803b82009-08-25 23:17:54 +00007119 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007120 BO->getOperand(1));
7121 break;
7122
7123 case Instruction::Or:
7124 // If bits are being or'd in that are not present in the constant we
7125 // are comparing against, then the comparison could never succeed!
7126 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007127 Constant *NotCI = ConstantExpr::getNot(RHS);
7128 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00007129 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007130 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007131 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007132 }
7133 break;
7134
7135 case Instruction::And:
7136 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7137 // If bits are being compared against that are and'd out, then the
7138 // comparison can never succeed!
7139 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007140 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007141 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007142 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007143
7144 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7145 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohmane6803b82009-08-25 23:17:54 +00007146 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007147 ICmpInst::ICMP_NE, LHSI,
Owen Andersonaac28372009-07-31 20:28:14 +00007148 Constant::getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007149
7150 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007151 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007152 Value *X = BO->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +00007153 Constant *Zero = Constant::getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007154 ICmpInst::Predicate pred = isICMP_NE ?
7155 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohmane6803b82009-08-25 23:17:54 +00007156 return new ICmpInst(pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007157 }
7158
7159 // ((X & ~7) == 0) --> X < 8
7160 if (RHSV == 0 && isHighOnes(BOC)) {
7161 Value *X = BO->getOperand(0);
Owen Anderson02b48c32009-07-29 18:55:55 +00007162 Constant *NegX = ConstantExpr::getNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007163 ICmpInst::Predicate pred = isICMP_NE ?
7164 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohmane6803b82009-08-25 23:17:54 +00007165 return new ICmpInst(pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007166 }
7167 }
7168 default: break;
7169 }
7170 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7171 // Handle icmp {eq|ne} <intrinsic>, intcst.
7172 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner3183fb62009-08-30 06:13:40 +00007173 Worklist.Add(II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007174 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007175 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007176 return &ICI;
7177 }
7178 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007179 }
7180 return 0;
7181}
7182
7183/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7184/// We only handle extending casts so far.
7185///
7186Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7187 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7188 Value *LHSCIOp = LHSCI->getOperand(0);
7189 const Type *SrcTy = LHSCIOp->getType();
7190 const Type *DestTy = LHSCI->getType();
7191 Value *RHSCIOp;
7192
7193 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7194 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007195 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7196 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007197 cast<IntegerType>(DestTy)->getBitWidth()) {
7198 Value *RHSOp = 0;
7199 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007200 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007201 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7202 RHSOp = RHSC->getOperand(0);
7203 // If the pointer types don't match, insert a bitcast.
7204 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner78628292009-08-30 19:47:22 +00007205 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007206 }
7207
7208 if (RHSOp)
Dan Gohmane6803b82009-08-25 23:17:54 +00007209 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007210 }
7211
7212 // The code below only handles extension cast instructions, so far.
7213 // Enforce this.
7214 if (LHSCI->getOpcode() != Instruction::ZExt &&
7215 LHSCI->getOpcode() != Instruction::SExt)
7216 return 0;
7217
7218 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewyckyb0796c62009-10-25 05:20:17 +00007219 bool isSignedCmp = ICI.isSigned();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007220
7221 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7222 // Not an extension from the same type?
7223 RHSCIOp = CI->getOperand(0);
7224 if (RHSCIOp->getType() != LHSCIOp->getType())
7225 return 0;
7226
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007227 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007228 // and the other is a zext), then we can't handle this.
7229 if (CI->getOpcode() != LHSCI->getOpcode())
7230 return 0;
7231
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007232 // Deal with equality cases early.
7233 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007234 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007235
7236 // A signed comparison of sign extended values simplifies into a
7237 // signed comparison.
7238 if (isSignedCmp && isSignedExt)
Dan Gohmane6803b82009-08-25 23:17:54 +00007239 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007240
7241 // The other three cases all fold into an unsigned comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00007242 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007243 }
7244
7245 // If we aren't dealing with a constant on the RHS, exit early
7246 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7247 if (!CI)
7248 return 0;
7249
7250 // Compute the constant that would happen if we truncated to SrcTy then
7251 // reextended to DestTy.
Owen Anderson02b48c32009-07-29 18:55:55 +00007252 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7253 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007254 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007255
7256 // If the re-extended constant didn't change...
7257 if (Res2 == CI) {
7258 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7259 // For example, we might have:
Dan Gohman9e1657f2009-06-14 23:30:43 +00007260 // %A = sext i16 %X to i32
7261 // %B = icmp ugt i32 %A, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007262 // It is incorrect to transform this into
Dan Gohman9e1657f2009-06-14 23:30:43 +00007263 // %B = icmp ugt i16 %X, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007264 // because %A may have negative value.
7265 //
Chris Lattner3d816532008-07-11 04:09:09 +00007266 // However, we allow this when the compare is EQ/NE, because they are
7267 // signless.
7268 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007269 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00007270 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007271 }
7272
7273 // The re-extended constant changed so the constant cannot be represented
7274 // in the shorter type. Consequently, we cannot emit a simple comparison.
7275
7276 // First, handle some easy cases. We know the result cannot be equal at this
7277 // point so handle the ICI.isEquality() cases
7278 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007279 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007280 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007281 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007282
7283 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7284 // should have been folded away previously and not enter in here.
7285 Value *Result;
7286 if (isSignedCmp) {
7287 // We're performing a signed comparison.
7288 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00007289 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007290 else
Owen Anderson4f720fa2009-07-31 17:39:07 +00007291 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007292 } else {
7293 // We're performing an unsigned comparison.
7294 if (isSignedExt) {
7295 // We're performing an unsigned comp with a sign extended value.
7296 // This is true if the input is >= 0. [aka >s -1]
Owen Andersonaac28372009-07-31 20:28:14 +00007297 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattnerc7694852009-08-30 07:44:24 +00007298 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007299 } else {
7300 // Unsigned extend & unsigned compare -> always true.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007301 Result = ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007302 }
7303 }
7304
7305 // Finally, return the value computed.
7306 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007307 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007308 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007309
7310 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7311 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7312 "ICmp should be folded!");
7313 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00007314 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohmancdff2122009-08-12 16:23:25 +00007315 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007316}
7317
7318Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7319 return commonShiftTransforms(I);
7320}
7321
7322Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7323 return commonShiftTransforms(I);
7324}
7325
7326Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007327 if (Instruction *R = commonShiftTransforms(I))
7328 return R;
7329
7330 Value *Op0 = I.getOperand(0);
7331
7332 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7333 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7334 if (CSI->isAllOnesValue())
7335 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007336
Dan Gohman2526aea2009-06-16 19:55:29 +00007337 // See if we can turn a signed shr into an unsigned shr.
7338 if (MaskedValueIsZero(Op0,
7339 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7340 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7341
7342 // Arithmetic shifting an all-sign-bit value is a no-op.
7343 unsigned NumSignBits = ComputeNumSignBits(Op0);
7344 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7345 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007346
Chris Lattnere3c504f2007-12-06 01:59:46 +00007347 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007348}
7349
7350Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7351 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7352 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7353
7354 // shl X, 0 == X and shr X, 0 == X
7355 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00007356 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7357 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007358 return ReplaceInstUsesWith(I, Op0);
7359
7360 if (isa<UndefValue>(Op0)) {
7361 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7362 return ReplaceInstUsesWith(I, Op0);
7363 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007364 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007365 }
7366 if (isa<UndefValue>(Op1)) {
7367 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7368 return ReplaceInstUsesWith(I, Op0);
7369 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007370 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007371 }
7372
Dan Gohman2bc21562009-05-21 02:28:33 +00007373 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007374 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007375 return &I;
7376
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007377 // Try to fold constant and into select arguments.
7378 if (isa<Constant>(Op0))
7379 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7380 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7381 return R;
7382
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007383 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7384 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7385 return Res;
7386 return 0;
7387}
7388
7389Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7390 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007391 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007392
7393 // See if we can simplify any instructions used by the instruction whose sole
7394 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007395 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007396
Dan Gohman9e1657f2009-06-14 23:30:43 +00007397 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7398 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007399 //
7400 if (Op1->uge(TypeBits)) {
7401 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007402 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007403 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007404 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007405 return &I;
7406 }
7407 }
7408
7409 // ((X*C1) << C2) == (X * (C1 << C2))
7410 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7411 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7412 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007413 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007414 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007415
7416 // Try to fold constant and into select arguments.
7417 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7418 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7419 return R;
7420 if (isa<PHINode>(Op0))
7421 if (Instruction *NV = FoldOpIntoPhi(I))
7422 return NV;
7423
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007424 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7425 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7426 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7427 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7428 // place. Don't try to do this transformation in this case. Also, we
7429 // require that the input operand is a shift-by-constant so that we have
7430 // confidence that the shifts will get folded together. We could do this
7431 // xform in more cases, but it is unlikely to be profitable.
7432 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7433 isa<ConstantInt>(TrOp->getOperand(1))) {
7434 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00007435 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattnerc7694852009-08-30 07:44:24 +00007436 // (shift2 (shift1 & 0x00FF), c2)
7437 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007438
7439 // For logical shifts, the truncation has the effect of making the high
7440 // part of the register be zeros. Emulate this by inserting an AND to
7441 // clear the top bits as needed. This 'and' will usually be zapped by
7442 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007443 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7444 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007445 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7446
7447 // The mask we constructed says what the trunc would do if occurring
7448 // between the shifts. We want to know the effect *after* the second
7449 // shift. We know that it is a logical shift by a constant, so adjust the
7450 // mask as appropriate.
7451 if (I.getOpcode() == Instruction::Shl)
7452 MaskV <<= Op1->getZExtValue();
7453 else {
7454 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7455 MaskV = MaskV.lshr(Op1->getZExtValue());
7456 }
7457
Chris Lattnerc7694852009-08-30 07:44:24 +00007458 // shift1 & 0x00FF
7459 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7460 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007461
7462 // Return the value truncated to the interesting size.
7463 return new TruncInst(And, I.getType());
7464 }
7465 }
7466
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007467 if (Op0->hasOneUse()) {
7468 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7469 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7470 Value *V1, *V2;
7471 ConstantInt *CC;
7472 switch (Op0BO->getOpcode()) {
7473 default: break;
7474 case Instruction::Add:
7475 case Instruction::And:
7476 case Instruction::Or:
7477 case Instruction::Xor: {
7478 // These operators commute.
7479 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7480 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007481 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerad7516a2009-08-30 18:50:58 +00007482 m_Specific(Op1)))) {
7483 Value *YS = // (Y << C)
7484 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7485 // (X + (Y << C))
7486 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7487 Op0BO->getOperand(1)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007488 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007489 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007490 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7491 }
7492
7493 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7494 Value *Op0BOOp1 = Op0BO->getOperand(1);
7495 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7496 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007497 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007498 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007499 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007500 Value *YS = // (Y << C)
7501 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7502 Op0BO->getName());
7503 // X & (CC << C)
7504 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7505 V1->getName()+".mask");
Gabor Greifa645dd32008-05-16 19:29:10 +00007506 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007507 }
7508 }
7509
7510 // FALL THROUGH.
7511 case Instruction::Sub: {
7512 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7513 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007514 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007515 m_Specific(Op1)))) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007516 Value *YS = // (Y << C)
7517 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7518 // (X + (Y << C))
7519 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7520 Op0BO->getOperand(0)->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007521 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007522 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007523 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7524 }
7525
7526 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7527 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7528 match(Op0BO->getOperand(0),
7529 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007530 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007531 cast<BinaryOperator>(Op0BO->getOperand(0))
7532 ->getOperand(0)->hasOneUse()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007533 Value *YS = // (Y << C)
7534 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7535 // X & (CC << C)
7536 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7537 V1->getName()+".mask");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007538
Gabor Greifa645dd32008-05-16 19:29:10 +00007539 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007540 }
7541
7542 break;
7543 }
7544 }
7545
7546
7547 // If the operand is an bitwise operator with a constant RHS, and the
7548 // shift is the only use, we can pull it out of the shift.
7549 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7550 bool isValid = true; // Valid only for And, Or, Xor
7551 bool highBitSet = false; // Transform if high bit of constant set?
7552
7553 switch (Op0BO->getOpcode()) {
7554 default: isValid = false; break; // Do not perform transform!
7555 case Instruction::Add:
7556 isValid = isLeftShift;
7557 break;
7558 case Instruction::Or:
7559 case Instruction::Xor:
7560 highBitSet = false;
7561 break;
7562 case Instruction::And:
7563 highBitSet = true;
7564 break;
7565 }
7566
7567 // If this is a signed shift right, and the high bit is modified
7568 // by the logical operation, do not perform the transformation.
7569 // The highBitSet boolean indicates the value of the high bit of
7570 // the constant which would cause it to be modified for this
7571 // operation.
7572 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007573 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007574 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007575
7576 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007577 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007578
Chris Lattnerad7516a2009-08-30 18:50:58 +00007579 Value *NewShift =
7580 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007581 NewShift->takeName(Op0BO);
7582
Gabor Greifa645dd32008-05-16 19:29:10 +00007583 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007584 NewRHS);
7585 }
7586 }
7587 }
7588 }
7589
7590 // Find out if this is a shift of a shift by a constant.
7591 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7592 if (ShiftOp && !ShiftOp->isShift())
7593 ShiftOp = 0;
7594
7595 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7596 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7597 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7598 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7599 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7600 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7601 Value *X = ShiftOp->getOperand(0);
7602
7603 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007604
7605 const IntegerType *Ty = cast<IntegerType>(I.getType());
7606
7607 // Check for (X << c1) << c2 and (X >> c1) >> c2
7608 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007609 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7610 // saturates.
7611 if (AmtSum >= TypeBits) {
7612 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007613 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007614 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7615 }
7616
Gabor Greifa645dd32008-05-16 19:29:10 +00007617 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007618 ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007619 }
7620
7621 if (ShiftOp->getOpcode() == Instruction::LShr &&
7622 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007623 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00007624 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007625
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007626 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00007627 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerad7516a2009-08-30 18:50:58 +00007628 }
7629
7630 if (ShiftOp->getOpcode() == Instruction::AShr &&
7631 I.getOpcode() == Instruction::LShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007632 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007633 if (AmtSum >= TypeBits)
7634 AmtSum = TypeBits-1;
7635
Chris Lattnerad7516a2009-08-30 18:50:58 +00007636 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007637
7638 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007639 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007640 }
7641
7642 // Okay, if we get here, one shift must be left, and the other shift must be
7643 // right. See if the amounts are equal.
7644 if (ShiftAmt1 == ShiftAmt2) {
7645 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7646 if (I.getOpcode() == Instruction::Shl) {
7647 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007648 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007649 }
7650 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7651 if (I.getOpcode() == Instruction::LShr) {
7652 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007653 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007654 }
7655 // We can simplify ((X << C) >>s C) into a trunc + sext.
7656 // NOTE: we could do this for any C, but that would make 'unusual' integer
7657 // types. For now, just stick to ones well-supported by the code
7658 // generators.
7659 const Type *SExtType = 0;
7660 switch (Ty->getBitWidth() - ShiftAmt1) {
7661 case 1 :
7662 case 8 :
7663 case 16 :
7664 case 32 :
7665 case 64 :
7666 case 128:
Owen Anderson35b47072009-08-13 21:58:54 +00007667 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007668 break;
7669 default: break;
7670 }
Chris Lattnerad7516a2009-08-30 18:50:58 +00007671 if (SExtType)
7672 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007673 // Otherwise, we can't handle it yet.
7674 } else if (ShiftAmt1 < ShiftAmt2) {
7675 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7676
7677 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7678 if (I.getOpcode() == Instruction::Shl) {
7679 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7680 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007681 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007682
7683 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007684 return BinaryOperator::CreateAnd(Shift,
7685 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007686 }
7687
7688 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7689 if (I.getOpcode() == Instruction::LShr) {
7690 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007691 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007692
7693 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007694 return BinaryOperator::CreateAnd(Shift,
7695 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007696 }
7697
7698 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7699 } else {
7700 assert(ShiftAmt2 < ShiftAmt1);
7701 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7702
7703 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7704 if (I.getOpcode() == Instruction::Shl) {
7705 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7706 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007707 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7708 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007709
7710 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007711 return BinaryOperator::CreateAnd(Shift,
7712 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007713 }
7714
7715 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7716 if (I.getOpcode() == Instruction::LShr) {
7717 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007718 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007719
7720 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007721 return BinaryOperator::CreateAnd(Shift,
7722 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007723 }
7724
7725 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7726 }
7727 }
7728 return 0;
7729}
7730
7731
7732/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7733/// expression. If so, decompose it, returning some value X, such that Val is
7734/// X*Scale+Offset.
7735///
7736static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007737 int &Offset, LLVMContext *Context) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00007738 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7739 "Unexpected allocation size type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007740 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7741 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007742 Scale = 0;
Owen Anderson35b47072009-08-13 21:58:54 +00007743 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007744 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7745 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7746 if (I->getOpcode() == Instruction::Shl) {
7747 // This is a value scaled by '1 << the shift amt'.
7748 Scale = 1U << RHS->getZExtValue();
7749 Offset = 0;
7750 return I->getOperand(0);
7751 } else if (I->getOpcode() == Instruction::Mul) {
7752 // This value is scaled by 'RHS'.
7753 Scale = RHS->getZExtValue();
7754 Offset = 0;
7755 return I->getOperand(0);
7756 } else if (I->getOpcode() == Instruction::Add) {
7757 // We have X+C. Check to see if we really have (X*C2)+C1,
7758 // where C1 is divisible by C2.
7759 unsigned SubScale;
7760 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00007761 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7762 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007763 Offset += RHS->getZExtValue();
7764 Scale = SubScale;
7765 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007766 }
7767 }
7768 }
7769
7770 // Otherwise, we can't look past this.
7771 Scale = 1;
7772 Offset = 0;
7773 return Val;
7774}
7775
7776
7777/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7778/// try to eliminate the cast by moving the type information into the alloc.
7779Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandezb1687302009-10-23 21:09:37 +00007780 AllocaInst &AI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007781 const PointerType *PTy = cast<PointerType>(CI.getType());
7782
Chris Lattnerad7516a2009-08-30 18:50:58 +00007783 BuilderTy AllocaBuilder(*Builder);
7784 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7785
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007786 // Remove any uses of AI that are dead.
7787 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7788
7789 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7790 Instruction *User = cast<Instruction>(*UI++);
7791 if (isInstructionTriviallyDead(User)) {
7792 while (UI != E && *UI == User)
7793 ++UI; // If this instruction uses AI more than once, don't break UI.
7794
7795 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00007796 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007797 EraseInstFromFunction(*User);
7798 }
7799 }
Dan Gohmana80e2712009-07-21 23:21:54 +00007800
7801 // This requires TargetData to get the alloca alignment and size information.
7802 if (!TD) return 0;
7803
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007804 // Get the type really allocated and the type casted to.
7805 const Type *AllocElTy = AI.getAllocatedType();
7806 const Type *CastElTy = PTy->getElementType();
7807 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7808
7809 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7810 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7811 if (CastElTyAlign < AllocElTyAlign) return 0;
7812
7813 // If the allocation has multiple uses, only promote it if we are strictly
7814 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007815 // same, we open the door to infinite loops of various kinds. (A reference
7816 // from a dbg.declare doesn't count as a use for this purpose.)
7817 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7818 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007819
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007820 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7821 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007822 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7823
7824 // See if we can satisfy the modulus by pulling a scale out of the array
7825 // size argument.
7826 unsigned ArraySizeScale;
7827 int ArrayOffset;
7828 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00007829 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7830 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007831
7832 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7833 // do the xform.
7834 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7835 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7836
7837 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7838 Value *Amt = 0;
7839 if (Scale == 1) {
7840 Amt = NumElements;
7841 } else {
Owen Anderson35b47072009-08-13 21:58:54 +00007842 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007843 // Insert before the alloca, not before the cast.
7844 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007845 }
7846
7847 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson35b47072009-08-13 21:58:54 +00007848 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007849 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007850 }
7851
Victor Hernandezb1687302009-10-23 21:09:37 +00007852 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00007853 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007854 New->takeName(&AI);
7855
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007856 // If the allocation has one real use plus a dbg.declare, just remove the
7857 // declare.
7858 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7859 EraseInstFromFunction(*DI);
7860 }
7861 // If the allocation has multiple real uses, insert a cast and change all
7862 // things that used it to use the new cast. This will also hack on CI, but it
7863 // will die soon.
7864 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007865 // New is the allocation instruction, pointer typed. AI is the original
7866 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerad7516a2009-08-30 18:50:58 +00007867 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007868 AI.replaceAllUsesWith(NewCast);
7869 }
7870 return ReplaceInstUsesWith(CI, New);
7871}
7872
7873/// CanEvaluateInDifferentType - Return true if we can take the specified value
7874/// and return it as type Ty without inserting any new casts and without
7875/// changing the computed value. This is used by code that tries to decide
7876/// whether promoting or shrinking integer operations to wider or smaller types
7877/// will allow us to eliminate a truncate or extend.
7878///
7879/// This is a truncation operation if Ty is smaller than V->getType(), or an
7880/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007881///
7882/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7883/// should return true if trunc(V) can be computed by computing V in the smaller
7884/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7885/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7886/// efficiently truncated.
7887///
7888/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7889/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7890/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007891bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00007892 unsigned CastOpc,
7893 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007894 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007895 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007896 return true;
7897
7898 Instruction *I = dyn_cast<Instruction>(V);
7899 if (!I) return false;
7900
Dan Gohman8fd520a2009-06-15 22:12:54 +00007901 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007902
Chris Lattneref70bb82007-08-02 06:11:14 +00007903 // If this is an extension or truncate, we can often eliminate it.
7904 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7905 // If this is a cast from the destination type, we can trivially eliminate
7906 // it, and this will remove a cast overall.
7907 if (I->getOperand(0)->getType() == Ty) {
7908 // If the first operand is itself a cast, and is eliminable, do not count
7909 // this as an eliminable cast. We would prefer to eliminate those two
7910 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007911 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007912 ++NumCastsRemoved;
7913 return true;
7914 }
7915 }
7916
7917 // We can't extend or shrink something that has multiple uses: doing so would
7918 // require duplicating the instruction in general, which isn't profitable.
7919 if (!I->hasOneUse()) return false;
7920
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007921 unsigned Opc = I->getOpcode();
7922 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007923 case Instruction::Add:
7924 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007925 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007926 case Instruction::And:
7927 case Instruction::Or:
7928 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007929 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007930 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007931 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007932 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007933 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007934
Eli Friedman08c45bc2009-07-13 22:46:01 +00007935 case Instruction::UDiv:
7936 case Instruction::URem: {
7937 // UDiv and URem can be truncated if all the truncated bits are zero.
7938 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7939 uint32_t BitWidth = Ty->getScalarSizeInBits();
7940 if (BitWidth < OrigBitWidth) {
7941 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7942 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7943 MaskedValueIsZero(I->getOperand(1), Mask)) {
7944 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7945 NumCastsRemoved) &&
7946 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7947 NumCastsRemoved);
7948 }
7949 }
7950 break;
7951 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007952 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007953 // If we are truncating the result of this SHL, and if it's a shift of a
7954 // constant amount, we can always perform a SHL in a smaller type.
7955 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007956 uint32_t BitWidth = Ty->getScalarSizeInBits();
7957 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007958 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007959 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007960 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007961 }
7962 break;
7963 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007964 // If this is a truncate of a logical shr, we can truncate it to a smaller
7965 // lshr iff we know that the bits we would otherwise be shifting in are
7966 // already zeros.
7967 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007968 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7969 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007970 if (BitWidth < OrigBitWidth &&
7971 MaskedValueIsZero(I->getOperand(0),
7972 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7973 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007974 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007975 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007976 }
7977 }
7978 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007979 case Instruction::ZExt:
7980 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007981 case Instruction::Trunc:
7982 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007983 // can safely replace it. Note that replacing it does not reduce the number
7984 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007985 if (Opc == CastOpc)
7986 return true;
7987
7988 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00007989 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007990 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007991 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007992 case Instruction::Select: {
7993 SelectInst *SI = cast<SelectInst>(I);
7994 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007995 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007996 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007997 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007998 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007999 case Instruction::PHI: {
8000 // We can change a phi if we can change all operands.
8001 PHINode *PN = cast<PHINode>(I);
8002 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8003 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008004 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00008005 return false;
8006 return true;
8007 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008008 default:
8009 // TODO: Can handle more cases here.
8010 break;
8011 }
8012
8013 return false;
8014}
8015
8016/// EvaluateInDifferentType - Given an expression that
8017/// CanEvaluateInDifferentType returns true for, actually insert the code to
8018/// evaluate the expression.
8019Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8020 bool isSigned) {
8021 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner1cd526b2009-11-08 19:23:30 +00008022 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008023
8024 // Otherwise, it must be an instruction.
8025 Instruction *I = cast<Instruction>(V);
8026 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008027 unsigned Opc = I->getOpcode();
8028 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008029 case Instruction::Add:
8030 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00008031 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008032 case Instruction::And:
8033 case Instruction::Or:
8034 case Instruction::Xor:
8035 case Instruction::AShr:
8036 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00008037 case Instruction::Shl:
8038 case Instruction::UDiv:
8039 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008040 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8041 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008042 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008043 break;
8044 }
8045 case Instruction::Trunc:
8046 case Instruction::ZExt:
8047 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008048 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00008049 // just return the source. There's no need to insert it because it is not
8050 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008051 if (I->getOperand(0)->getType() == Ty)
8052 return I->getOperand(0);
8053
Chris Lattner4200c2062008-06-18 04:00:49 +00008054 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner1cd526b2009-11-08 19:23:30 +00008055 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00008056 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008057 case Instruction::Select: {
8058 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8059 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8060 Res = SelectInst::Create(I->getOperand(0), True, False);
8061 break;
8062 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008063 case Instruction::PHI: {
8064 PHINode *OPN = cast<PHINode>(I);
8065 PHINode *NPN = PHINode::Create(Ty);
8066 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8067 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8068 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8069 }
8070 Res = NPN;
8071 break;
8072 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008073 default:
8074 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00008075 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008076 break;
8077 }
8078
Chris Lattner4200c2062008-06-18 04:00:49 +00008079 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008080 return InsertNewInstBefore(Res, *I);
8081}
8082
8083/// @brief Implement the transforms common to all CastInst visitors.
8084Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8085 Value *Src = CI.getOperand(0);
8086
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008087 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8088 // eliminate it now.
8089 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8090 if (Instruction::CastOps opc =
8091 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8092 // The first cast (CSrc) is eliminable so we need to fix up or replace
8093 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008094 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008095 }
8096 }
8097
8098 // If we are casting a select then fold the cast into the select
8099 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8100 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8101 return NV;
8102
8103 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner1cd526b2009-11-08 19:23:30 +00008104 if (isa<PHINode>(Src)) {
8105 // We don't do this if this would create a PHI node with an illegal type if
8106 // it is currently legal.
8107 if (!isa<IntegerType>(Src->getType()) ||
8108 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerd0011092009-11-10 07:23:37 +00008109 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner1cd526b2009-11-08 19:23:30 +00008110 if (Instruction *NV = FoldOpIntoPhi(CI))
8111 return NV;
Chris Lattner1cd526b2009-11-08 19:23:30 +00008112 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008113
8114 return 0;
8115}
8116
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008117/// FindElementAtOffset - Given a type and a constant offset, determine whether
8118/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008119/// the specified offset. If so, fill them into NewIndices and return the
8120/// resultant element type, otherwise return null.
8121static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8122 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008123 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008124 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008125 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008126 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008127
8128 // Start with the index over the outer type. Note that the type size
8129 // might be zero (even if the offset isn't zero) if the indexed type
8130 // is something like [0 x {int, int}]
Owen Anderson35b47072009-08-13 21:58:54 +00008131 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008132 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008133 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008134 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008135 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008136
Chris Lattnerce48c462009-01-11 20:15:20 +00008137 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008138 if (Offset < 0) {
8139 --FirstIdx;
8140 Offset += TySize;
8141 assert(Offset >= 0);
8142 }
8143 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8144 }
8145
Owen Andersoneacb44d2009-07-24 23:12:02 +00008146 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008147
8148 // Index into the types. If we fail, set OrigBase to null.
8149 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008150 // Indexing into tail padding between struct/array elements.
8151 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008152 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008153
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008154 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8155 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008156 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8157 "Offset must stay within the indexed type");
8158
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008159 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson35b47072009-08-13 21:58:54 +00008160 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008161
8162 Offset -= SL->getElementOffset(Elt);
8163 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008164 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008165 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008166 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00008167 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008168 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008169 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008170 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008171 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008172 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008173 }
8174 }
8175
Chris Lattner54dddc72009-01-24 01:00:13 +00008176 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008177}
8178
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008179/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8180Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8181 Value *Src = CI.getOperand(0);
8182
8183 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8184 // If casting the result of a getelementptr instruction with no offset, turn
8185 // this into a cast of the original pointer!
8186 if (GEP->hasAllZeroIndices()) {
8187 // Changing the cast operand is usually not a good idea but it is safe
8188 // here because the pointer operand is being replaced with another
8189 // pointer operand so the opcode doesn't need to change.
Chris Lattner3183fb62009-08-30 06:13:40 +00008190 Worklist.Add(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008191 CI.setOperand(0, GEP->getOperand(0));
8192 return &CI;
8193 }
8194
8195 // If the GEP has a single use, and the base pointer is a bitcast, and the
8196 // GEP computes a constant offset, see if we can convert these three
8197 // instructions into fewer. This typically happens with unions and other
8198 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008199 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008200 if (GEP->hasAllConstantIndices()) {
8201 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner93e6ff92009-11-04 08:05:20 +00008202 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008203 int64_t Offset = OffsetV->getSExtValue();
8204
8205 // Get the base pointer input of the bitcast, and the type it points to.
8206 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8207 const Type *GEPIdxTy =
8208 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008209 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008210 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008211 // If we were able to index down into an element, create the GEP
8212 // and bitcast the result. This eliminates one bitcast, potentially
8213 // two.
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008214 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8215 Builder->CreateInBoundsGEP(OrigBase,
8216 NewIndices.begin(), NewIndices.end()) :
8217 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008218 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008219
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008220 if (isa<BitCastInst>(CI))
8221 return new BitCastInst(NGEP, CI.getType());
8222 assert(isa<PtrToIntInst>(CI));
8223 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008224 }
8225 }
8226 }
8227 }
8228
8229 return commonCastTransforms(CI);
8230}
8231
Eli Friedman827e37a2009-07-13 20:58:59 +00008232/// commonIntCastTransforms - This function implements the common transforms
8233/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008234Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8235 if (Instruction *Result = commonCastTransforms(CI))
8236 return Result;
8237
8238 Value *Src = CI.getOperand(0);
8239 const Type *SrcTy = Src->getType();
8240 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008241 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8242 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008243
8244 // See if we can simplify any instructions used by the LHS whose sole
8245 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008246 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008247 return &CI;
8248
8249 // If the source isn't an instruction or has more than one use then we
8250 // can't do anything more.
8251 Instruction *SrcI = dyn_cast<Instruction>(Src);
8252 if (!SrcI || !Src->hasOneUse())
8253 return 0;
8254
8255 // Attempt to propagate the cast into the instruction for int->int casts.
8256 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008257 // Only do this if the dest type is a simple type, don't convert the
8258 // expression tree to something weird like i93 unless the source is also
8259 // strange.
Chris Lattnerbc5d0132009-11-10 17:00:47 +00008260 if ((isa<VectorType>(DestTy) ||
8261 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8262 CanEvaluateInDifferentType(SrcI, DestTy,
8263 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008264 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008265 // eliminates the cast, so it is always a win. If this is a zero-extension,
8266 // we need to do an AND to maintain the clear top-part of the computation,
8267 // so we require that the input have eliminated at least one cast. If this
8268 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008269 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008270 bool DoXForm = false;
8271 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008272 switch (CI.getOpcode()) {
8273 default:
8274 // All the others use floating point so we shouldn't actually
8275 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008276 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008277 case Instruction::Trunc:
8278 DoXForm = true;
8279 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008280 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008281 DoXForm = NumCastsRemoved >= 1;
Chris Lattner2e9f5d02009-11-07 19:11:46 +00008282
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008283 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008284 // If it's unnecessary to issue an AND to clear the high bits, it's
8285 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008286 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008287 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8288 if (MaskedValueIsZero(TryRes, Mask))
8289 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008290
8291 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008292 if (TryI->use_empty())
8293 EraseInstFromFunction(*TryI);
8294 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008295 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008296 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008297 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008298 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008299 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008300 // If we do not have to emit the truncate + sext pair, then it's always
8301 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008302 //
8303 // It's not safe to eliminate the trunc + sext pair if one of the
8304 // eliminated cast is a truncate. e.g.
8305 // t2 = trunc i32 t1 to i16
8306 // t3 = sext i16 t2 to i32
8307 // !=
8308 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008309 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008310 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8311 if (NumSignBits > (DestBitSize - SrcBitSize))
8312 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008313
8314 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008315 if (TryI->use_empty())
8316 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008317 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008318 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008319 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008320 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008321
8322 if (DoXForm) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00008323 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8324 " to avoid cast: " << CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008325 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8326 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008327 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008328 // Just replace this cast with the result.
8329 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008331 assert(Res->getType() == DestTy);
8332 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008333 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008334 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008335 // Just replace this cast with the result.
8336 return ReplaceInstUsesWith(CI, Res);
8337 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008338 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008339
8340 // If the high bits are already zero, just replace this cast with the
8341 // result.
8342 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8343 if (MaskedValueIsZero(Res, Mask))
8344 return ReplaceInstUsesWith(CI, Res);
8345
8346 // We need to emit an AND to clear the high bits.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008347 Constant *C = ConstantInt::get(*Context,
8348 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008349 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008350 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008351 case Instruction::SExt: {
8352 // If the high bits are already filled with sign bit, just replace this
8353 // cast with the result.
8354 unsigned NumSignBits = ComputeNumSignBits(Res);
8355 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008356 return ReplaceInstUsesWith(CI, Res);
8357
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008358 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008359 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008360 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008361 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008362 }
8363 }
8364
8365 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8366 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8367
8368 switch (SrcI->getOpcode()) {
8369 case Instruction::Add:
8370 case Instruction::Mul:
8371 case Instruction::And:
8372 case Instruction::Or:
8373 case Instruction::Xor:
8374 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008375 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8376 // Don't insert two casts unless at least one can be eliminated.
8377 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008378 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008379 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8380 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008381 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008382 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8383 }
8384 }
8385
8386 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8387 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8388 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson4f720fa2009-07-31 17:39:07 +00008389 Op1 == ConstantInt::getTrue(*Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008390 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008391 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Anderson24be4c12009-07-03 00:17:18 +00008392 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008393 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008394 }
8395 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008396
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008397 case Instruction::Shl: {
8398 // Canonicalize trunc inside shl, if we can.
8399 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8400 if (CI && DestBitSize < SrcBitSize &&
8401 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008402 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8403 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008404 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008405 }
8406 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008407 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008408 }
8409 return 0;
8410}
8411
8412Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8413 if (Instruction *Result = commonIntCastTransforms(CI))
8414 return Result;
8415
8416 Value *Src = CI.getOperand(0);
8417 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008418 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8419 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008420
8421 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008422 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008423 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008424 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersonaac28372009-07-31 20:28:14 +00008425 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohmane6803b82009-08-25 23:17:54 +00008426 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008427 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008428
Chris Lattner32177f82009-03-24 18:15:30 +00008429 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8430 ConstantInt *ShAmtV = 0;
8431 Value *ShiftOp = 0;
8432 if (Src->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00008433 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner32177f82009-03-24 18:15:30 +00008434 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8435
8436 // Get a mask for the bits shifting in.
8437 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8438 if (MaskedValueIsZero(ShiftOp, Mask)) {
8439 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00008440 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008441
8442 // Okay, we can shrink this. Truncate the input, then return a new
8443 // shift.
Chris Lattnerd6164c22009-08-30 20:01:10 +00008444 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Anderson02b48c32009-07-29 18:55:55 +00008445 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008446 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008447 }
8448 }
Chris Lattner1cd526b2009-11-08 19:23:30 +00008449
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008450 return 0;
8451}
8452
Evan Chenge3779cf2008-03-24 00:21:34 +00008453/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8454/// in order to eliminate the icmp.
8455Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8456 bool DoXform) {
8457 // If we are just checking for a icmp eq of a single bit and zext'ing it
8458 // to an integer, then shift the bit to the appropriate place and then
8459 // cast to integer to avoid the comparison.
8460 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8461 const APInt &Op1CV = Op1C->getValue();
8462
8463 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8464 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8465 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8466 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8467 if (!DoXform) return ICI;
8468
8469 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008470 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008471 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008472 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008473 if (In->getType() != CI.getType())
Chris Lattnerad7516a2009-08-30 18:50:58 +00008474 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008475
8476 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008477 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008478 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chenge3779cf2008-03-24 00:21:34 +00008479 }
8480
8481 return ReplaceInstUsesWith(CI, In);
8482 }
8483
8484
8485
8486 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8487 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8488 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8489 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8490 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8491 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8492 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8493 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8494 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8495 // This only works for EQ and NE
8496 ICI->isEquality()) {
8497 // If Op1C some other power of two, convert:
8498 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8499 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8500 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8501 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8502
8503 APInt KnownZeroMask(~KnownZero);
8504 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8505 if (!DoXform) return ICI;
8506
8507 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8508 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8509 // (X&4) == 2 --> false
8510 // (X&4) != 2 --> true
Owen Anderson35b47072009-08-13 21:58:54 +00008511 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00008512 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008513 return ReplaceInstUsesWith(CI, Res);
8514 }
8515
8516 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8517 Value *In = ICI->getOperand(0);
8518 if (ShiftAmt) {
8519 // Perform a logical shr by shiftamt.
8520 // Insert the shift to put the result in the low bit.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008521 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8522 In->getName()+".lobit");
Evan Chenge3779cf2008-03-24 00:21:34 +00008523 }
8524
8525 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008526 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008527 In = Builder->CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008528 }
8529
8530 if (CI.getType() == In->getType())
8531 return ReplaceInstUsesWith(CI, In);
8532 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008533 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008534 }
8535 }
8536 }
8537
Nick Lewyckyef61f692009-11-23 03:17:33 +00008538 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8539 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8540 // may lead to additional simplifications.
8541 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8542 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8543 uint32_t BitWidth = ITy->getBitWidth();
8544 if (BitWidth > 1) {
8545 Value *LHS = ICI->getOperand(0);
8546 Value *RHS = ICI->getOperand(1);
8547
8548 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8549 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8550 APInt TypeMask(APInt::getHighBitsSet(BitWidth, BitWidth-1));
8551 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8552 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
8553
8554 if (KnownZeroLHS.countLeadingOnes() == BitWidth-1 &&
8555 KnownZeroRHS.countLeadingOnes() == BitWidth-1) {
8556 if (!DoXform) return ICI;
8557
8558 Value *Xor = Builder->CreateXor(LHS, RHS);
8559 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8560 Xor = Builder->CreateXor(Xor, ConstantInt::get(ITy, 1));
8561 Xor->takeName(ICI);
8562 return ReplaceInstUsesWith(CI, Xor);
8563 }
8564 }
8565 }
8566 }
8567
Evan Chenge3779cf2008-03-24 00:21:34 +00008568 return 0;
8569}
8570
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008571Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8572 // If one of the common conversion will work ..
8573 if (Instruction *Result = commonIntCastTransforms(CI))
8574 return Result;
8575
8576 Value *Src = CI.getOperand(0);
8577
Chris Lattner215d56e2009-02-17 20:47:23 +00008578 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8579 // types and if the sizes are just right we can convert this into a logical
8580 // 'and' which will be much cheaper than the pair of casts.
8581 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8582 // Get the sizes of the types involved. We know that the intermediate type
8583 // will be smaller than A or C, but don't know the relation between A and C.
8584 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008585 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8586 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8587 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008588 // If we're actually extending zero bits, then if
8589 // SrcSize < DstSize: zext(a & mask)
8590 // SrcSize == DstSize: a & mask
8591 // SrcSize > DstSize: trunc(a) & mask
8592 if (SrcSize < DstSize) {
8593 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008594 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008595 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattner215d56e2009-02-17 20:47:23 +00008596 return new ZExtInst(And, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008597 }
8598
8599 if (SrcSize == DstSize) {
Chris Lattner215d56e2009-02-17 20:47:23 +00008600 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008601 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008602 AndValue));
Chris Lattnerad7516a2009-08-30 18:50:58 +00008603 }
8604 if (SrcSize > DstSize) {
8605 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattner215d56e2009-02-17 20:47:23 +00008606 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008607 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008608 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008609 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008610 }
8611 }
8612
Evan Chenge3779cf2008-03-24 00:21:34 +00008613 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8614 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008615
Evan Chenge3779cf2008-03-24 00:21:34 +00008616 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8617 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8618 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8619 // of the (zext icmp) will be transformed.
8620 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8621 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8622 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8623 (transformZExtICmp(LHS, CI, false) ||
8624 transformZExtICmp(RHS, CI, false))) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008625 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8626 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greifa645dd32008-05-16 19:29:10 +00008627 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008628 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008629 }
8630
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008631 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008632 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8633 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8634 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8635 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008636 if (TI0->getType() == CI.getType())
8637 return
8638 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00008639 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008640 }
8641
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008642 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8643 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8644 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8645 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8646 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8647 And->getOperand(1) == C)
8648 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8649 Value *TI0 = TI->getOperand(0);
8650 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00008651 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerad7516a2009-08-30 18:50:58 +00008652 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008653 return BinaryOperator::CreateXor(NewAnd, ZC);
8654 }
8655 }
8656
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008657 return 0;
8658}
8659
8660Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8661 if (Instruction *I = commonIntCastTransforms(CI))
8662 return I;
8663
8664 Value *Src = CI.getOperand(0);
8665
Dan Gohman35b76162008-10-30 20:40:10 +00008666 // Canonicalize sign-extend from i1 to a select.
Owen Anderson35b47072009-08-13 21:58:54 +00008667 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman35b76162008-10-30 20:40:10 +00008668 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00008669 Constant::getAllOnesValue(CI.getType()),
8670 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008671
8672 // See if the value being truncated is already sign extended. If so, just
8673 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00008674 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00008675 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008676 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8677 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8678 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008679 unsigned NumSignBits = ComputeNumSignBits(Op);
8680
8681 if (OpBits == DestBits) {
8682 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8683 // bits, it is already ready.
8684 if (NumSignBits > DestBits-MidBits)
8685 return ReplaceInstUsesWith(CI, Op);
8686 } else if (OpBits < DestBits) {
8687 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8688 // bits, just sext from i32.
8689 if (NumSignBits > OpBits-MidBits)
8690 return new SExtInst(Op, CI.getType(), "tmp");
8691 } else {
8692 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8693 // bits, just truncate to i32.
8694 if (NumSignBits > OpBits-MidBits)
8695 return new TruncInst(Op, CI.getType(), "tmp");
8696 }
8697 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008698
8699 // If the input is a shl/ashr pair of a same constant, then this is a sign
8700 // extension from a smaller value. If we could trust arbitrary bitwidth
8701 // integers, we could turn this into a truncate to the smaller bit and then
8702 // use a sext for the whole extension. Since we don't, look deeper and check
8703 // for a truncate. If the source and dest are the same type, eliminate the
8704 // trunc and extend and just do shifts. For example, turn:
8705 // %a = trunc i32 %i to i8
8706 // %b = shl i8 %a, 6
8707 // %c = ashr i8 %b, 6
8708 // %d = sext i8 %c to i32
8709 // into:
8710 // %a = shl i32 %i, 30
8711 // %d = ashr i32 %a, 30
8712 Value *A = 0;
8713 ConstantInt *BA = 0, *CA = 0;
8714 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohmancdff2122009-08-12 16:23:25 +00008715 m_ConstantInt(CA))) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008716 BA == CA && isa<TruncInst>(A)) {
8717 Value *I = cast<TruncInst>(A)->getOperand(0);
8718 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008719 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8720 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008721 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00008722 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerad7516a2009-08-30 18:50:58 +00008723 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner8a2d0592008-08-06 07:35:52 +00008724 return BinaryOperator::CreateAShr(I, ShAmtV);
8725 }
8726 }
8727
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008728 return 0;
8729}
8730
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008731/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8732/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008733static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008734 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008735 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008736 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008737 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8738 if (!losesInfo)
Owen Andersond363a0e2009-07-27 20:59:43 +00008739 return ConstantFP::get(*Context, F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008740 return 0;
8741}
8742
8743/// LookThroughFPExtensions - If this is an fp extension instruction, look
8744/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00008745static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008746 if (Instruction *I = dyn_cast<Instruction>(V))
8747 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00008748 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008749
8750 // If this value is a constant, return the constant in the smallest FP type
8751 // that can accurately represent it. This allows us to turn
8752 // (float)((double)X+2.0) into x+2.0f.
8753 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +00008754 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008755 return V; // No constant folding of this.
8756 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00008757 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008758 return V;
Owen Anderson35b47072009-08-13 21:58:54 +00008759 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008760 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00008761 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008762 return V;
8763 // Don't try to shrink to various long double types.
8764 }
8765
8766 return V;
8767}
8768
8769Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8770 if (Instruction *I = commonCastTransforms(CI))
8771 return I;
8772
Dan Gohman7ce405e2009-06-04 22:49:04 +00008773 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008774 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008775 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008776 // many builtins (sqrt, etc).
8777 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8778 if (OpI && OpI->hasOneUse()) {
8779 switch (OpI->getOpcode()) {
8780 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008781 case Instruction::FAdd:
8782 case Instruction::FSub:
8783 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008784 case Instruction::FDiv:
8785 case Instruction::FRem:
8786 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00008787 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8788 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008789 if (LHSTrunc->getType() != SrcTy &&
8790 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008791 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008792 // If the source types were both smaller than the destination type of
8793 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008794 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8795 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008796 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8797 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00008798 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008799 }
8800 }
8801 break;
8802 }
8803 }
8804 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008805}
8806
8807Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8808 return commonCastTransforms(CI);
8809}
8810
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008811Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008812 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8813 if (OpI == 0)
8814 return commonCastTransforms(FI);
8815
8816 // fptoui(uitofp(X)) --> X
8817 // fptoui(sitofp(X)) --> X
8818 // This is safe if the intermediate type has enough bits in its mantissa to
8819 // accurately represent all values of X. For example, do not do this with
8820 // i64->float->i64. This is also safe for sitofp case, because any negative
8821 // 'X' value would cause an undefined result for the fptoui.
8822 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8823 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008824 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008825 OpI->getType()->getFPMantissaWidth())
8826 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008827
8828 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008829}
8830
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008831Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008832 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8833 if (OpI == 0)
8834 return commonCastTransforms(FI);
8835
8836 // fptosi(sitofp(X)) --> X
8837 // fptosi(uitofp(X)) --> X
8838 // This is safe if the intermediate type has enough bits in its mantissa to
8839 // accurately represent all values of X. For example, do not do this with
8840 // i64->float->i64. This is also safe for sitofp case, because any negative
8841 // 'X' value would cause an undefined result for the fptoui.
8842 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8843 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008844 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008845 OpI->getType()->getFPMantissaWidth())
8846 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008847
8848 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008849}
8850
8851Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8852 return commonCastTransforms(CI);
8853}
8854
8855Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8856 return commonCastTransforms(CI);
8857}
8858
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008859Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8860 // If the destination integer type is smaller than the intptr_t type for
8861 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8862 // trunc to be exposed to other transforms. Don't do this for extending
8863 // ptrtoint's, because we don't know if the target sign or zero extends its
8864 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008865 if (TD &&
8866 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008867 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8868 TD->getIntPtrType(CI.getContext()),
8869 "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008870 return new TruncInst(P, CI.getType());
8871 }
8872
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008873 return commonPointerCastTransforms(CI);
8874}
8875
Chris Lattner7c1626482008-01-08 07:23:51 +00008876Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008877 // If the source integer type is larger than the intptr_t type for
8878 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8879 // allows the trunc to be exposed to other transforms. Don't do this for
8880 // extending inttoptr's, because we don't know if the target sign or zero
8881 // extends to pointers.
Chris Lattnerad7516a2009-08-30 18:50:58 +00008882 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008883 TD->getPointerSizeInBits()) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008884 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8885 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008886 return new IntToPtrInst(P, CI.getType());
8887 }
8888
Chris Lattner7c1626482008-01-08 07:23:51 +00008889 if (Instruction *I = commonCastTransforms(CI))
8890 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00008891
Chris Lattner7c1626482008-01-08 07:23:51 +00008892 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008893}
8894
8895Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8896 // If the operands are integer typed then apply the integer transforms,
8897 // otherwise just apply the common ones.
8898 Value *Src = CI.getOperand(0);
8899 const Type *SrcTy = Src->getType();
8900 const Type *DestTy = CI.getType();
8901
Eli Friedman5013d3f2009-07-13 20:53:00 +00008902 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008903 if (Instruction *I = commonPointerCastTransforms(CI))
8904 return I;
8905 } else {
8906 if (Instruction *Result = commonCastTransforms(CI))
8907 return Result;
8908 }
8909
8910
8911 // Get rid of casts from one type to the same type. These are useless and can
8912 // be replaced by the operand.
8913 if (DestTy == Src->getType())
8914 return ReplaceInstUsesWith(CI, Src);
8915
8916 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8917 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8918 const Type *DstElTy = DstPTy->getElementType();
8919 const Type *SrcElTy = SrcPTy->getElementType();
8920
Nate Begemandf5b3612008-03-31 00:22:16 +00008921 // If the address spaces don't match, don't eliminate the bitcast, which is
8922 // required for changing types.
8923 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8924 return 0;
8925
Victor Hernandez48c3c542009-09-18 22:35:49 +00008926 // If we are casting a alloca to a pointer to a type of the same
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008927 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez48c3c542009-09-18 22:35:49 +00008928 // There is no need to modify malloc calls because it is their bitcast that
8929 // needs to be cleaned up.
Victor Hernandezb1687302009-10-23 21:09:37 +00008930 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008931 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8932 return V;
8933
8934 // If the source and destination are pointers, and this cast is equivalent
8935 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8936 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson35b47072009-08-13 21:58:54 +00008937 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008938 unsigned NumZeros = 0;
8939 while (SrcElTy != DstElTy &&
8940 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8941 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8942 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8943 ++NumZeros;
8944 }
8945
8946 // If we found a path from the src to dest, create the getelementptr now.
8947 if (SrcElTy == DstElTy) {
8948 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf3a08b82009-09-07 23:54:19 +00008949 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8950 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008951 }
8952 }
8953
Eli Friedman1d31dee2009-07-18 23:06:53 +00008954 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8955 if (DestVTy->getNumElements() == 1) {
8956 if (!isa<VectorType>(SrcTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008957 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Andersonb99ecca2009-07-30 23:03:37 +00008958 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattnerd6164c22009-08-30 20:01:10 +00008959 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00008960 }
8961 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8962 }
8963 }
8964
8965 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8966 if (SrcVTy->getNumElements() == 1) {
8967 if (!isa<VectorType>(DestTy)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +00008968 Value *Elem =
8969 Builder->CreateExtractElement(Src,
8970 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00008971 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8972 }
8973 }
8974 }
8975
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008976 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8977 if (SVI->hasOneUse()) {
8978 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8979 // a bitconvert to a vector with the same # elts.
8980 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00008981 cast<VectorType>(DestTy)->getNumElements() ==
8982 SVI->getType()->getNumElements() &&
8983 SVI->getType()->getNumElements() ==
8984 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008985 CastInst *Tmp;
8986 // If either of the operands is a cast from CI.getType(), then
8987 // evaluating the shuffle in the casted destination's type will allow
8988 // us to eliminate at least one cast.
8989 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8990 Tmp->getOperand(0)->getType() == DestTy) ||
8991 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8992 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattnerd6164c22009-08-30 20:01:10 +00008993 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8994 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008995 // Return a new shuffle vector. Use the same element ID's, as we
8996 // know the vector types match #elts.
8997 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8998 }
8999 }
9000 }
9001 }
9002 return 0;
9003}
9004
9005/// GetSelectFoldableOperands - We want to turn code that looks like this:
9006/// %C = or %A, %B
9007/// %D = select %cond, %C, %A
9008/// into:
9009/// %C = select %cond, %B, 0
9010/// %D = or %A, %C
9011///
9012/// Assuming that the specified instruction is an operand to the select, return
9013/// a bitmask indicating which operands of this instruction are foldable if they
9014/// equal the other incoming value of the select.
9015///
9016static unsigned GetSelectFoldableOperands(Instruction *I) {
9017 switch (I->getOpcode()) {
9018 case Instruction::Add:
9019 case Instruction::Mul:
9020 case Instruction::And:
9021 case Instruction::Or:
9022 case Instruction::Xor:
9023 return 3; // Can fold through either operand.
9024 case Instruction::Sub: // Can only fold on the amount subtracted.
9025 case Instruction::Shl: // Can only fold on the shift amount.
9026 case Instruction::LShr:
9027 case Instruction::AShr:
9028 return 1;
9029 default:
9030 return 0; // Cannot fold
9031 }
9032}
9033
9034/// GetSelectFoldableConstant - For the same transformation as the previous
9035/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00009036static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00009037 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009038 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00009039 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009040 case Instruction::Add:
9041 case Instruction::Sub:
9042 case Instruction::Or:
9043 case Instruction::Xor:
9044 case Instruction::Shl:
9045 case Instruction::LShr:
9046 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00009047 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009048 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00009049 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009050 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00009051 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009052 }
9053}
9054
9055/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9056/// have the same opcode and only one use each. Try to simplify this.
9057Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9058 Instruction *FI) {
9059 if (TI->getNumOperands() == 1) {
9060 // If this is a non-volatile load or a cast from the same type,
9061 // merge.
9062 if (TI->isCast()) {
9063 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9064 return 0;
9065 } else {
9066 return 0; // unknown unary op.
9067 }
9068
9069 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009070 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00009071 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009072 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009073 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009074 TI->getType());
9075 }
9076
9077 // Only handle binary operators here.
9078 if (!isa<BinaryOperator>(TI))
9079 return 0;
9080
9081 // Figure out if the operations have any operands in common.
9082 Value *MatchOp, *OtherOpT, *OtherOpF;
9083 bool MatchIsOpZero;
9084 if (TI->getOperand(0) == FI->getOperand(0)) {
9085 MatchOp = TI->getOperand(0);
9086 OtherOpT = TI->getOperand(1);
9087 OtherOpF = FI->getOperand(1);
9088 MatchIsOpZero = true;
9089 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9090 MatchOp = TI->getOperand(1);
9091 OtherOpT = TI->getOperand(0);
9092 OtherOpF = FI->getOperand(0);
9093 MatchIsOpZero = false;
9094 } else if (!TI->isCommutative()) {
9095 return 0;
9096 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9097 MatchOp = TI->getOperand(0);
9098 OtherOpT = TI->getOperand(1);
9099 OtherOpF = FI->getOperand(0);
9100 MatchIsOpZero = true;
9101 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9102 MatchOp = TI->getOperand(1);
9103 OtherOpT = TI->getOperand(0);
9104 OtherOpF = FI->getOperand(1);
9105 MatchIsOpZero = true;
9106 } else {
9107 return 0;
9108 }
9109
9110 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009111 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9112 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009113 InsertNewInstBefore(NewSI, SI);
9114
9115 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9116 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009117 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009118 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009119 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009120 }
Edwin Törökbd448e32009-07-14 16:55:14 +00009121 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009122 return 0;
9123}
9124
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009125static bool isSelect01(Constant *C1, Constant *C2) {
9126 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9127 if (!C1I)
9128 return false;
9129 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9130 if (!C2I)
9131 return false;
9132 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9133}
9134
9135/// FoldSelectIntoOp - Try fold the select into one of the operands to
9136/// facilitate further optimization.
9137Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9138 Value *FalseVal) {
9139 // See the comment above GetSelectFoldableOperands for a description of the
9140 // transformation we are doing here.
9141 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9142 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9143 !isa<Constant>(FalseVal)) {
9144 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9145 unsigned OpToFold = 0;
9146 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9147 OpToFold = 1;
9148 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9149 OpToFold = 2;
9150 }
9151
9152 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009153 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009154 Value *OOp = TVI->getOperand(2-OpToFold);
9155 // Avoid creating select between 2 constants unless it's selecting
9156 // between 0 and 1.
9157 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9158 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9159 InsertNewInstBefore(NewSel, SI);
9160 NewSel->takeName(TVI);
9161 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9162 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009163 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009164 }
9165 }
9166 }
9167 }
9168 }
9169
9170 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9171 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9172 !isa<Constant>(TrueVal)) {
9173 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9174 unsigned OpToFold = 0;
9175 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9176 OpToFold = 1;
9177 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9178 OpToFold = 2;
9179 }
9180
9181 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009182 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009183 Value *OOp = FVI->getOperand(2-OpToFold);
9184 // Avoid creating select between 2 constants unless it's selecting
9185 // between 0 and 1.
9186 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9187 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9188 InsertNewInstBefore(NewSel, SI);
9189 NewSel->takeName(FVI);
9190 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9191 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009192 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009193 }
9194 }
9195 }
9196 }
9197 }
9198
9199 return 0;
9200}
9201
Dan Gohman58c09632008-09-16 18:46:06 +00009202/// visitSelectInstWithICmp - Visit a SelectInst that has an
9203/// ICmpInst as its first operand.
9204///
9205Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9206 ICmpInst *ICI) {
9207 bool Changed = false;
9208 ICmpInst::Predicate Pred = ICI->getPredicate();
9209 Value *CmpLHS = ICI->getOperand(0);
9210 Value *CmpRHS = ICI->getOperand(1);
9211 Value *TrueVal = SI.getTrueValue();
9212 Value *FalseVal = SI.getFalseValue();
9213
9214 // Check cases where the comparison is with a constant that
9215 // can be adjusted to fit the min/max idiom. We may edit ICI in
9216 // place here, so make sure the select is the only user.
9217 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009218 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009219 switch (Pred) {
9220 default: break;
9221 case ICmpInst::ICMP_ULT:
9222 case ICmpInst::ICMP_SLT: {
9223 // X < MIN ? T : F --> F
9224 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9225 return ReplaceInstUsesWith(SI, FalseVal);
9226 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009227 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009228 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9229 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9230 Pred = ICmpInst::getSwappedPredicate(Pred);
9231 CmpRHS = AdjustedRHS;
9232 std::swap(FalseVal, TrueVal);
9233 ICI->setPredicate(Pred);
9234 ICI->setOperand(1, CmpRHS);
9235 SI.setOperand(1, TrueVal);
9236 SI.setOperand(2, FalseVal);
9237 Changed = true;
9238 }
9239 break;
9240 }
9241 case ICmpInst::ICMP_UGT:
9242 case ICmpInst::ICMP_SGT: {
9243 // X > MAX ? T : F --> F
9244 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9245 return ReplaceInstUsesWith(SI, FalseVal);
9246 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009247 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009248 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9249 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9250 Pred = ICmpInst::getSwappedPredicate(Pred);
9251 CmpRHS = AdjustedRHS;
9252 std::swap(FalseVal, TrueVal);
9253 ICI->setPredicate(Pred);
9254 ICI->setOperand(1, CmpRHS);
9255 SI.setOperand(1, TrueVal);
9256 SI.setOperand(2, FalseVal);
9257 Changed = true;
9258 }
9259 break;
9260 }
9261 }
9262
Dan Gohman35b76162008-10-30 20:40:10 +00009263 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9264 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009265 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohmancdff2122009-08-12 16:23:25 +00009266 if (match(TrueVal, m_ConstantInt<-1>()) &&
9267 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009268 Pred = ICI->getPredicate();
Dan Gohmancdff2122009-08-12 16:23:25 +00009269 else if (match(TrueVal, m_ConstantInt<0>()) &&
9270 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009271 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9272
Dan Gohman35b76162008-10-30 20:40:10 +00009273 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9274 // If we are just checking for a icmp eq of a single bit and zext'ing it
9275 // to an integer, then shift the bit to the appropriate place and then
9276 // cast to integer to avoid the comparison.
9277 const APInt &Op1CV = CI->getValue();
9278
9279 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9280 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9281 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009282 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009283 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00009284 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009285 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009286 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00009287 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00009288 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009289 if (In->getType() != SI.getType())
9290 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009291 true/*SExt*/, "tmp", ICI);
9292
9293 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohmancdff2122009-08-12 16:23:25 +00009294 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman35b76162008-10-30 20:40:10 +00009295 In->getName()+".not"), *ICI);
9296
9297 return ReplaceInstUsesWith(SI, In);
9298 }
9299 }
9300 }
9301
Dan Gohman58c09632008-09-16 18:46:06 +00009302 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9303 // Transform (X == Y) ? X : Y -> Y
9304 if (Pred == ICmpInst::ICMP_EQ)
9305 return ReplaceInstUsesWith(SI, FalseVal);
9306 // Transform (X != Y) ? X : Y -> X
9307 if (Pred == ICmpInst::ICMP_NE)
9308 return ReplaceInstUsesWith(SI, TrueVal);
9309 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9310
9311 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9312 // Transform (X == Y) ? Y : X -> X
9313 if (Pred == ICmpInst::ICMP_EQ)
9314 return ReplaceInstUsesWith(SI, FalseVal);
9315 // Transform (X != Y) ? Y : X -> Y
9316 if (Pred == ICmpInst::ICMP_NE)
9317 return ReplaceInstUsesWith(SI, TrueVal);
9318 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9319 }
9320
9321 /// NOTE: if we wanted to, this is where to detect integer ABS
9322
9323 return Changed ? &SI : 0;
9324}
9325
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009326
Chris Lattnerb5ed7f02009-10-22 00:17:26 +00009327/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9328/// PHI node (but the two may be in different blocks). See if the true/false
9329/// values (V) are live in all of the predecessor blocks of the PHI. For
9330/// example, cases like this cannot be mapped:
9331///
9332/// X = phi [ C1, BB1], [C2, BB2]
9333/// Y = add
9334/// Z = select X, Y, 0
9335///
9336/// because Y is not live in BB1/BB2.
9337///
9338static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9339 const SelectInst &SI) {
9340 // If the value is a non-instruction value like a constant or argument, it
9341 // can always be mapped.
9342 const Instruction *I = dyn_cast<Instruction>(V);
9343 if (I == 0) return true;
9344
9345 // If V is a PHI node defined in the same block as the condition PHI, we can
9346 // map the arguments.
9347 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9348
9349 if (const PHINode *VP = dyn_cast<PHINode>(I))
9350 if (VP->getParent() == CondPHI->getParent())
9351 return true;
9352
9353 // Otherwise, if the PHI and select are defined in the same block and if V is
9354 // defined in a different block, then we can transform it.
9355 if (SI.getParent() == CondPHI->getParent() &&
9356 I->getParent() != CondPHI->getParent())
9357 return true;
9358
9359 // Otherwise we have a 'hard' case and we can't tell without doing more
9360 // detailed dominator based analysis, punt.
9361 return false;
9362}
Chris Lattnerff5cd9d2009-09-27 20:18:49 +00009363
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009364Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9365 Value *CondVal = SI.getCondition();
9366 Value *TrueVal = SI.getTrueValue();
9367 Value *FalseVal = SI.getFalseValue();
9368
9369 // select true, X, Y -> X
9370 // select false, X, Y -> Y
9371 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9372 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9373
9374 // select C, X, X -> X
9375 if (TrueVal == FalseVal)
9376 return ReplaceInstUsesWith(SI, TrueVal);
9377
9378 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9379 return ReplaceInstUsesWith(SI, FalseVal);
9380 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9381 return ReplaceInstUsesWith(SI, TrueVal);
9382 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9383 if (isa<Constant>(TrueVal))
9384 return ReplaceInstUsesWith(SI, TrueVal);
9385 else
9386 return ReplaceInstUsesWith(SI, FalseVal);
9387 }
9388
Owen Anderson35b47072009-08-13 21:58:54 +00009389 if (SI.getType() == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009390 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9391 if (C->getZExtValue()) {
9392 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009393 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009394 } else {
9395 // Change: A = select B, false, C --> A = and !B, C
9396 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009397 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009398 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009399 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009400 }
9401 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9402 if (C->getZExtValue() == false) {
9403 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009404 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009405 } else {
9406 // Change: A = select B, C, true --> A = or !B, C
9407 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009408 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009409 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009410 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009411 }
9412 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009413
9414 // select a, b, a -> a&b
9415 // select a, a, b -> a|b
9416 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009417 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009418 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009419 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009420 }
9421
9422 // Selecting between two integer constants?
9423 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9424 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9425 // select C, 1, 0 -> zext C to int
9426 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009427 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009428 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9429 // select C, 0, 1 -> zext !C to int
9430 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009431 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009432 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009433 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009434 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009435
9436 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009437 // If one of the constants is zero (we know they can't both be) and we
9438 // have an icmp instruction with zero, and we have an 'and' with the
9439 // non-constant value, eliminate this whole mess. This corresponds to
9440 // cases like this: ((X & 27) ? 27 : 0)
9441 if (TrueValC->isZero() || FalseValC->isZero())
9442 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9443 cast<Constant>(IC->getOperand(1))->isNullValue())
9444 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9445 if (ICA->getOpcode() == Instruction::And &&
9446 isa<ConstantInt>(ICA->getOperand(1)) &&
9447 (ICA->getOperand(1) == TrueValC ||
9448 ICA->getOperand(1) == FalseValC) &&
9449 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9450 // Okay, now we know that everything is set up, we just don't
9451 // know whether we have a icmp_ne or icmp_eq and whether the
9452 // true or false val is the zero.
9453 bool ShouldNotVal = !TrueValC->isZero();
9454 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9455 Value *V = ICA;
9456 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009457 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009458 Instruction::Xor, V, ICA->getOperand(1)), SI);
9459 return ReplaceInstUsesWith(SI, V);
9460 }
9461 }
9462 }
9463
9464 // See if we are selecting two values based on a comparison of the two values.
9465 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9466 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9467 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009468 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9469 // This is not safe in general for floating point:
9470 // consider X== -0, Y== +0.
9471 // It becomes safe if either operand is a nonzero constant.
9472 ConstantFP *CFPt, *CFPf;
9473 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9474 !CFPt->getValueAPF().isZero()) ||
9475 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9476 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009477 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009478 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009479 // Transform (X != Y) ? X : Y -> X
9480 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9481 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009482 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009483
9484 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9485 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009486 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9487 // This is not safe in general for floating point:
9488 // consider X== -0, Y== +0.
9489 // It becomes safe if either operand is a nonzero constant.
9490 ConstantFP *CFPt, *CFPf;
9491 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9492 !CFPt->getValueAPF().isZero()) ||
9493 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9494 !CFPf->getValueAPF().isZero()))
9495 return ReplaceInstUsesWith(SI, FalseVal);
9496 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009497 // Transform (X != Y) ? Y : X -> Y
9498 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9499 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009500 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009501 }
Dan Gohman58c09632008-09-16 18:46:06 +00009502 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009503 }
9504
9505 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009506 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9507 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9508 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009509
9510 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9511 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9512 if (TI->hasOneUse() && FI->hasOneUse()) {
9513 Instruction *AddOp = 0, *SubOp = 0;
9514
9515 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9516 if (TI->getOpcode() == FI->getOpcode())
9517 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9518 return IV;
9519
9520 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9521 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009522 if ((TI->getOpcode() == Instruction::Sub &&
9523 FI->getOpcode() == Instruction::Add) ||
9524 (TI->getOpcode() == Instruction::FSub &&
9525 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009526 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009527 } else if ((FI->getOpcode() == Instruction::Sub &&
9528 TI->getOpcode() == Instruction::Add) ||
9529 (FI->getOpcode() == Instruction::FSub &&
9530 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009531 AddOp = TI; SubOp = FI;
9532 }
9533
9534 if (AddOp) {
9535 Value *OtherAddOp = 0;
9536 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9537 OtherAddOp = AddOp->getOperand(1);
9538 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9539 OtherAddOp = AddOp->getOperand(0);
9540 }
9541
9542 if (OtherAddOp) {
9543 // So at this point we know we have (Y -> OtherAddOp):
9544 // select C, (add X, Y), (sub X, Z)
9545 Value *NegVal; // Compute -Z
9546 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00009547 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009548 } else {
9549 NegVal = InsertNewInstBefore(
Dan Gohmancdff2122009-08-12 16:23:25 +00009550 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00009551 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009552 }
9553
9554 Value *NewTrueOp = OtherAddOp;
9555 Value *NewFalseOp = NegVal;
9556 if (AddOp != TI)
9557 std::swap(NewTrueOp, NewFalseOp);
9558 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009559 SelectInst::Create(CondVal, NewTrueOp,
9560 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009561
9562 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009563 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009564 }
9565 }
9566 }
9567
9568 // See if we can fold the select into one of our operands.
9569 if (SI.getType()->isInteger()) {
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009570 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9571 if (FoldI)
9572 return FoldI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009573 }
9574
Chris Lattnerb5ed7f02009-10-22 00:17:26 +00009575 // See if we can fold the select into a phi node if the condition is a select.
9576 if (isa<PHINode>(SI.getCondition()))
9577 // The true/false values have to be live in the PHI predecessor's blocks.
9578 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9579 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9580 if (Instruction *NV = FoldOpIntoPhi(SI))
9581 return NV;
Chris Lattnerf7843b72009-09-27 19:57:57 +00009582
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009583 if (BinaryOperator::isNot(CondVal)) {
9584 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9585 SI.setOperand(1, FalseVal);
9586 SI.setOperand(2, TrueVal);
9587 return &SI;
9588 }
9589
9590 return 0;
9591}
9592
Dan Gohman2d648bb2008-04-10 18:43:06 +00009593/// EnforceKnownAlignment - If the specified pointer points to an object that
9594/// we control, modify the object's alignment to PrefAlign. This isn't
9595/// often possible though. If alignment is important, a more reliable approach
9596/// is to simply align all global variables and allocation instructions to
9597/// their preferred alignment from the beginning.
9598///
9599static unsigned EnforceKnownAlignment(Value *V,
9600 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009601
Dan Gohman2d648bb2008-04-10 18:43:06 +00009602 User *U = dyn_cast<User>(V);
9603 if (!U) return Align;
9604
Dan Gohman9545fb02009-07-17 20:47:02 +00009605 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009606 default: break;
9607 case Instruction::BitCast:
9608 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9609 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009610 // If all indexes are zero, it is just the alignment of the base pointer.
9611 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009612 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009613 if (!isa<Constant>(*i) ||
9614 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009615 AllZeroOperands = false;
9616 break;
9617 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009618
9619 if (AllZeroOperands) {
9620 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009621 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009622 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009623 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009624 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009625 }
9626
9627 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9628 // If there is a large requested alignment and we can, bump up the alignment
9629 // of the global.
9630 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009631 if (GV->getAlignment() >= PrefAlign)
9632 Align = GV->getAlignment();
9633 else {
9634 GV->setAlignment(PrefAlign);
9635 Align = PrefAlign;
9636 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009637 }
Chris Lattnere8ad9ae2009-09-27 21:42:46 +00009638 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9639 // If there is a requested alignment and if this is an alloca, round up.
9640 if (AI->getAlignment() >= PrefAlign)
9641 Align = AI->getAlignment();
9642 else {
9643 AI->setAlignment(PrefAlign);
9644 Align = PrefAlign;
Dan Gohman2d648bb2008-04-10 18:43:06 +00009645 }
9646 }
9647
9648 return Align;
9649}
9650
9651/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9652/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9653/// and it is more than the alignment of the ultimate object, see if we can
9654/// increase the alignment of the ultimate object, making this check succeed.
9655unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9656 unsigned PrefAlign) {
9657 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9658 sizeof(PrefAlign) * CHAR_BIT;
9659 APInt Mask = APInt::getAllOnesValue(BitWidth);
9660 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9661 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9662 unsigned TrailZ = KnownZero.countTrailingOnes();
9663 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9664
9665 if (PrefAlign > Align)
9666 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9667
9668 // We don't need to make any adjustment.
9669 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009670}
9671
Chris Lattner00ae5132008-01-13 23:50:23 +00009672Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009673 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009674 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009675 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009676 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009677
9678 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009679 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009680 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00009681 return MI;
9682 }
9683
9684 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9685 // load/store.
9686 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9687 if (MemOpLength == 0) return 0;
9688
Chris Lattnerc669fb62008-01-14 00:28:35 +00009689 // Source and destination pointer types are always "i8*" for intrinsic. See
9690 // if the size is something we can handle with a single primitive load/store.
9691 // A single load+store correctly handles overlapping memory in the memmove
9692 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009693 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009694 if (Size == 0) return MI; // Delete this mem transfer.
9695
9696 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009697 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009698
Chris Lattnerc669fb62008-01-14 00:28:35 +00009699 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00009700 Type *NewPtrTy =
Owen Anderson35b47072009-08-13 21:58:54 +00009701 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009702
9703 // Memcpy forces the use of i8* for the source and destination. That means
9704 // that if you're using memcpy to move one double around, you'll get a cast
9705 // from double* to i8*. We'd much rather use a double load+store rather than
9706 // an i64 load+store, here because this improves the odds that the source or
9707 // dest address will be promotable. See if we can find a better type than the
9708 // integer datatype.
9709 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9710 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00009711 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009712 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9713 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009714 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009715 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9716 if (STy->getNumElements() == 1)
9717 SrcETy = STy->getElementType(0);
9718 else
9719 break;
9720 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9721 if (ATy->getNumElements() == 1)
9722 SrcETy = ATy->getElementType();
9723 else
9724 break;
9725 } else
9726 break;
9727 }
9728
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009729 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009730 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009731 }
9732 }
9733
9734
Chris Lattner00ae5132008-01-13 23:50:23 +00009735 // If the memcpy/memmove provides better alignment info than we can
9736 // infer, use it.
9737 SrcAlign = std::max(SrcAlign, CopyAlign);
9738 DstAlign = std::max(DstAlign, CopyAlign);
9739
Chris Lattner78628292009-08-30 19:47:22 +00009740 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9741 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009742 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9743 InsertNewInstBefore(L, *MI);
9744 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9745
9746 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009747 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009748 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009749}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009750
Chris Lattner5af8a912008-04-30 06:39:11 +00009751Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9752 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009753 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009754 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009755 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +00009756 return MI;
9757 }
9758
9759 // Extract the length and alignment and fill if they are constant.
9760 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9761 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson35b47072009-08-13 21:58:54 +00009762 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner5af8a912008-04-30 06:39:11 +00009763 return 0;
9764 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009765 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009766
9767 // If the length is zero, this is a no-op
9768 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9769
9770 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9771 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson35b47072009-08-13 21:58:54 +00009772 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00009773
9774 Value *Dest = MI->getDest();
Chris Lattner78628292009-08-30 19:47:22 +00009775 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner5af8a912008-04-30 06:39:11 +00009776
9777 // Alignment 0 is identity for alignment 1 for memset, but not store.
9778 if (Alignment == 0) Alignment = 1;
9779
9780 // Extract the fill value and store.
9781 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +00009782 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +00009783 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009784
9785 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009786 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00009787 return MI;
9788 }
9789
9790 return 0;
9791}
9792
9793
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009794/// visitCallInst - CallInst simplification. This mostly only handles folding
9795/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9796/// the heavy lifting.
9797///
9798Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez93946082009-10-24 04:23:03 +00009799 if (isFreeCall(&CI))
9800 return visitFree(CI);
9801
Chris Lattneraa295aa2009-05-13 17:39:14 +00009802 // If the caller function is nounwind, mark the call as nounwind, even if the
9803 // callee isn't.
9804 if (CI.getParent()->getParent()->doesNotThrow() &&
9805 !CI.doesNotThrow()) {
9806 CI.setDoesNotThrow();
9807 return &CI;
9808 }
9809
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009810 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9811 if (!II) return visitCallSite(&CI);
9812
9813 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9814 // visitCallSite.
9815 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9816 bool Changed = false;
9817
9818 // memmove/cpy/set of zero bytes is a noop.
9819 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9820 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9821
9822 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9823 if (CI->getZExtValue() == 1) {
9824 // Replace the instruction with just byte operations. We would
9825 // transform other cases to loads/stores, but we don't know if
9826 // alignment is sufficient.
9827 }
9828 }
9829
9830 // If we have a memmove and the source operation is a constant global,
9831 // then the source and dest pointers can't alias, so we can change this
9832 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009833 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009834 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9835 if (GVSrc->isConstant()) {
9836 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009837 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9838 const Type *Tys[1];
9839 Tys[0] = CI.getOperand(3)->getType();
9840 CI.setOperand(0,
9841 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009842 Changed = true;
9843 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009844
9845 // memmove(x,x,size) -> noop.
9846 if (MMI->getSource() == MMI->getDest())
9847 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009848 }
9849
9850 // If we can determine a pointer alignment that is bigger than currently
9851 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009852 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009853 if (Instruction *I = SimplifyMemTransfer(MI))
9854 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009855 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9856 if (Instruction *I = SimplifyMemSet(MSI))
9857 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009858 }
9859
9860 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009861 }
9862
9863 switch (II->getIntrinsicID()) {
9864 default: break;
9865 case Intrinsic::bswap:
9866 // bswap(bswap(x)) -> x
9867 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9868 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9869 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9870 break;
Chris Lattner0b452262009-11-26 21:42:47 +00009871 case Intrinsic::uadd_with_overflow: {
9872 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
9873 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
9874 uint32_t BitWidth = IT->getBitWidth();
9875 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner65e34842009-11-26 22:08:06 +00009876 APInt LHSKnownZero(BitWidth, 0);
9877 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +00009878 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
9879 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
9880 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
9881
9882 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner65e34842009-11-26 22:08:06 +00009883 APInt RHSKnownZero(BitWidth, 0);
9884 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner0b452262009-11-26 21:42:47 +00009885 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
9886 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
9887 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
9888 if (LHSKnownNegative && RHSKnownNegative) {
9889 // The sign bit is set in both cases: this MUST overflow.
9890 // Create a simple add instruction, and insert it into the struct.
9891 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
9892 Worklist.Add(Add);
9893 Constant *V[2];
9894 V[0] = UndefValue::get(LHS->getType());
9895 V[1] = ConstantInt::getTrue(*Context);
9896 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
9897 return InsertValueInst::Create(Struct, Add, 0);
9898 }
9899
9900 if (LHSKnownPositive && RHSKnownPositive) {
9901 // The sign bit is clear in both cases: this CANNOT overflow.
9902 // Create a simple add instruction, and insert it into the struct.
9903 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
9904 Worklist.Add(Add);
9905 Constant *V[2];
9906 V[0] = UndefValue::get(LHS->getType());
9907 V[1] = ConstantInt::getFalse(*Context);
9908 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
9909 return InsertValueInst::Create(Struct, Add, 0);
9910 }
9911 }
9912 }
9913 // FALL THROUGH uadd into sadd
9914 case Intrinsic::sadd_with_overflow:
9915 // Canonicalize constants into the RHS.
9916 if (isa<Constant>(II->getOperand(1)) &&
9917 !isa<Constant>(II->getOperand(2))) {
9918 Value *LHS = II->getOperand(1);
9919 II->setOperand(1, II->getOperand(2));
9920 II->setOperand(2, LHS);
9921 return II;
9922 }
9923
9924 // X + undef -> undef
9925 if (isa<UndefValue>(II->getOperand(2)))
9926 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
9927
9928 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
9929 // X + 0 -> {X, false}
9930 if (RHS->isZero()) {
9931 Constant *V[] = {
9932 UndefValue::get(II->getType()), ConstantInt::getFalse(*Context)
9933 };
9934 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
9935 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
9936 }
9937 }
9938 break;
9939 case Intrinsic::usub_with_overflow:
9940 case Intrinsic::ssub_with_overflow:
9941 // undef - X -> undef
9942 // X - undef -> undef
9943 if (isa<UndefValue>(II->getOperand(1)) ||
9944 isa<UndefValue>(II->getOperand(2)))
9945 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
9946
9947 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
9948 // X - 0 -> {X, false}
9949 if (RHS->isZero()) {
9950 Constant *V[] = {
9951 UndefValue::get(II->getType()), ConstantInt::getFalse(*Context)
9952 };
9953 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
9954 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
9955 }
9956 }
9957 break;
9958 case Intrinsic::umul_with_overflow:
9959 case Intrinsic::smul_with_overflow:
9960 // Canonicalize constants into the RHS.
9961 if (isa<Constant>(II->getOperand(1)) &&
9962 !isa<Constant>(II->getOperand(2))) {
9963 Value *LHS = II->getOperand(1);
9964 II->setOperand(1, II->getOperand(2));
9965 II->setOperand(2, LHS);
9966 return II;
9967 }
9968
9969 // X * undef -> undef
9970 if (isa<UndefValue>(II->getOperand(2)))
9971 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
9972
9973 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
9974 // X*0 -> {0, false}
9975 if (RHSI->isZero())
9976 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
9977
9978 // X * 1 -> {X, false}
9979 if (RHSI->equalsInt(1)) {
9980 Constant *V[2];
9981 V[0] = UndefValue::get(II->getType());
9982 V[1] = ConstantInt::getFalse(*Context);
9983 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
9984 return InsertValueInst::Create(Struct, II->getOperand(1), 1);
9985 }
9986 }
9987 break;
Chris Lattner989ba312008-06-18 04:33:20 +00009988 case Intrinsic::ppc_altivec_lvx:
9989 case Intrinsic::ppc_altivec_lvxl:
9990 case Intrinsic::x86_sse_loadu_ps:
9991 case Intrinsic::x86_sse2_loadu_pd:
9992 case Intrinsic::x86_sse2_loadu_dq:
9993 // Turn PPC lvx -> load if the pointer is known aligned.
9994 // Turn X86 loadups -> load if the pointer is known aligned.
9995 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner78628292009-08-30 19:47:22 +00009996 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9997 PointerType::getUnqual(II->getType()));
Chris Lattner989ba312008-06-18 04:33:20 +00009998 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009999 }
Chris Lattner989ba312008-06-18 04:33:20 +000010000 break;
10001 case Intrinsic::ppc_altivec_stvx:
10002 case Intrinsic::ppc_altivec_stvxl:
10003 // Turn stvx -> store if the pointer is known aligned.
10004 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10005 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010006 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner78628292009-08-30 19:47:22 +000010007 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +000010008 return new StoreInst(II->getOperand(1), Ptr);
10009 }
10010 break;
10011 case Intrinsic::x86_sse_storeu_ps:
10012 case Intrinsic::x86_sse2_storeu_pd:
10013 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +000010014 // Turn X86 storeu -> store if the pointer is known aligned.
10015 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10016 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010017 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner78628292009-08-30 19:47:22 +000010018 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner989ba312008-06-18 04:33:20 +000010019 return new StoreInst(II->getOperand(2), Ptr);
10020 }
10021 break;
10022
10023 case Intrinsic::x86_sse_cvttss2si: {
10024 // These intrinsics only demands the 0th element of its input vector. If
10025 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +000010026 unsigned VWidth =
10027 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10028 APInt DemandedElts(VWidth, 1);
10029 APInt UndefElts(VWidth, 0);
10030 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +000010031 UndefElts)) {
10032 II->setOperand(1, V);
10033 return II;
10034 }
10035 break;
10036 }
10037
10038 case Intrinsic::ppc_altivec_vperm:
10039 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10040 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10041 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010042
Chris Lattner989ba312008-06-18 04:33:20 +000010043 // Check that all of the elements are integer constants or undefs.
10044 bool AllEltsOk = true;
10045 for (unsigned i = 0; i != 16; ++i) {
10046 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10047 !isa<UndefValue>(Mask->getOperand(i))) {
10048 AllEltsOk = false;
10049 break;
10050 }
10051 }
10052
10053 if (AllEltsOk) {
10054 // Cast the input vectors to byte vectors.
Chris Lattner78628292009-08-30 19:47:22 +000010055 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10056 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Andersonb99ecca2009-07-30 23:03:37 +000010057 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010058
Chris Lattner989ba312008-06-18 04:33:20 +000010059 // Only extract each element once.
10060 Value *ExtractedElts[32];
10061 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10062
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010063 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +000010064 if (isa<UndefValue>(Mask->getOperand(i)))
10065 continue;
10066 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10067 Idx &= 31; // Match the hardware behavior.
10068
10069 if (ExtractedElts[Idx] == 0) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010070 ExtractedElts[Idx] =
10071 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
10072 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10073 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010074 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010075
Chris Lattner989ba312008-06-18 04:33:20 +000010076 // Insert this value into the result vector.
Chris Lattnerad7516a2009-08-30 18:50:58 +000010077 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10078 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10079 "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010080 }
Chris Lattner989ba312008-06-18 04:33:20 +000010081 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010082 }
Chris Lattner989ba312008-06-18 04:33:20 +000010083 }
10084 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010085
Chris Lattner989ba312008-06-18 04:33:20 +000010086 case Intrinsic::stackrestore: {
10087 // If the save is right next to the restore, remove the restore. This can
10088 // happen when variable allocas are DCE'd.
10089 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10090 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10091 BasicBlock::iterator BI = SS;
10092 if (&*++BI == II)
10093 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010094 }
Chris Lattner989ba312008-06-18 04:33:20 +000010095 }
10096
10097 // Scan down this block to see if there is another stack restore in the
10098 // same block without an intervening call/alloca.
10099 BasicBlock::iterator BI = II;
10100 TerminatorInst *TI = II->getParent()->getTerminator();
10101 bool CannotRemove = false;
10102 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez48c3c542009-09-18 22:35:49 +000010103 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner989ba312008-06-18 04:33:20 +000010104 CannotRemove = true;
10105 break;
10106 }
Chris Lattnera6b477c2008-06-25 05:59:28 +000010107 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10108 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10109 // If there is a stackrestore below this one, remove this one.
10110 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10111 return EraseInstFromFunction(CI);
10112 // Otherwise, ignore the intrinsic.
10113 } else {
10114 // If we found a non-intrinsic call, we can't remove the stack
10115 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +000010116 CannotRemove = true;
10117 break;
10118 }
Chris Lattner989ba312008-06-18 04:33:20 +000010119 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010120 }
Chris Lattner989ba312008-06-18 04:33:20 +000010121
10122 // If the stack restore is in a return/unwind block and if there are no
10123 // allocas or calls between the restore and the return, nuke the restore.
10124 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10125 return EraseInstFromFunction(CI);
10126 break;
10127 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010128 }
10129
10130 return visitCallSite(II);
10131}
10132
10133// InvokeInst simplification
10134//
10135Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10136 return visitCallSite(&II);
10137}
10138
Dale Johannesen96021832008-04-25 21:16:07 +000010139/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10140/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +000010141static bool isSafeToEliminateVarargsCast(const CallSite CS,
10142 const CastInst * const CI,
10143 const TargetData * const TD,
10144 const int ix) {
10145 if (!CI->isLosslessCast())
10146 return false;
10147
10148 // The size of ByVal arguments is derived from the type, so we
10149 // can't change to a type with a different size. If the size were
10150 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +000010151 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +000010152 return true;
10153
10154 const Type* SrcTy =
10155 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10156 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10157 if (!SrcTy->isSized() || !DstTy->isSized())
10158 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +000010159 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +000010160 return false;
10161 return true;
10162}
10163
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010164// visitCallSite - Improvements for call and invoke instructions.
10165//
10166Instruction *InstCombiner::visitCallSite(CallSite CS) {
10167 bool Changed = false;
10168
10169 // If the callee is a constexpr cast of a function, attempt to move the cast
10170 // to the arguments of the call/invoke.
10171 if (transformConstExprCastCall(CS)) return 0;
10172
10173 Value *Callee = CS.getCalledValue();
10174
10175 if (Function *CalleeF = dyn_cast<Function>(Callee))
10176 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10177 Instruction *OldCall = CS.getInstruction();
10178 // If the call and callee calling conventions don't match, this call must
10179 // be unreachable, as the call is undefined.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010180 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000010181 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Anderson24be4c12009-07-03 00:17:18 +000010182 OldCall);
Devang Patele3829c82009-10-13 22:56:32 +000010183 // If OldCall dues not return void then replaceAllUsesWith undef.
10184 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010185 if (!OldCall->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010186 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010187 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10188 return EraseInstFromFunction(*OldCall);
10189 return 0;
10190 }
10191
10192 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10193 // This instruction is not reachable, just remove it. We insert a store to
10194 // undef so that we know that this code is not reachable, despite the fact
10195 // that we can't modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010196 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsf2519d62009-10-06 15:40:36 +000010197 UndefValue::get(Type::getInt1PtrTy(*Context)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010198 CS.getInstruction());
10199
Devang Patele3829c82009-10-13 22:56:32 +000010200 // If CS dues not return void then replaceAllUsesWith undef.
10201 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000010202 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000010203 CS.getInstruction()->
10204 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010205
10206 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10207 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010208 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson4f720fa2009-07-31 17:39:07 +000010209 ConstantInt::getTrue(*Context), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010210 }
10211 return EraseInstFromFunction(*CS.getInstruction());
10212 }
10213
Duncan Sands74833f22007-09-17 10:26:40 +000010214 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10215 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10216 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10217 return transformCallThroughTrampoline(CS);
10218
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010219 const PointerType *PTy = cast<PointerType>(Callee->getType());
10220 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10221 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +000010222 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010223 // See if we can optimize any arguments passed through the varargs area of
10224 // the call.
10225 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +000010226 E = CS.arg_end(); I != E; ++I, ++ix) {
10227 CastInst *CI = dyn_cast<CastInst>(*I);
10228 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10229 *I = CI->getOperand(0);
10230 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010231 }
Dale Johannesen35615462008-04-23 18:34:37 +000010232 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010233 }
10234
Duncan Sands2937e352007-12-19 21:13:37 +000010235 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010236 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010237 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010238 Changed = true;
10239 }
10240
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010241 return Changed ? CS.getInstruction() : 0;
10242}
10243
10244// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10245// attempt to move the cast to the arguments of the call/invoke.
10246//
10247bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10248 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10249 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10250 if (CE->getOpcode() != Instruction::BitCast ||
10251 !isa<Function>(CE->getOperand(0)))
10252 return false;
10253 Function *Callee = cast<Function>(CE->getOperand(0));
10254 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010255 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010256
10257 // Okay, this is a cast from a function to a different type. Unless doing so
10258 // would cause a type conversion of one of our arguments, change this call to
10259 // be a direct call with arguments casted to the appropriate types.
10260 //
10261 const FunctionType *FT = Callee->getFunctionType();
10262 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010263 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010264
Duncan Sands7901ce12008-06-01 07:38:42 +000010265 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010266 return false; // TODO: Handle multiple return values.
10267
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010268 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010269 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010270 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010271 // Conversion is ok if changing from one pointer type to another or from
10272 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +000010273 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010274 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000010275 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010276 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010277 return false; // Cannot transform this return value.
10278
Duncan Sands5c489582008-01-06 10:12:28 +000010279 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010280 // void -> non-void is handled specially
Devang Patele9d08b82009-10-14 17:29:00 +000010281 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010282 return false; // Cannot transform this return value.
10283
Chris Lattner1c8733e2008-03-12 17:45:29 +000010284 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010285 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010286 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010287 return false; // Attribute not compatible with transformed value.
10288 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010289
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010290 // If the callsite is an invoke instruction, and the return value is used by
10291 // a PHI node in a successor, we cannot change the return type of the call
10292 // because there is no place to put the cast instruction (without breaking
10293 // the critical edge). Bail out in this case.
10294 if (!Caller->use_empty())
10295 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10296 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10297 UI != E; ++UI)
10298 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10299 if (PN->getParent() == II->getNormalDest() ||
10300 PN->getParent() == II->getUnwindDest())
10301 return false;
10302 }
10303
10304 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10305 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10306
10307 CallSite::arg_iterator AI = CS.arg_begin();
10308 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10309 const Type *ParamTy = FT->getParamType(i);
10310 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010311
10312 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010313 return false; // Cannot transform this parameter value.
10314
Devang Patelf2a4a922008-09-26 22:53:05 +000010315 if (CallerPAL.getParamAttributes(i + 1)
10316 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010317 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010318
Duncan Sands7901ce12008-06-01 07:38:42 +000010319 // Converting from one pointer type to another or between a pointer and an
10320 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010321 bool isConvertible = ActTy == ParamTy ||
Owen Anderson35b47072009-08-13 21:58:54 +000010322 (TD && ((isa<PointerType>(ParamTy) ||
10323 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10324 (isa<PointerType>(ActTy) ||
10325 ActTy == TD->getIntPtrType(Caller->getContext()))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010326 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010327 }
10328
10329 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10330 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010331 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010332
Chris Lattner1c8733e2008-03-12 17:45:29 +000010333 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10334 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010335 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010336 // won't be dropping them. Check that these extra arguments have attributes
10337 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010338 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10339 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010340 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010341 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010342 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010343 return false;
10344 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010345
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010346 // Okay, we decided that this is a safe thing to do: go ahead and start
10347 // inserting cast instructions as necessary...
10348 std::vector<Value*> Args;
10349 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010350 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010351 attrVec.reserve(NumCommonArgs);
10352
10353 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010354 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010355
10356 // If the return value is not being used, the type may not be compatible
10357 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010358 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010359
10360 // Add the new return attributes.
10361 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010362 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010363
10364 AI = CS.arg_begin();
10365 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10366 const Type *ParamTy = FT->getParamType(i);
10367 if ((*AI)->getType() == ParamTy) {
10368 Args.push_back(*AI);
10369 } else {
10370 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10371 false, ParamTy, false);
Chris Lattnerad7516a2009-08-30 18:50:58 +000010372 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010373 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010374
10375 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010376 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010377 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010378 }
10379
10380 // If the function takes more arguments than the call was taking, add them
Chris Lattnerad7516a2009-08-30 18:50:58 +000010381 // now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010382 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +000010383 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010384
Chris Lattnerad7516a2009-08-30 18:50:58 +000010385 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010386 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010387 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +000010388 errs() << "WARNING: While resolving call to function '"
10389 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010390 } else {
Chris Lattnerad7516a2009-08-30 18:50:58 +000010391 // Add all of the arguments in their promoted form to the arg list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010392 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10393 const Type *PTy = getPromotedType((*AI)->getType());
10394 if (PTy != (*AI)->getType()) {
10395 // Must promote to pass through va_arg area!
Chris Lattnerad7516a2009-08-30 18:50:58 +000010396 Instruction::CastOps opcode =
10397 CastInst::getCastOpcode(*AI, false, PTy, false);
10398 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010399 } else {
10400 Args.push_back(*AI);
10401 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010402
Duncan Sands4ced1f82008-01-13 08:02:44 +000010403 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010404 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010405 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010406 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010407 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010408 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010409
Devang Patelf2a4a922008-09-26 22:53:05 +000010410 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10411 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10412
Devang Patele9d08b82009-10-14 17:29:00 +000010413 if (NewRetTy->isVoidTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010414 Caller->setName(""); // Void type should not have a name.
10415
Eric Christopher3e7381f2009-07-25 02:45:27 +000010416 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10417 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010418
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010419 Instruction *NC;
10420 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010421 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010422 Args.begin(), Args.end(),
10423 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010424 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010425 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010426 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010427 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10428 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010429 CallInst *CI = cast<CallInst>(Caller);
10430 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010431 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010432 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010433 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010434 }
10435
10436 // Insert a cast of the return type as necessary.
10437 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010438 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patele9d08b82009-10-14 17:29:00 +000010439 if (!NV->getType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010440 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010441 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010442 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010443
10444 // If this is an invoke instruction, we should insert it after the first
10445 // non-phi, instruction in the normal successor block.
10446 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010447 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010448 InsertNewInstBefore(NC, *I);
10449 } else {
10450 // Otherwise, it's a call, just insert cast right after the call instr
10451 InsertNewInstBefore(NC, *Caller);
10452 }
Chris Lattner4796b622009-08-30 06:22:51 +000010453 Worklist.AddUsersToWorkList(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010454 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010455 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010456 }
10457 }
10458
Devang Pateledad36f2009-10-13 21:41:20 +000010459
Chris Lattner26b7f942009-08-31 05:17:58 +000010460 if (!Caller->use_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010461 Caller->replaceAllUsesWith(NV);
Chris Lattner26b7f942009-08-31 05:17:58 +000010462
10463 EraseInstFromFunction(*Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010464 return true;
10465}
10466
Duncan Sands74833f22007-09-17 10:26:40 +000010467// transformCallThroughTrampoline - Turn a call to a function created by the
10468// init_trampoline intrinsic into a direct call to the underlying function.
10469//
10470Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10471 Value *Callee = CS.getCalledValue();
10472 const PointerType *PTy = cast<PointerType>(Callee->getType());
10473 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010474 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010475
10476 // If the call already has the 'nest' attribute somewhere then give up -
10477 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010478 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010479 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010480
10481 IntrinsicInst *Tramp =
10482 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10483
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010484 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010485 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10486 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10487
Devang Pateld222f862008-09-25 21:00:45 +000010488 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010489 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010490 unsigned NestIdx = 1;
10491 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010492 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010493
10494 // Look for a parameter marked with the 'nest' attribute.
10495 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10496 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010497 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010498 // Record the parameter type and any other attributes.
10499 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010500 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010501 break;
10502 }
10503
10504 if (NestTy) {
10505 Instruction *Caller = CS.getInstruction();
10506 std::vector<Value*> NewArgs;
10507 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10508
Devang Pateld222f862008-09-25 21:00:45 +000010509 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010510 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010511
Duncan Sands74833f22007-09-17 10:26:40 +000010512 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010513 // mean appending it. Likewise for attributes.
10514
Devang Patelf2a4a922008-09-26 22:53:05 +000010515 // Add any result attributes.
10516 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010517 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010518
Duncan Sands74833f22007-09-17 10:26:40 +000010519 {
10520 unsigned Idx = 1;
10521 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10522 do {
10523 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010524 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010525 Value *NestVal = Tramp->getOperand(3);
10526 if (NestVal->getType() != NestTy)
10527 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10528 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010529 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010530 }
10531
10532 if (I == E)
10533 break;
10534
Duncan Sands48b81112008-01-14 19:52:09 +000010535 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010536 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010537 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010538 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010539 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010540
10541 ++Idx, ++I;
10542 } while (1);
10543 }
10544
Devang Patelf2a4a922008-09-26 22:53:05 +000010545 // Add any function attributes.
10546 if (Attributes Attr = Attrs.getFnAttributes())
10547 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10548
Duncan Sands74833f22007-09-17 10:26:40 +000010549 // The trampoline may have been bitcast to a bogus type (FTy).
10550 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010551 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010552
Duncan Sands74833f22007-09-17 10:26:40 +000010553 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010554 NewTypes.reserve(FTy->getNumParams()+1);
10555
Duncan Sands74833f22007-09-17 10:26:40 +000010556 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010557 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010558 {
10559 unsigned Idx = 1;
10560 FunctionType::param_iterator I = FTy->param_begin(),
10561 E = FTy->param_end();
10562
10563 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010564 if (Idx == NestIdx)
10565 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010566 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010567
10568 if (I == E)
10569 break;
10570
Duncan Sands48b81112008-01-14 19:52:09 +000010571 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010572 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010573
10574 ++Idx, ++I;
10575 } while (1);
10576 }
10577
10578 // Replace the trampoline call with a direct call. Let the generic
10579 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010580 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +000010581 FTy->isVarArg());
10582 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010583 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +000010584 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010585 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +000010586 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10587 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010588
10589 Instruction *NewCaller;
10590 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010591 NewCaller = InvokeInst::Create(NewCallee,
10592 II->getNormalDest(), II->getUnwindDest(),
10593 NewArgs.begin(), NewArgs.end(),
10594 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010595 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010596 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010597 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010598 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10599 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010600 if (cast<CallInst>(Caller)->isTailCall())
10601 cast<CallInst>(NewCaller)->setTailCall();
10602 cast<CallInst>(NewCaller)->
10603 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010604 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010605 }
Devang Patele9d08b82009-10-14 17:29:00 +000010606 if (!Caller->getType()->isVoidTy())
Duncan Sands74833f22007-09-17 10:26:40 +000010607 Caller->replaceAllUsesWith(NewCaller);
10608 Caller->eraseFromParent();
Chris Lattner3183fb62009-08-30 06:13:40 +000010609 Worklist.Remove(Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010610 return 0;
10611 }
10612 }
10613
10614 // Replace the trampoline call with a direct call. Since there is no 'nest'
10615 // parameter, there is no need to adjust the argument list. Let the generic
10616 // code sort out any function type mismatches.
10617 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010618 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +000010619 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010620 CS.setCalledFunction(NewCallee);
10621 return CS.getInstruction();
10622}
10623
Dan Gohman09cf2b62009-09-16 16:50:24 +000010624/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10625/// 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 +000010626/// and a single binop.
10627Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10628 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010629 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010630 unsigned Opc = FirstInst->getOpcode();
10631 Value *LHSVal = FirstInst->getOperand(0);
10632 Value *RHSVal = FirstInst->getOperand(1);
10633
10634 const Type *LHSType = LHSVal->getType();
10635 const Type *RHSType = RHSVal->getType();
10636
Dan Gohman09cf2b62009-09-16 16:50:24 +000010637 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010638 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010639 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10640 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10641 // Verify type of the LHS matches so we don't fold cmp's of different
10642 // types or GEP's with different index types.
10643 I->getOperand(0)->getType() != LHSType ||
10644 I->getOperand(1)->getType() != RHSType)
10645 return 0;
10646
10647 // If they are CmpInst instructions, check their predicates
10648 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10649 if (cast<CmpInst>(I)->getPredicate() !=
10650 cast<CmpInst>(FirstInst)->getPredicate())
10651 return 0;
10652
10653 // Keep track of which operand needs a phi node.
10654 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10655 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10656 }
Dan Gohman09cf2b62009-09-16 16:50:24 +000010657
10658 // If both LHS and RHS would need a PHI, don't do this transformation,
10659 // because it would increase the number of PHIs entering the block,
10660 // which leads to higher register pressure. This is especially
10661 // bad when the PHIs are in the header of a loop.
10662 if (!LHSVal && !RHSVal)
10663 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010664
Chris Lattner30078012008-12-01 03:42:51 +000010665 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010666
10667 Value *InLHS = FirstInst->getOperand(0);
10668 Value *InRHS = FirstInst->getOperand(1);
10669 PHINode *NewLHS = 0, *NewRHS = 0;
10670 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010671 NewLHS = PHINode::Create(LHSType,
10672 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010673 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10674 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10675 InsertNewInstBefore(NewLHS, PN);
10676 LHSVal = NewLHS;
10677 }
10678
10679 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010680 NewRHS = PHINode::Create(RHSType,
10681 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010682 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10683 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10684 InsertNewInstBefore(NewRHS, PN);
10685 RHSVal = NewRHS;
10686 }
10687
10688 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010689 if (NewLHS || NewRHS) {
10690 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10691 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10692 if (NewLHS) {
10693 Value *NewInLHS = InInst->getOperand(0);
10694 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10695 }
10696 if (NewRHS) {
10697 Value *NewInRHS = InInst->getOperand(1);
10698 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10699 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010700 }
10701 }
10702
10703 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010704 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010705 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohmane6803b82009-08-25 23:17:54 +000010706 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson6601fcd2009-07-09 23:48:35 +000010707 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010708}
10709
Chris Lattner9e1916e2008-12-01 02:34:36 +000010710Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10711 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10712
10713 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10714 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010715 // This is true if all GEP bases are allocas and if all indices into them are
10716 // constants.
10717 bool AllBasePointersAreAllocas = true;
Dan Gohman37a534b2009-09-16 02:01:52 +000010718
10719 // We don't want to replace this phi if the replacement would require
Dan Gohman09cf2b62009-09-16 16:50:24 +000010720 // more than one phi, which leads to higher register pressure. This is
10721 // especially bad when the PHIs are in the header of a loop.
Dan Gohman37a534b2009-09-16 02:01:52 +000010722 bool NeededPhi = false;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010723
Dan Gohman09cf2b62009-09-16 16:50:24 +000010724 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010725 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10726 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10727 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10728 GEP->getNumOperands() != FirstInst->getNumOperands())
10729 return 0;
10730
Chris Lattneradf354b2009-02-21 00:46:50 +000010731 // Keep track of whether or not all GEPs are of alloca pointers.
10732 if (AllBasePointersAreAllocas &&
10733 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10734 !GEP->hasAllConstantIndices()))
10735 AllBasePointersAreAllocas = false;
10736
Chris Lattner9e1916e2008-12-01 02:34:36 +000010737 // Compare the operand lists.
10738 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10739 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10740 continue;
10741
10742 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10743 // if one of the PHIs has a constant for the index. The index may be
10744 // substantially cheaper to compute for the constants, so making it a
10745 // variable index could pessimize the path. This also handles the case
10746 // for struct indices, which must always be constant.
10747 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10748 isa<ConstantInt>(GEP->getOperand(op)))
10749 return 0;
10750
10751 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10752 return 0;
Dan Gohman37a534b2009-09-16 02:01:52 +000010753
10754 // If we already needed a PHI for an earlier operand, and another operand
10755 // also requires a PHI, we'd be introducing more PHIs than we're
10756 // eliminating, which increases register pressure on entry to the PHI's
10757 // block.
10758 if (NeededPhi)
10759 return 0;
10760
Chris Lattner9e1916e2008-12-01 02:34:36 +000010761 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohman37a534b2009-09-16 02:01:52 +000010762 NeededPhi = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010763 }
10764 }
10765
Chris Lattneradf354b2009-02-21 00:46:50 +000010766 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010767 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010768 // offset calculation, but all the predecessors will have to materialize the
10769 // stack address into a register anyway. We'd actually rather *clone* the
10770 // load up into the predecessors so that we have a load of a gep of an alloca,
10771 // which can usually all be folded into the load.
10772 if (AllBasePointersAreAllocas)
10773 return 0;
10774
Chris Lattner9e1916e2008-12-01 02:34:36 +000010775 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10776 // that is variable.
10777 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10778
10779 bool HasAnyPHIs = false;
10780 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10781 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10782 Value *FirstOp = FirstInst->getOperand(i);
10783 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10784 FirstOp->getName()+".pn");
10785 InsertNewInstBefore(NewPN, PN);
10786
10787 NewPN->reserveOperandSpace(e);
10788 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10789 OperandPhis[i] = NewPN;
10790 FixedOperands[i] = NewPN;
10791 HasAnyPHIs = true;
10792 }
10793
10794
10795 // Add all operands to the new PHIs.
10796 if (HasAnyPHIs) {
10797 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10798 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10799 BasicBlock *InBB = PN.getIncomingBlock(i);
10800
10801 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10802 if (PHINode *OpPhi = OperandPhis[op])
10803 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10804 }
10805 }
10806
10807 Value *Base = FixedOperands[0];
Dan Gohmanf3a08b82009-09-07 23:54:19 +000010808 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10809 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10810 FixedOperands.end()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000010811 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10812 FixedOperands.end());
Chris Lattner9e1916e2008-12-01 02:34:36 +000010813}
10814
10815
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010816/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10817/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010818/// obvious the value of the load is not changed from the point of the load to
10819/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010820///
10821/// Finally, it is safe, but not profitable, to sink a load targetting a
10822/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10823/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010824static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010825 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10826
10827 for (++BBI; BBI != E; ++BBI)
10828 if (BBI->mayWriteToMemory())
10829 return false;
10830
10831 // Check for non-address taken alloca. If not address-taken already, it isn't
10832 // profitable to do this xform.
10833 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10834 bool isAddressTaken = false;
10835 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10836 UI != E; ++UI) {
10837 if (isa<LoadInst>(UI)) continue;
10838 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10839 // If storing TO the alloca, then the address isn't taken.
10840 if (SI->getOperand(1) == AI) continue;
10841 }
10842 isAddressTaken = true;
10843 break;
10844 }
10845
Chris Lattneradf354b2009-02-21 00:46:50 +000010846 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010847 return false;
10848 }
10849
Chris Lattneradf354b2009-02-21 00:46:50 +000010850 // If this load is a load from a GEP with a constant offset from an alloca,
10851 // then we don't want to sink it. In its present form, it will be
10852 // load [constant stack offset]. Sinking it will cause us to have to
10853 // materialize the stack addresses in each predecessor in a register only to
10854 // do a shared load from register in the successor.
10855 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10856 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10857 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10858 return false;
10859
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010860 return true;
10861}
10862
Chris Lattner38751f82009-11-01 20:04:24 +000010863Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10864 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10865
10866 // When processing loads, we need to propagate two bits of information to the
10867 // sunk load: whether it is volatile, and what its alignment is. We currently
10868 // don't sink loads when some have their alignment specified and some don't.
10869 // visitLoadInst will propagate an alignment onto the load when TD is around,
10870 // and if TD isn't around, we can't handle the mixed case.
10871 bool isVolatile = FirstLI->isVolatile();
10872 unsigned LoadAlignment = FirstLI->getAlignment();
10873
10874 // We can't sink the load if the loaded value could be modified between the
10875 // load and the PHI.
10876 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10877 !isSafeAndProfitableToSinkLoad(FirstLI))
10878 return 0;
10879
10880 // If the PHI is of volatile loads and the load block has multiple
10881 // successors, sinking it would remove a load of the volatile value from
10882 // the path through the other successor.
10883 if (isVolatile &&
10884 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10885 return 0;
10886
10887 // Check to see if all arguments are the same operation.
10888 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10889 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10890 if (!LI || !LI->hasOneUse())
10891 return 0;
10892
10893 // We can't sink the load if the loaded value could be modified between
10894 // the load and the PHI.
10895 if (LI->isVolatile() != isVolatile ||
10896 LI->getParent() != PN.getIncomingBlock(i) ||
10897 !isSafeAndProfitableToSinkLoad(LI))
10898 return 0;
10899
10900 // If some of the loads have an alignment specified but not all of them,
10901 // we can't do the transformation.
10902 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10903 return 0;
10904
Chris Lattner52fe1bc2009-11-01 20:07:07 +000010905 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner38751f82009-11-01 20:04:24 +000010906
10907 // If the PHI is of volatile loads and the load block has multiple
10908 // successors, sinking it would remove a load of the volatile value from
10909 // the path through the other successor.
10910 if (isVolatile &&
10911 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10912 return 0;
10913 }
10914
10915 // Okay, they are all the same operation. Create a new PHI node of the
10916 // correct type, and PHI together all of the LHS's of the instructions.
10917 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10918 PN.getName()+".in");
10919 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10920
10921 Value *InVal = FirstLI->getOperand(0);
10922 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10923
10924 // Add all operands to the new PHI.
10925 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10926 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10927 if (NewInVal != InVal)
10928 InVal = 0;
10929 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10930 }
10931
10932 Value *PhiVal;
10933 if (InVal) {
10934 // The new PHI unions all of the same values together. This is really
10935 // common, so we handle it intelligently here for compile-time speed.
10936 PhiVal = InVal;
10937 delete NewPN;
10938 } else {
10939 InsertNewInstBefore(NewPN, PN);
10940 PhiVal = NewPN;
10941 }
10942
10943 // If this was a volatile load that we are merging, make sure to loop through
10944 // and mark all the input loads as non-volatile. If we don't do this, we will
10945 // insert a new volatile load and the old ones will not be deletable.
10946 if (isVolatile)
10947 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10948 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10949
10950 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
10951}
10952
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010953
Chris Lattnerd0011092009-11-10 07:23:37 +000010954
10955/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10956/// operator and they all are only used by the PHI, PHI together their
10957/// inputs, and do the operation once, to the result of the PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010958Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10959 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10960
Chris Lattner38751f82009-11-01 20:04:24 +000010961 if (isa<GetElementPtrInst>(FirstInst))
10962 return FoldPHIArgGEPIntoPHI(PN);
10963 if (isa<LoadInst>(FirstInst))
10964 return FoldPHIArgLoadIntoPHI(PN);
10965
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010966 // Scan the instruction, looking for input operations that can be folded away.
10967 // If all input operands to the phi are the same instruction (e.g. a cast from
10968 // the same type or "+42") we can pull the operation through the PHI, reducing
10969 // code size and simplifying code.
10970 Constant *ConstantOp = 0;
10971 const Type *CastSrcTy = 0;
Chris Lattner310a00f2009-11-01 19:50:13 +000010972
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010973 if (isa<CastInst>(FirstInst)) {
10974 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattner4ca73902009-11-08 21:20:06 +000010975
10976 // Be careful about transforming integer PHIs. We don't want to pessimize
10977 // the code by turning an i32 into an i1293.
10978 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerd0011092009-11-10 07:23:37 +000010979 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattner4ca73902009-11-08 21:20:06 +000010980 return 0;
10981 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010982 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10983 // Can fold binop, compare or shift here if the RHS is a constant,
10984 // otherwise call FoldPHIArgBinOpIntoPHI.
10985 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10986 if (ConstantOp == 0)
10987 return FoldPHIArgBinOpIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010988 } else {
10989 return 0; // Cannot fold this operation.
10990 }
10991
10992 // Check to see if all arguments are the same operation.
10993 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner38751f82009-11-01 20:04:24 +000010994 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10995 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010996 return 0;
10997 if (CastSrcTy) {
10998 if (I->getOperand(0)->getType() != CastSrcTy)
10999 return 0; // Cast operation must match.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011000 } else if (I->getOperand(1) != ConstantOp) {
11001 return 0;
11002 }
11003 }
11004
11005 // Okay, they are all the same operation. Create a new PHI node of the
11006 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000011007 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11008 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011009 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11010
11011 Value *InVal = FirstInst->getOperand(0);
11012 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11013
11014 // Add all operands to the new PHI.
11015 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11016 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11017 if (NewInVal != InVal)
11018 InVal = 0;
11019 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11020 }
11021
11022 Value *PhiVal;
11023 if (InVal) {
11024 // The new PHI unions all of the same values together. This is really
11025 // common, so we handle it intelligently here for compile-time speed.
11026 PhiVal = InVal;
11027 delete NewPN;
11028 } else {
11029 InsertNewInstBefore(NewPN, PN);
11030 PhiVal = NewPN;
11031 }
11032
11033 // Insert and return the new operation.
Chris Lattner310a00f2009-11-01 19:50:13 +000011034 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000011035 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner310a00f2009-11-01 19:50:13 +000011036
Chris Lattnerfc984e92008-04-29 17:13:43 +000011037 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000011038 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner310a00f2009-11-01 19:50:13 +000011039
Chris Lattner38751f82009-11-01 20:04:24 +000011040 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11041 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11042 PhiVal, ConstantOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011043}
11044
11045/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11046/// that is dead.
11047static bool DeadPHICycle(PHINode *PN,
11048 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
11049 if (PN->use_empty()) return true;
11050 if (!PN->hasOneUse()) return false;
11051
11052 // Remember this node, and if we find the cycle, return.
11053 if (!PotentiallyDeadPHIs.insert(PN))
11054 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000011055
11056 // Don't scan crazily complex things.
11057 if (PotentiallyDeadPHIs.size() == 16)
11058 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011059
11060 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11061 return DeadPHICycle(PU, PotentiallyDeadPHIs);
11062
11063 return false;
11064}
11065
Chris Lattner27b695d2007-11-06 21:52:06 +000011066/// PHIsEqualValue - Return true if this phi node is always equal to
11067/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11068/// z = some value; x = phi (y, z); y = phi (x, z)
11069static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11070 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11071 // See if we already saw this PHI node.
11072 if (!ValueEqualPHIs.insert(PN))
11073 return true;
11074
11075 // Don't scan crazily complex things.
11076 if (ValueEqualPHIs.size() == 16)
11077 return false;
11078
11079 // Scan the operands to see if they are either phi nodes or are equal to
11080 // the value.
11081 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11082 Value *Op = PN->getIncomingValue(i);
11083 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11084 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11085 return false;
11086 } else if (Op != NonPhiInVal)
11087 return false;
11088 }
11089
11090 return true;
11091}
11092
11093
Chris Lattner1cd526b2009-11-08 19:23:30 +000011094namespace {
11095struct PHIUsageRecord {
Chris Lattner073c12c2009-11-09 01:38:00 +000011096 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner1cd526b2009-11-08 19:23:30 +000011097 unsigned Shift; // The amount shifted.
11098 Instruction *Inst; // The trunc instruction.
11099
Chris Lattner073c12c2009-11-09 01:38:00 +000011100 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11101 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner1cd526b2009-11-08 19:23:30 +000011102
11103 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattner073c12c2009-11-09 01:38:00 +000011104 if (PHIId < RHS.PHIId) return true;
11105 if (PHIId > RHS.PHIId) return false;
Chris Lattner1cd526b2009-11-08 19:23:30 +000011106 if (Shift < RHS.Shift) return true;
Chris Lattner073c12c2009-11-09 01:38:00 +000011107 if (Shift > RHS.Shift) return false;
11108 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner1cd526b2009-11-08 19:23:30 +000011109 RHS.Inst->getType()->getPrimitiveSizeInBits();
11110 }
11111};
Chris Lattner073c12c2009-11-09 01:38:00 +000011112
11113struct LoweredPHIRecord {
11114 PHINode *PN; // The PHI that was lowered.
11115 unsigned Shift; // The amount shifted.
11116 unsigned Width; // The width extracted.
11117
11118 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11119 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11120
11121 // Ctor form used by DenseMap.
11122 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11123 : PN(pn), Shift(Sh), Width(0) {}
11124};
11125}
11126
11127namespace llvm {
11128 template<>
11129 struct DenseMapInfo<LoweredPHIRecord> {
11130 static inline LoweredPHIRecord getEmptyKey() {
11131 return LoweredPHIRecord(0, 0);
11132 }
11133 static inline LoweredPHIRecord getTombstoneKey() {
11134 return LoweredPHIRecord(0, 1);
11135 }
11136 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11137 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11138 (Val.Width>>3);
11139 }
11140 static bool isEqual(const LoweredPHIRecord &LHS,
11141 const LoweredPHIRecord &RHS) {
11142 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11143 LHS.Width == RHS.Width;
11144 }
11145 static bool isPod() { return true; }
11146 };
Chris Lattner1cd526b2009-11-08 19:23:30 +000011147}
11148
11149
11150/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11151/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11152/// so, we split the PHI into the various pieces being extracted. This sort of
11153/// thing is introduced when SROA promotes an aggregate to large integer values.
11154///
11155/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11156/// inttoptr. We should produce new PHIs in the right type.
11157///
Chris Lattner073c12c2009-11-09 01:38:00 +000011158Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11159 // PHIUsers - Keep track of all of the truncated values extracted from a set
11160 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner1cd526b2009-11-08 19:23:30 +000011161 SmallVector<PHIUsageRecord, 16> PHIUsers;
11162
Chris Lattner073c12c2009-11-09 01:38:00 +000011163 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11164 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11165 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11166 // check the uses of (to ensure they are all extracts).
11167 SmallVector<PHINode*, 8> PHIsToSlice;
11168 SmallPtrSet<PHINode*, 8> PHIsInspected;
11169
11170 PHIsToSlice.push_back(&FirstPhi);
11171 PHIsInspected.insert(&FirstPhi);
11172
11173 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11174 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner1cd526b2009-11-08 19:23:30 +000011175
Chris Lattner073c12c2009-11-09 01:38:00 +000011176 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11177 UI != E; ++UI) {
11178 Instruction *User = cast<Instruction>(*UI);
11179
11180 // If the user is a PHI, inspect its uses recursively.
11181 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11182 if (PHIsInspected.insert(UserPN))
11183 PHIsToSlice.push_back(UserPN);
11184 continue;
11185 }
11186
11187 // Truncates are always ok.
11188 if (isa<TruncInst>(User)) {
11189 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11190 continue;
11191 }
11192
11193 // Otherwise it must be a lshr which can only be used by one trunc.
11194 if (User->getOpcode() != Instruction::LShr ||
11195 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11196 !isa<ConstantInt>(User->getOperand(1)))
11197 return 0;
11198
11199 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11200 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner1cd526b2009-11-08 19:23:30 +000011201 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011202 }
11203
11204 // If we have no users, they must be all self uses, just nuke the PHI.
11205 if (PHIUsers.empty())
Chris Lattner073c12c2009-11-09 01:38:00 +000011206 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner1cd526b2009-11-08 19:23:30 +000011207
11208 // If this phi node is transformable, create new PHIs for all the pieces
11209 // extracted out of it. First, sort the users by their offset and size.
11210 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11211
Chris Lattner073c12c2009-11-09 01:38:00 +000011212 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11213 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11214 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11215 );
Chris Lattner1cd526b2009-11-08 19:23:30 +000011216
Chris Lattner073c12c2009-11-09 01:38:00 +000011217 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11218 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner1cd526b2009-11-08 19:23:30 +000011219 DenseMap<BasicBlock*, Value*> PredValues;
11220
Chris Lattner073c12c2009-11-09 01:38:00 +000011221 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11222 // introduce redundant PHIs.
11223 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11224
11225 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11226 unsigned PHIId = PHIUsers[UserI].PHIId;
11227 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner1cd526b2009-11-08 19:23:30 +000011228 unsigned Offset = PHIUsers[UserI].Shift;
11229 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner1cd526b2009-11-08 19:23:30 +000011230
Chris Lattner073c12c2009-11-09 01:38:00 +000011231 PHINode *EltPHI;
11232
11233 // If we've already lowered a user like this, reuse the previously lowered
11234 // value.
11235 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner1cd526b2009-11-08 19:23:30 +000011236
Chris Lattner073c12c2009-11-09 01:38:00 +000011237 // Otherwise, Create the new PHI node for this user.
11238 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11239 assert(EltPHI->getType() != PN->getType() &&
11240 "Truncate didn't shrink phi?");
11241
11242 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11243 BasicBlock *Pred = PN->getIncomingBlock(i);
11244 Value *&PredVal = PredValues[Pred];
11245
11246 // If we already have a value for this predecessor, reuse it.
11247 if (PredVal) {
11248 EltPHI->addIncoming(PredVal, Pred);
11249 continue;
11250 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011251
Chris Lattner073c12c2009-11-09 01:38:00 +000011252 // Handle the PHI self-reuse case.
11253 Value *InVal = PN->getIncomingValue(i);
11254 if (InVal == PN) {
11255 PredVal = EltPHI;
11256 EltPHI->addIncoming(PredVal, Pred);
11257 continue;
11258 } else if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
11259 // If the incoming value was a PHI, and if it was one of the PHIs we
11260 // already rewrote it, just use the lowered value.
11261 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11262 PredVal = Res;
11263 EltPHI->addIncoming(PredVal, Pred);
11264 continue;
11265 }
11266 }
11267
11268 // Otherwise, do an extract in the predecessor.
11269 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11270 Value *Res = InVal;
11271 if (Offset)
11272 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11273 Offset), "extract");
11274 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11275 PredVal = Res;
11276 EltPHI->addIncoming(Res, Pred);
11277
11278 // If the incoming value was a PHI, and if it was one of the PHIs we are
11279 // rewriting, we will ultimately delete the code we inserted. This
11280 // means we need to revisit that PHI to make sure we extract out the
11281 // needed piece.
11282 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11283 if (PHIsInspected.count(OldInVal)) {
11284 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11285 OldInVal)-PHIsToSlice.begin();
11286 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11287 cast<Instruction>(Res)));
11288 ++UserE;
11289 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011290 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011291 PredValues.clear();
Chris Lattner1cd526b2009-11-08 19:23:30 +000011292
Chris Lattner073c12c2009-11-09 01:38:00 +000011293 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11294 << *EltPHI << '\n');
11295 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner1cd526b2009-11-08 19:23:30 +000011296 }
Chris Lattner1cd526b2009-11-08 19:23:30 +000011297
Chris Lattner073c12c2009-11-09 01:38:00 +000011298 // Replace the use of this piece with the PHI node.
11299 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner1cd526b2009-11-08 19:23:30 +000011300 }
Chris Lattner073c12c2009-11-09 01:38:00 +000011301
11302 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11303 // with undefs.
11304 Value *Undef = UndefValue::get(FirstPhi.getType());
11305 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11306 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11307 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner1cd526b2009-11-08 19:23:30 +000011308}
11309
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011310// PHINode simplification
11311//
11312Instruction *InstCombiner::visitPHINode(PHINode &PN) {
11313 // If LCSSA is around, don't mess with Phi nodes
11314 if (MustPreserveLCSSA) return 0;
11315
11316 if (Value *V = PN.hasConstantValue())
11317 return ReplaceInstUsesWith(PN, V);
11318
11319 // If all PHI operands are the same operation, pull them through the PHI,
11320 // reducing code size.
11321 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000011322 isa<Instruction>(PN.getIncomingValue(1)) &&
11323 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11324 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11325 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11326 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011327 PN.getIncomingValue(0)->hasOneUse())
11328 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11329 return Result;
11330
11331 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11332 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11333 // PHI)... break the cycle.
11334 if (PN.hasOneUse()) {
11335 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11336 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
11337 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
11338 PotentiallyDeadPHIs.insert(&PN);
11339 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011340 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011341 }
11342
11343 // If this phi has a single use, and if that use just computes a value for
11344 // the next iteration of a loop, delete the phi. This occurs with unused
11345 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11346 // common case here is good because the only other things that catch this
11347 // are induction variable analysis (sometimes) and ADCE, which is only run
11348 // late.
11349 if (PHIUser->hasOneUse() &&
11350 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11351 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000011352 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011353 }
11354 }
11355
Chris Lattner27b695d2007-11-06 21:52:06 +000011356 // We sometimes end up with phi cycles that non-obviously end up being the
11357 // same value, for example:
11358 // z = some value; x = phi (y, z); y = phi (x, z)
11359 // where the phi nodes don't necessarily need to be in the same block. Do a
11360 // quick check to see if the PHI node only contains a single non-phi value, if
11361 // so, scan to see if the phi cycle is actually equal to that value.
11362 {
11363 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11364 // Scan for the first non-phi operand.
11365 while (InValNo != NumOperandVals &&
11366 isa<PHINode>(PN.getIncomingValue(InValNo)))
11367 ++InValNo;
11368
11369 if (InValNo != NumOperandVals) {
11370 Value *NonPhiInVal = PN.getOperand(InValNo);
11371
11372 // Scan the rest of the operands to see if there are any conflicts, if so
11373 // there is no need to recursively scan other phis.
11374 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11375 Value *OpVal = PN.getIncomingValue(InValNo);
11376 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11377 break;
11378 }
11379
11380 // If we scanned over all operands, then we have one unique value plus
11381 // phi values. Scan PHI nodes to see if they all merge in each other or
11382 // the value.
11383 if (InValNo == NumOperandVals) {
11384 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11385 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11386 return ReplaceInstUsesWith(PN, NonPhiInVal);
11387 }
11388 }
11389 }
Dan Gohman012d03d2009-10-30 22:22:22 +000011390
Dan Gohman2cc8e842009-10-31 14:22:52 +000011391 // If there are multiple PHIs, sort their operands so that they all list
11392 // the blocks in the same order. This will help identical PHIs be eliminated
11393 // by other passes. Other passes shouldn't depend on this for correctness
11394 // however.
11395 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11396 if (&PN != FirstPN)
11397 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman012d03d2009-10-30 22:22:22 +000011398 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman2cc8e842009-10-31 14:22:52 +000011399 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11400 if (BBA != BBB) {
11401 Value *VA = PN.getIncomingValue(i);
11402 unsigned j = PN.getBasicBlockIndex(BBB);
11403 Value *VB = PN.getIncomingValue(j);
11404 PN.setIncomingBlock(i, BBB);
11405 PN.setIncomingValue(i, VB);
11406 PN.setIncomingBlock(j, BBA);
11407 PN.setIncomingValue(j, VA);
Chris Lattnerd56c0cb2009-10-31 17:48:31 +000011408 // NOTE: Instcombine normally would want us to "return &PN" if we
11409 // modified any of the operands of an instruction. However, since we
11410 // aren't adding or removing uses (just rearranging them) we don't do
11411 // this in this case.
Dan Gohman2cc8e842009-10-31 14:22:52 +000011412 }
Dan Gohman012d03d2009-10-30 22:22:22 +000011413 }
11414
Chris Lattner1cd526b2009-11-08 19:23:30 +000011415 // If this is an integer PHI and we know that it has an illegal type, see if
11416 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11417 // PHI into the various pieces being extracted. This sort of thing is
11418 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattner4ca73902009-11-08 21:20:06 +000011419 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner1cd526b2009-11-08 19:23:30 +000011420 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11421 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11422 return Res;
11423
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011424 return 0;
11425}
11426
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011427Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5594a482009-11-27 00:29:05 +000011428 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11429
11430 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11431 return ReplaceInstUsesWith(GEP, V);
11432
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011433 Value *PtrOp = GEP.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011434
11435 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011436 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011437
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011438 // Eliminate unneeded casts for indices.
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011439 if (TD) {
11440 bool MadeChange = false;
11441 unsigned PtrSize = TD->getPointerSizeInBits();
11442
11443 gep_type_iterator GTI = gep_type_begin(GEP);
11444 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11445 I != E; ++I, ++GTI) {
11446 if (!isa<SequentialType>(*GTI)) continue;
11447
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011448 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011449 // to what we need. If narrower, sign-extend it to what we need. This
11450 // explicit cast can make subsequent optimizations more obvious.
11451 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011452 if (OpBits == PtrSize)
11453 continue;
11454
Chris Lattnerd6164c22009-08-30 20:01:10 +000011455 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011456 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011457 }
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011458 if (MadeChange) return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011459 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011460
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011461 // Combine Indices - If the source pointer to this getelementptr instruction
11462 // is a getelementptr instruction, combine the indices of the two
11463 // getelementptr instructions into a single instruction.
11464 //
Dan Gohman17f46f72009-07-28 01:40:03 +000011465 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011466 // Note that if our source is a gep chain itself that we wait for that
11467 // chain to be resolved before we perform this transformation. This
11468 // avoids us creating a TON of code in some cases.
11469 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011470 if (GetElementPtrInst *SrcGEP =
11471 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11472 if (SrcGEP->getNumOperands() == 2)
11473 return 0; // Wait until our source is folded to completion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011474
11475 SmallVector<Value*, 8> Indices;
11476
11477 // Find out whether the last index in the source GEP is a sequential idx.
11478 bool EndsWithSequential = false;
Chris Lattner1c641fc2009-08-30 05:30:55 +000011479 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11480 I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011481 EndsWithSequential = !isa<StructType>(*I);
11482
11483 // Can we combine the two pointer arithmetics offsets?
11484 if (EndsWithSequential) {
11485 // Replace: gep (gep %P, long B), long A, ...
11486 // With: T = long A+B; gep %P, T, ...
11487 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011488 Value *Sum;
11489 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11490 Value *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +000011491 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011492 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +000011493 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011494 Sum = SO1;
11495 } else {
Chris Lattner1c641fc2009-08-30 05:30:55 +000011496 // If they aren't the same type, then the input hasn't been processed
11497 // by the loop above yet (which canonicalizes sequential index types to
11498 // intptr_t). Just avoid transforming this until the input has been
11499 // normalized.
11500 if (SO1->getType() != GO1->getType())
11501 return 0;
Chris Lattnerad7516a2009-08-30 18:50:58 +000011502 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011503 }
11504
Chris Lattner1c641fc2009-08-30 05:30:55 +000011505 // Update the GEP in place if possible.
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011506 if (Src->getNumOperands() == 2) {
11507 GEP.setOperand(0, Src->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011508 GEP.setOperand(1, Sum);
11509 return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011510 }
Chris Lattner1c641fc2009-08-30 05:30:55 +000011511 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011512 Indices.push_back(Sum);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011513 Indices.append(GEP.op_begin()+2, GEP.op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011514 } else if (isa<Constant>(*GEP.idx_begin()) &&
11515 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011516 Src->getNumOperands() != 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011517 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner1c641fc2009-08-30 05:30:55 +000011518 Indices.append(Src->op_begin()+1, Src->op_end());
11519 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011520 }
11521
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011522 if (!Indices.empty())
11523 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11524 Src->isInBounds()) ?
11525 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11526 Indices.end(), GEP.getName()) :
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011527 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerc0f553e2009-08-30 04:49:01 +000011528 Indices.end(), GEP.getName());
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011529 }
11530
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +000011531 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11532 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011533 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattnerf3a23592009-08-30 20:36:46 +000011534
Chris Lattner83288fa2009-08-30 20:38:21 +000011535 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11536 // want to change the gep until the bitcasts are eliminated.
11537 if (getBitCastOperand(X)) {
11538 Worklist.AddValue(PtrOp);
11539 return 0;
11540 }
11541
Chris Lattner5594a482009-11-27 00:29:05 +000011542 bool HasZeroPointerIndex = false;
11543 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
11544 HasZeroPointerIndex = C->isZero();
11545
Chris Lattnerf3a23592009-08-30 20:36:46 +000011546 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11547 // into : GEP [10 x i8]* X, i32 0, ...
11548 //
11549 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11550 // into : GEP i8* X, ...
11551 //
11552 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner95ba1ec2009-08-30 05:00:50 +000011553 if (HasZeroPointerIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011554 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11555 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011556 if (const ArrayType *CATy =
11557 dyn_cast<ArrayType>(CPTy->getElementType())) {
11558 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11559 if (CATy->getElementType() == XTy->getElementType()) {
11560 // -> GEP i8* X, ...
11561 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011562 return cast<GEPOperator>(&GEP)->isInBounds() ?
11563 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11564 GEP.getName()) :
Dan Gohman17f46f72009-07-28 01:40:03 +000011565 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11566 GEP.getName());
Chris Lattnerf3a23592009-08-30 20:36:46 +000011567 }
11568
11569 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sandscf866e62009-03-02 09:18:21 +000011570 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011571 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011572 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011573 // At this point, we know that the cast source type is a pointer
11574 // to an array of the same type as the destination pointer
11575 // array. Because the array type is never stepped over (there
11576 // is a leading zero) we can fold the cast into this GEP.
11577 GEP.setOperand(0, X);
11578 return &GEP;
11579 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011580 }
11581 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011582 } else if (GEP.getNumOperands() == 2) {
11583 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011584 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11585 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011586 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11587 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000011588 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011589 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11590 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011591 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011592 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011593 Idx[1] = GEP.getOperand(1);
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011594 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11595 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerad7516a2009-08-30 18:50:58 +000011596 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011597 // V and GEP are both pointer types --> BitCast
Chris Lattnerad7516a2009-08-30 18:50:58 +000011598 return new BitCastInst(NewGEP, GEP.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011599 }
11600
11601 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011602 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011603 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011604 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011605
Owen Anderson35b47072009-08-13 21:58:54 +000011606 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011607 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011608 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011609
11610 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11611 // allow either a mul, shift, or constant here.
11612 Value *NewIdx = 0;
11613 ConstantInt *Scale = 0;
11614 if (ArrayEltSize == 1) {
11615 NewIdx = GEP.getOperand(1);
Chris Lattner1c641fc2009-08-30 05:30:55 +000011616 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011617 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011618 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011619 Scale = CI;
11620 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11621 if (Inst->getOpcode() == Instruction::Shl &&
11622 isa<ConstantInt>(Inst->getOperand(1))) {
11623 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11624 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +000011625 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011626 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011627 NewIdx = Inst->getOperand(0);
11628 } else if (Inst->getOpcode() == Instruction::Mul &&
11629 isa<ConstantInt>(Inst->getOperand(1))) {
11630 Scale = cast<ConstantInt>(Inst->getOperand(1));
11631 NewIdx = Inst->getOperand(0);
11632 }
11633 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011634
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011635 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011636 // out, perform the transformation. Note, we don't know whether Scale is
11637 // signed or not. We'll use unsigned version of division/modulo
11638 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011639 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011640 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011641 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011642 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011643 if (Scale->getZExtValue() != 1) {
Chris Lattnerbf09d632009-08-30 05:56:44 +000011644 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11645 false /*ZExt*/);
Chris Lattnerad7516a2009-08-30 18:50:58 +000011646 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011647 }
11648
11649 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011650 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011651 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011652 Idx[1] = NewIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011653 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11654 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11655 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011656 // The NewGEP must be pointer typed, so must the old one -> BitCast
11657 return new BitCastInst(NewGEP, GEP.getType());
11658 }
11659 }
11660 }
11661 }
Chris Lattner111ea772009-01-09 04:53:57 +000011662
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011663 /// See if we can simplify:
Chris Lattner5119c702009-08-30 05:55:36 +000011664 /// X = bitcast A* to B*
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011665 /// Y = gep X, <...constant indices...>
11666 /// into a gep of the original struct. This is important for SROA and alias
11667 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011668 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011669 if (TD &&
11670 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011671 // Determine how much the GEP moves the pointer. We are guaranteed to get
11672 // a constant back from EmitGEPOffset.
Chris Lattner93e6ff92009-11-04 08:05:20 +000011673 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011674 int64_t Offset = OffsetV->getSExtValue();
11675
11676 // If this GEP instruction doesn't move the pointer, just replace the GEP
11677 // with a bitcast of the real input to the dest type.
11678 if (Offset == 0) {
11679 // If the bitcast is of an allocation, and the allocation will be
11680 // converted to match the type of the cast, don't touch this.
Victor Hernandezb1687302009-10-23 21:09:37 +000011681 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez48c3c542009-09-18 22:35:49 +000011682 isMalloc(BCI->getOperand(0))) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011683 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11684 if (Instruction *I = visitBitCast(*BCI)) {
11685 if (I != BCI) {
11686 I->takeName(BCI);
11687 BCI->getParent()->getInstList().insert(BCI, I);
11688 ReplaceInstUsesWith(*BCI, I);
11689 }
11690 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011691 }
Chris Lattner111ea772009-01-09 04:53:57 +000011692 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011693 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011694 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011695
11696 // Otherwise, if the offset is non-zero, we need to find out if there is a
11697 // field at Offset in 'A's type. If so, we can pull the cast through the
11698 // GEP.
11699 SmallVector<Value*, 8> NewIndices;
11700 const Type *InTy =
11701 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000011702 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011703 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11704 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11705 NewIndices.end()) :
11706 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11707 NewIndices.end());
Chris Lattnerad7516a2009-08-30 18:50:58 +000011708
11709 if (NGEP->getType() == GEP.getType())
11710 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011711 NGEP->takeName(&GEP);
11712 return new BitCastInst(NGEP, GEP.getType());
11713 }
Chris Lattner111ea772009-01-09 04:53:57 +000011714 }
11715 }
11716
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011717 return 0;
11718}
11719
Victor Hernandezb1687302009-10-23 21:09:37 +000011720Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattner310a00f2009-11-01 19:50:13 +000011721 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011722 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011723 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11724 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011725 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandez37f513d2009-10-17 01:18:07 +000011726 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandezb1687302009-10-23 21:09:37 +000011727 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerad7516a2009-08-30 18:50:58 +000011728 New->setAlignment(AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011729
11730 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011731 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011732 //
11733 BasicBlock::iterator It = New;
Victor Hernandezb1687302009-10-23 21:09:37 +000011734 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011735
11736 // Now that I is pointing to the first non-allocation-inst in the block,
11737 // insert our getelementptr instruction...
11738 //
Owen Anderson35b47072009-08-13 21:58:54 +000011739 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011740 Value *Idx[2];
11741 Idx[0] = NullIdx;
11742 Idx[1] = NullIdx;
Dan Gohmanf3a08b82009-09-07 23:54:19 +000011743 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11744 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011745
11746 // Now make everything use the getelementptr instead of the original
11747 // allocation.
11748 return ReplaceInstUsesWith(AI, V);
11749 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +000011750 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011751 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011752 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011753
Dan Gohmana80e2712009-07-21 23:21:54 +000011754 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000011755 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011756 // Note that we only do this for alloca's, because malloc should allocate
11757 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011758 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +000011759 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000011760
11761 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11762 if (AI.getAlignment() == 0)
11763 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11764 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011765
11766 return 0;
11767}
11768
Victor Hernandez93946082009-10-24 04:23:03 +000011769Instruction *InstCombiner::visitFree(Instruction &FI) {
11770 Value *Op = FI.getOperand(1);
11771
11772 // free undef -> unreachable.
11773 if (isa<UndefValue>(Op)) {
11774 // Insert a new store to null because we cannot modify the CFG here.
11775 new StoreInst(ConstantInt::getTrue(*Context),
11776 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11777 return EraseInstFromFunction(FI);
11778 }
11779
11780 // If we have 'free null' delete the instruction. This can happen in stl code
11781 // when lots of inlining happens.
11782 if (isa<ConstantPointerNull>(Op))
11783 return EraseInstFromFunction(FI);
11784
Victor Hernandezf9a7a332009-10-26 23:43:48 +000011785 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman1674ea52009-10-27 00:11:02 +000011786 if (isMalloc(Op)) {
Victor Hernandez93946082009-10-24 04:23:03 +000011787 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11788 if (Op->hasOneUse() && CI->hasOneUse()) {
11789 EraseInstFromFunction(FI);
11790 EraseInstFromFunction(*CI);
11791 return EraseInstFromFunction(*cast<Instruction>(Op));
11792 }
11793 } else {
11794 // Op is a call to malloc
11795 if (Op->hasOneUse()) {
11796 EraseInstFromFunction(FI);
11797 return EraseInstFromFunction(*cast<Instruction>(Op));
11798 }
11799 }
Dan Gohman1674ea52009-10-27 00:11:02 +000011800 }
Victor Hernandez93946082009-10-24 04:23:03 +000011801
11802 return 0;
11803}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011804
11805/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011806static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011807 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011808 User *CI = cast<User>(LI.getOperand(0));
11809 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011810 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011811
Mon P Wangbd05ed82009-02-07 22:19:29 +000011812 const PointerType *DestTy = cast<PointerType>(CI->getType());
11813 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011814 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011815
11816 // If the address spaces don't match, don't eliminate the cast.
11817 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11818 return 0;
11819
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011820 const Type *SrcPTy = SrcTy->getElementType();
11821
11822 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11823 isa<VectorType>(DestPTy)) {
11824 // If the source is an array, the code below will not succeed. Check to
11825 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11826 // constants.
11827 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11828 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11829 if (ASrcTy->getNumElements() != 0) {
11830 Value *Idxs[2];
Chris Lattner7bdc6d52009-10-22 06:44:07 +000011831 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11832 Idxs[1] = Idxs[0];
Owen Anderson02b48c32009-07-29 18:55:55 +000011833 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011834 SrcTy = cast<PointerType>(CastOp->getType());
11835 SrcPTy = SrcTy->getElementType();
11836 }
11837
Dan Gohmana80e2712009-07-21 23:21:54 +000011838 if (IC.getTargetData() &&
11839 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011840 isa<VectorType>(SrcPTy)) &&
11841 // Do not allow turning this into a load of an integer, which is then
11842 // casted to a pointer, this pessimizes pointer analysis a lot.
11843 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000011844 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11845 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011846
11847 // Okay, we are casting from one integer or pointer type to another of
11848 // the same size. Instead of casting the pointer before the load, cast
11849 // the result of the loaded value.
Chris Lattnerad7516a2009-08-30 18:50:58 +000011850 Value *NewLoad =
11851 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011852 // Now cast the result of the load.
11853 return new BitCastInst(NewLoad, LI.getType());
11854 }
11855 }
11856 }
11857 return 0;
11858}
11859
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011860Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11861 Value *Op = LI.getOperand(0);
11862
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011863 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011864 if (TD) {
11865 unsigned KnownAlign =
11866 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11867 if (KnownAlign >
11868 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11869 LI.getAlignment()))
11870 LI.setAlignment(KnownAlign);
11871 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011872
Chris Lattnerf3a23592009-08-30 20:36:46 +000011873 // load (cast X) --> cast (load X) iff safe.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011874 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011875 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011876 return Res;
11877
11878 // None of the following transforms are legal for volatile loads.
11879 if (LI.isVolatile()) return 0;
11880
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011881 // Do really simple store-to-load forwarding and load CSE, to catch cases
11882 // where there are several consequtive memory accesses to the same location,
11883 // separated by a few arithmetic operations.
11884 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011885 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11886 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011887
Chris Lattner05274832009-10-22 06:25:11 +000011888 // load(gep null, ...) -> unreachable
Christopher Lamb2c175392007-12-29 07:56:53 +000011889 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11890 const Value *GEPI0 = GEPI->getOperand(0);
11891 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +000011892 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011893 // Insert a new store to null instruction before the load to indicate
11894 // that this code is not reachable. We do this instead of inserting
11895 // an unreachable instruction directly because we cannot modify the
11896 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011897 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011898 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011899 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011900 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011901 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011902
Chris Lattner05274832009-10-22 06:25:11 +000011903 // load null/undef -> unreachable
11904 // TODO: Consider a target hook for valid address spaces for this xform.
11905 if (isa<UndefValue>(Op) ||
11906 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11907 // Insert a new store to null instruction before the load to indicate that
11908 // this code is not reachable. We do this instead of inserting an
11909 // unreachable instruction directly because we cannot modify the CFG.
11910 new StoreInst(UndefValue::get(LI.getType()),
11911 Constant::getNullValue(Op->getType()), &LI);
11912 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011913 }
Chris Lattner05274832009-10-22 06:25:11 +000011914
11915 // Instcombine load (constantexpr_cast global) -> cast (load global)
11916 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11917 if (CE->isCast())
11918 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11919 return Res;
11920
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011921 if (Op->hasOneUse()) {
11922 // Change select and PHI nodes to select values instead of addresses: this
11923 // helps alias analysis out a lot, allows many others simplifications, and
11924 // exposes redundancy in the code.
11925 //
11926 // Note that we cannot do the transformation unless we know that the
11927 // introduced loads cannot trap! Something like this is valid as long as
11928 // the condition is always false: load (select bool %C, int* null, int* %G),
11929 // but it would not be valid if we transformed it to load from null
11930 // unconditionally.
11931 //
11932 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11933 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11934 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11935 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerad7516a2009-08-30 18:50:58 +000011936 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11937 SI->getOperand(1)->getName()+".val");
11938 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11939 SI->getOperand(2)->getName()+".val");
Gabor Greifd6da1d02008-04-06 20:25:17 +000011940 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011941 }
11942
11943 // load (select (cond, null, P)) -> load P
11944 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11945 if (C->isNullValue()) {
11946 LI.setOperand(0, SI->getOperand(2));
11947 return &LI;
11948 }
11949
11950 // load (select (cond, P, null)) -> load P
11951 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11952 if (C->isNullValue()) {
11953 LI.setOperand(0, SI->getOperand(1));
11954 return &LI;
11955 }
11956 }
11957 }
11958 return 0;
11959}
11960
11961/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011962/// when possible. This makes it generally easy to do alias analysis and/or
11963/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011964static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11965 User *CI = cast<User>(SI.getOperand(1));
11966 Value *CastOp = CI->getOperand(0);
11967
11968 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011969 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11970 if (SrcTy == 0) return 0;
11971
11972 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011973
Chris Lattnera032c0e2009-01-16 20:08:59 +000011974 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11975 return 0;
11976
Chris Lattner54dddc72009-01-24 01:00:13 +000011977 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11978 /// to its first element. This allows us to handle things like:
11979 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11980 /// on 32-bit hosts.
11981 SmallVector<Value*, 4> NewGEPIndices;
11982
Chris Lattnera032c0e2009-01-16 20:08:59 +000011983 // If the source is an array, the code below will not succeed. Check to
11984 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11985 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011986 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11987 // Index through pointer.
Owen Anderson35b47072009-08-13 21:58:54 +000011988 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner54dddc72009-01-24 01:00:13 +000011989 NewGEPIndices.push_back(Zero);
11990
11991 while (1) {
11992 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011993 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011994 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011995 NewGEPIndices.push_back(Zero);
11996 SrcPTy = STy->getElementType(0);
11997 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11998 NewGEPIndices.push_back(Zero);
11999 SrcPTy = ATy->getElementType();
12000 } else {
12001 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012002 }
Chris Lattner54dddc72009-01-24 01:00:13 +000012003 }
12004
Owen Anderson6b6e2d92009-07-29 22:17:13 +000012005 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000012006 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000012007
12008 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12009 return 0;
12010
Chris Lattnerc73a0d12009-01-16 20:12:52 +000012011 // If the pointers point into different address spaces or if they point to
12012 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000012013 if (!IC.getTargetData() ||
12014 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000012015 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000012016 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12017 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000012018 return 0;
12019
12020 // Okay, we are casting from one integer or pointer type to another of
12021 // the same size. Instead of casting the pointer before
12022 // the store, cast the value to be stored.
12023 Value *NewCast;
12024 Value *SIOp0 = SI.getOperand(0);
12025 Instruction::CastOps opcode = Instruction::BitCast;
12026 const Type* CastSrcTy = SIOp0->getType();
12027 const Type* CastDstTy = SrcPTy;
12028 if (isa<PointerType>(CastDstTy)) {
12029 if (CastSrcTy->isInteger())
12030 opcode = Instruction::IntToPtr;
12031 } else if (isa<IntegerType>(CastDstTy)) {
12032 if (isa<PointerType>(SIOp0->getType()))
12033 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012034 }
Chris Lattner54dddc72009-01-24 01:00:13 +000012035
12036 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12037 // emit a GEP to index into its first field.
Dan Gohmanf3a08b82009-09-07 23:54:19 +000012038 if (!NewGEPIndices.empty())
12039 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12040 NewGEPIndices.end());
Chris Lattner54dddc72009-01-24 01:00:13 +000012041
Chris Lattnerad7516a2009-08-30 18:50:58 +000012042 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12043 SIOp0->getName()+".c");
Chris Lattnera032c0e2009-01-16 20:08:59 +000012044 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012045}
12046
Chris Lattner6fd8c802008-11-27 08:56:30 +000012047/// equivalentAddressValues - Test if A and B will obviously have the same
12048/// value. This includes recognizing that %t0 and %t1 will have the same
12049/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000012050/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000012051/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000012052/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000012053/// %t2 = load i32* %t1
12054///
12055static bool equivalentAddressValues(Value *A, Value *B) {
12056 // Test if the values are trivially equivalent.
12057 if (A == B) return true;
12058
12059 // Test if the values come form identical arithmetic instructions.
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000012060 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12061 // its only used to compare two uses within the same basic block, which
12062 // means that they'll always either have the same value or one of them
12063 // will have an undefined value.
Chris Lattner6fd8c802008-11-27 08:56:30 +000012064 if (isa<BinaryOperator>(A) ||
12065 isa<CastInst>(A) ||
12066 isa<PHINode>(A) ||
12067 isa<GetElementPtrInst>(A))
12068 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000012069 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner6fd8c802008-11-27 08:56:30 +000012070 return true;
12071
12072 // Otherwise they may not be equivalent.
12073 return false;
12074}
12075
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012076// If this instruction has two uses, one of which is a llvm.dbg.declare,
12077// return the llvm.dbg.declare.
12078DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12079 if (!V->hasNUses(2))
12080 return 0;
12081 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12082 UI != E; ++UI) {
12083 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12084 return DI;
12085 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12086 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12087 return DI;
12088 }
12089 }
12090 return 0;
12091}
12092
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012093Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12094 Value *Val = SI.getOperand(0);
12095 Value *Ptr = SI.getOperand(1);
12096
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012097 // If the RHS is an alloca with a single use, zapify the store, making the
12098 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012099 // If the RHS is an alloca with a two uses, the other one being a
12100 // llvm.dbg.declare, zapify the store and the declare, making the
12101 // alloca dead. We must do this to prevent declare's from affecting
12102 // codegen.
12103 if (!SI.isVolatile()) {
12104 if (Ptr->hasOneUse()) {
12105 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012106 EraseInstFromFunction(SI);
12107 ++NumCombined;
12108 return 0;
12109 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000012110 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12111 if (isa<AllocaInst>(GEP->getOperand(0))) {
12112 if (GEP->getOperand(0)->hasOneUse()) {
12113 EraseInstFromFunction(SI);
12114 ++NumCombined;
12115 return 0;
12116 }
12117 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12118 EraseInstFromFunction(*DI);
12119 EraseInstFromFunction(SI);
12120 ++NumCombined;
12121 return 0;
12122 }
12123 }
12124 }
12125 }
12126 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12127 EraseInstFromFunction(*DI);
12128 EraseInstFromFunction(SI);
12129 ++NumCombined;
12130 return 0;
12131 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012132 }
12133
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012134 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000012135 if (TD) {
12136 unsigned KnownAlign =
12137 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12138 if (KnownAlign >
12139 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12140 SI.getAlignment()))
12141 SI.setAlignment(KnownAlign);
12142 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000012143
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012144 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012145 // stores to the same location, separated by a few arithmetic operations. This
12146 // situation often occurs with bitfield accesses.
12147 BasicBlock::iterator BBI = &SI;
12148 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12149 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000012150 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000012151 // Don't count debug info directives, lest they affect codegen,
12152 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12153 // It is necessary for correctness to skip those that feed into a
12154 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000012155 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000012156 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012157 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000012158 continue;
12159 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012160
12161 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12162 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000012163 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12164 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012165 ++NumDeadStore;
12166 ++BBI;
12167 EraseInstFromFunction(*PrevSI);
12168 continue;
12169 }
12170 break;
12171 }
12172
12173 // If this is a load, we have to stop. However, if the loaded value is from
12174 // the pointer we're loading and is producing the pointer we're storing,
12175 // then *this* store is dead (X = load P; store X -> P).
12176 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000012177 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12178 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012179 EraseInstFromFunction(SI);
12180 ++NumCombined;
12181 return 0;
12182 }
12183 // Otherwise, this is a load from some other location. Stores before it
12184 // may not be dead.
12185 break;
12186 }
12187
12188 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000012189 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012190 break;
12191 }
12192
12193
12194 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
12195
12196 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner6807a242009-08-30 20:06:40 +000012197 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012198 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012199 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012200 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner3183fb62009-08-30 06:13:40 +000012201 Worklist.Add(U); // Dropped a use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012202 ++NumCombined;
12203 }
12204 return 0; // Do not modify these!
12205 }
12206
12207 // store undef, Ptr -> noop
12208 if (isa<UndefValue>(Val)) {
12209 EraseInstFromFunction(SI);
12210 ++NumCombined;
12211 return 0;
12212 }
12213
12214 // If the pointer destination is a cast, see if we can fold the cast into the
12215 // source instead.
12216 if (isa<CastInst>(Ptr))
12217 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12218 return Res;
12219 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
12220 if (CE->isCast())
12221 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12222 return Res;
12223
12224
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012225 // If this store is the last instruction in the basic block (possibly
12226 // excepting debug info instructions and the pointer bitcasts that feed
12227 // into them), and if the block ends with an unconditional branch, try
12228 // to move it to the successor block.
12229 BBI = &SI;
12230 do {
12231 ++BBI;
12232 } while (isa<DbgInfoIntrinsic>(BBI) ||
12233 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012234 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
12235 if (BI->isUnconditional())
12236 if (SimplifyStoreAtEndOfBlock(SI))
12237 return 0; // xform done!
12238
12239 return 0;
12240}
12241
12242/// SimplifyStoreAtEndOfBlock - Turn things like:
12243/// if () { *P = v1; } else { *P = v2 }
12244/// into a phi node with a store in the successor.
12245///
12246/// Simplify things like:
12247/// *P = v1; if () { *P = v2; }
12248/// into a phi node with a store in the successor.
12249///
12250bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12251 BasicBlock *StoreBB = SI.getParent();
12252
12253 // Check to see if the successor block has exactly two incoming edges. If
12254 // so, see if the other predecessor contains a store to the same location.
12255 // if so, insert a PHI node (if needed) and move the stores down.
12256 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12257
12258 // Determine whether Dest has exactly two predecessors and, if so, compute
12259 // the other predecessor.
12260 pred_iterator PI = pred_begin(DestBB);
12261 BasicBlock *OtherBB = 0;
12262 if (*PI != StoreBB)
12263 OtherBB = *PI;
12264 ++PI;
12265 if (PI == pred_end(DestBB))
12266 return false;
12267
12268 if (*PI != StoreBB) {
12269 if (OtherBB)
12270 return false;
12271 OtherBB = *PI;
12272 }
12273 if (++PI != pred_end(DestBB))
12274 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000012275
12276 // Bail out if all the relevant blocks aren't distinct (this can happen,
12277 // for example, if SI is in an infinite loop)
12278 if (StoreBB == DestBB || OtherBB == DestBB)
12279 return false;
12280
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012281 // Verify that the other block ends in a branch and is not otherwise empty.
12282 BasicBlock::iterator BBI = OtherBB->getTerminator();
12283 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12284 if (!OtherBr || BBI == OtherBB->begin())
12285 return false;
12286
12287 // If the other block ends in an unconditional branch, check for the 'if then
12288 // else' case. there is an instruction before the branch.
12289 StoreInst *OtherStore = 0;
12290 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012291 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012292 // Skip over debugging info.
12293 while (isa<DbgInfoIntrinsic>(BBI) ||
12294 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12295 if (BBI==OtherBB->begin())
12296 return false;
12297 --BBI;
12298 }
Chris Lattner69fa3f52009-11-02 02:06:37 +000012299 // If this isn't a store, isn't a store to the same location, or if the
12300 // alignments differ, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012301 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner69fa3f52009-11-02 02:06:37 +000012302 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12303 OtherStore->getAlignment() != SI.getAlignment())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012304 return false;
12305 } else {
12306 // Otherwise, the other block ended with a conditional branch. If one of the
12307 // destinations is StoreBB, then we have the if/then case.
12308 if (OtherBr->getSuccessor(0) != StoreBB &&
12309 OtherBr->getSuccessor(1) != StoreBB)
12310 return false;
12311
12312 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12313 // if/then triangle. See if there is a store to the same ptr as SI that
12314 // lives in OtherBB.
12315 for (;; --BBI) {
12316 // Check to see if we find the matching store.
12317 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner69fa3f52009-11-02 02:06:37 +000012318 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12319 OtherStore->getAlignment() != SI.getAlignment())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012320 return false;
12321 break;
12322 }
Eli Friedman3a311d52008-06-13 22:02:12 +000012323 // If we find something that may be using or overwriting the stored
12324 // value, or if we run out of instructions, we can't do the xform.
12325 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012326 BBI == OtherBB->begin())
12327 return false;
12328 }
12329
12330 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000012331 // make sure nothing reads or overwrites the stored value in
12332 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012333 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12334 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000012335 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012336 return false;
12337 }
12338 }
12339
12340 // Insert a PHI node now if we need it.
12341 Value *MergedVal = OtherStore->getOperand(0);
12342 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000012343 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012344 PN->reserveOperandSpace(2);
12345 PN->addIncoming(SI.getOperand(0), SI.getParent());
12346 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12347 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12348 }
12349
12350 // Advance to a place where it is safe to insert the new store and
12351 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000012352 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012353 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner69fa3f52009-11-02 02:06:37 +000012354 OtherStore->isVolatile(),
12355 SI.getAlignment()), *BBI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012356
12357 // Nuke the old stores.
12358 EraseInstFromFunction(SI);
12359 EraseInstFromFunction(*OtherStore);
12360 ++NumCombined;
12361 return true;
12362}
12363
12364
12365Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12366 // Change br (not X), label True, label False to: br X, label False, True
12367 Value *X = 0;
12368 BasicBlock *TrueDest;
12369 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +000012370 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012371 !isa<Constant>(X)) {
12372 // Swap Destinations and condition...
12373 BI.setCondition(X);
12374 BI.setSuccessor(0, FalseDest);
12375 BI.setSuccessor(1, TrueDest);
12376 return &BI;
12377 }
12378
12379 // Cannonicalize fcmp_one -> fcmp_oeq
12380 FCmpInst::Predicate FPred; Value *Y;
12381 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000012382 TrueDest, FalseDest)) &&
12383 BI.getCondition()->hasOneUse())
12384 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12385 FPred == FCmpInst::FCMP_OGE) {
12386 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12387 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12388
12389 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012390 BI.setSuccessor(0, FalseDest);
12391 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000012392 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012393 return &BI;
12394 }
12395
12396 // Cannonicalize icmp_ne -> icmp_eq
12397 ICmpInst::Predicate IPred;
12398 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +000012399 TrueDest, FalseDest)) &&
12400 BI.getCondition()->hasOneUse())
12401 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12402 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12403 IPred == ICmpInst::ICMP_SGE) {
12404 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12405 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12406 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012407 BI.setSuccessor(0, FalseDest);
12408 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +000012409 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012410 return &BI;
12411 }
12412
12413 return 0;
12414}
12415
12416Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12417 Value *Cond = SI.getCondition();
12418 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12419 if (I->getOpcode() == Instruction::Add)
12420 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12421 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12422 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012423 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +000012424 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012425 AddRHS));
12426 SI.setOperand(0, I->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +000012427 Worklist.Add(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012428 return &SI;
12429 }
12430 }
12431 return 0;
12432}
12433
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012434Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012435 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012436
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012437 if (!EV.hasIndices())
12438 return ReplaceInstUsesWith(EV, Agg);
12439
12440 if (Constant *C = dyn_cast<Constant>(Agg)) {
12441 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012442 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012443
12444 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +000012445 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012446
12447 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12448 // Extract the element indexed by the first index out of the constant
12449 Value *V = C->getOperand(*EV.idx_begin());
12450 if (EV.getNumIndices() > 1)
12451 // Extract the remaining indices out of the constant indexed by the
12452 // first index
12453 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12454 else
12455 return ReplaceInstUsesWith(EV, V);
12456 }
12457 return 0; // Can't handle other constants
12458 }
12459 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12460 // We're extracting from an insertvalue instruction, compare the indices
12461 const unsigned *exti, *exte, *insi, *inse;
12462 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12463 exte = EV.idx_end(), inse = IV->idx_end();
12464 exti != exte && insi != inse;
12465 ++exti, ++insi) {
12466 if (*insi != *exti)
12467 // The insert and extract both reference distinctly different elements.
12468 // This means the extract is not influenced by the insert, and we can
12469 // replace the aggregate operand of the extract with the aggregate
12470 // operand of the insert. i.e., replace
12471 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12472 // %E = extractvalue { i32, { i32 } } %I, 0
12473 // with
12474 // %E = extractvalue { i32, { i32 } } %A, 0
12475 return ExtractValueInst::Create(IV->getAggregateOperand(),
12476 EV.idx_begin(), EV.idx_end());
12477 }
12478 if (exti == exte && insi == inse)
12479 // Both iterators are at the end: Index lists are identical. Replace
12480 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12481 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12482 // with "i32 42"
12483 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12484 if (exti == exte) {
12485 // The extract list is a prefix of the insert list. i.e. replace
12486 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12487 // %E = extractvalue { i32, { i32 } } %I, 1
12488 // with
12489 // %X = extractvalue { i32, { i32 } } %A, 1
12490 // %E = insertvalue { i32 } %X, i32 42, 0
12491 // by switching the order of the insert and extract (though the
12492 // insertvalue should be left in, since it may have other uses).
Chris Lattnerad7516a2009-08-30 18:50:58 +000012493 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12494 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012495 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12496 insi, inse);
12497 }
12498 if (insi == inse)
12499 // The insert list is a prefix of the extract list
12500 // We can simply remove the common indices from the extract and make it
12501 // operate on the inserted value instead of the insertvalue result.
12502 // i.e., replace
12503 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12504 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12505 // with
12506 // %E extractvalue { i32 } { i32 42 }, 0
12507 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12508 exti, exte);
12509 }
Chris Lattner69a70752009-11-09 07:07:56 +000012510 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12511 // We're extracting from an intrinsic, see if we're the only user, which
12512 // allows us to simplify multiple result intrinsics to simpler things that
12513 // just get one value..
12514 if (II->hasOneUse()) {
12515 // Check if we're grabbing the overflow bit or the result of a 'with
12516 // overflow' intrinsic. If it's the latter we can remove the intrinsic
12517 // and replace it with a traditional binary instruction.
12518 switch (II->getIntrinsicID()) {
12519 case Intrinsic::uadd_with_overflow:
12520 case Intrinsic::sadd_with_overflow:
12521 if (*EV.idx_begin() == 0) { // Normal result.
12522 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12523 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12524 EraseInstFromFunction(*II);
12525 return BinaryOperator::CreateAdd(LHS, RHS);
12526 }
12527 break;
12528 case Intrinsic::usub_with_overflow:
12529 case Intrinsic::ssub_with_overflow:
12530 if (*EV.idx_begin() == 0) { // Normal result.
12531 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12532 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12533 EraseInstFromFunction(*II);
12534 return BinaryOperator::CreateSub(LHS, RHS);
12535 }
12536 break;
12537 case Intrinsic::umul_with_overflow:
12538 case Intrinsic::smul_with_overflow:
12539 if (*EV.idx_begin() == 0) { // Normal result.
12540 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12541 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12542 EraseInstFromFunction(*II);
12543 return BinaryOperator::CreateMul(LHS, RHS);
12544 }
12545 break;
12546 default:
12547 break;
12548 }
12549 }
12550 }
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012551 // Can't simplify extracts from other values. Note that nested extracts are
12552 // already simplified implicitely by the above (extract ( extract (insert) )
12553 // will be translated into extract ( insert ( extract ) ) first and then just
12554 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012555 return 0;
12556}
12557
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012558/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12559/// is to leave as a vector operation.
12560static bool CheapToScalarize(Value *V, bool isConstant) {
12561 if (isa<ConstantAggregateZero>(V))
12562 return true;
12563 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12564 if (isConstant) return true;
12565 // If all elts are the same, we can extract.
12566 Constant *Op0 = C->getOperand(0);
12567 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12568 if (C->getOperand(i) != Op0)
12569 return false;
12570 return true;
12571 }
12572 Instruction *I = dyn_cast<Instruction>(V);
12573 if (!I) return false;
12574
12575 // Insert element gets simplified to the inserted element or is deleted if
12576 // this is constant idx extract element and its a constant idx insertelt.
12577 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12578 isa<ConstantInt>(I->getOperand(2)))
12579 return true;
12580 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12581 return true;
12582 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12583 if (BO->hasOneUse() &&
12584 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12585 CheapToScalarize(BO->getOperand(1), isConstant)))
12586 return true;
12587 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12588 if (CI->hasOneUse() &&
12589 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12590 CheapToScalarize(CI->getOperand(1), isConstant)))
12591 return true;
12592
12593 return false;
12594}
12595
12596/// Read and decode a shufflevector mask.
12597///
12598/// It turns undef elements into values that are larger than the number of
12599/// elements in the input.
12600static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12601 unsigned NElts = SVI->getType()->getNumElements();
12602 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12603 return std::vector<unsigned>(NElts, 0);
12604 if (isa<UndefValue>(SVI->getOperand(2)))
12605 return std::vector<unsigned>(NElts, 2*NElts);
12606
12607 std::vector<unsigned> Result;
12608 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012609 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12610 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012611 Result.push_back(NElts*2); // undef -> 8
12612 else
Gabor Greif17396002008-06-12 21:37:33 +000012613 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012614 return Result;
12615}
12616
12617/// FindScalarElement - Given a vector and an element number, see if the scalar
12618/// value is already around as a register, for example if it were inserted then
12619/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012620static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012621 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012622 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12623 const VectorType *PTy = cast<VectorType>(V->getType());
12624 unsigned Width = PTy->getNumElements();
12625 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012626 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012627
12628 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012629 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012630 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +000012631 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012632 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12633 return CP->getOperand(EltNo);
12634 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12635 // If this is an insert to a variable element, we don't know what it is.
12636 if (!isa<ConstantInt>(III->getOperand(2)))
12637 return 0;
12638 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12639
12640 // If this is an insert to the element we are looking for, return the
12641 // inserted value.
12642 if (EltNo == IIElt)
12643 return III->getOperand(1);
12644
12645 // Otherwise, the insertelement doesn't modify the value, recurse on its
12646 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000012647 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012648 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012649 unsigned LHSWidth =
12650 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012651 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012652 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012653 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012654 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012655 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012656 else
Owen Andersonb99ecca2009-07-30 23:03:37 +000012657 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012658 }
12659
12660 // Otherwise, we don't know.
12661 return 0;
12662}
12663
12664Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012665 // If vector val is undef, replace extract with scalar undef.
12666 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012667 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012668
12669 // If vector val is constant 0, replace extract with scalar 0.
12670 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +000012671 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012672
12673 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012674 // If vector val is constant with all elements the same, replace EI with
12675 // that element. When the elements are not identical, we cannot replace yet
12676 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012677 Constant *op0 = C->getOperand(0);
Chris Lattner1ba36b72009-09-08 03:44:51 +000012678 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012679 if (C->getOperand(i) != op0) {
12680 op0 = 0;
12681 break;
12682 }
12683 if (op0)
12684 return ReplaceInstUsesWith(EI, op0);
12685 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000012686
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012687 // If extracting a specified index from the vector, see if we can recursively
12688 // find a previously computed scalar that was inserted into the vector.
12689 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12690 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner1ba36b72009-09-08 03:44:51 +000012691 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012692
12693 // If this is extracting an invalid index, turn this into undef, to avoid
12694 // crashing the code below.
12695 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +000012696 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012697
12698 // This instruction only demands the single element from the input vector.
12699 // If the input vector has a single use, simplify it based on this use
12700 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000012701 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012702 APInt UndefElts(VectorWidth, 0);
12703 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012704 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012705 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012706 EI.setOperand(0, V);
12707 return &EI;
12708 }
12709 }
12710
Owen Anderson24be4c12009-07-03 00:17:18 +000012711 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012712 return ReplaceInstUsesWith(EI, Elt);
12713
12714 // If the this extractelement is directly using a bitcast from a vector of
12715 // the same number of elements, see if we can find the source element from
12716 // it. In this case, we will end up needing to bitcast the scalars.
12717 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12718 if (const VectorType *VT =
12719 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12720 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012721 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12722 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012723 return new BitCastInst(Elt, EI.getType());
12724 }
12725 }
12726
12727 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattnera97bc602009-09-08 18:48:01 +000012728 // Push extractelement into predecessor operation if legal and
12729 // profitable to do so
12730 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12731 if (I->hasOneUse() &&
12732 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12733 Value *newEI0 =
12734 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12735 EI.getName()+".lhs");
12736 Value *newEI1 =
12737 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12738 EI.getName()+".rhs");
12739 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012740 }
Chris Lattnera97bc602009-09-08 18:48:01 +000012741 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012742 // Extracting the inserted element?
12743 if (IE->getOperand(2) == EI.getOperand(1))
12744 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12745 // If the inserted and extracted elements are constants, they must not
12746 // be the same value, extract from the pre-inserted value instead.
Chris Lattner78628292009-08-30 19:47:22 +000012747 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattnerc5ad98f2009-08-30 06:27:41 +000012748 Worklist.AddValue(EI.getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012749 EI.setOperand(0, IE->getOperand(0));
12750 return &EI;
12751 }
12752 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12753 // If this is extracting an element from a shufflevector, figure out where
12754 // it came from and extract from the appropriate input element instead.
12755 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12756 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12757 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012758 unsigned LHSWidth =
12759 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12760
12761 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012762 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012763 else if (SrcIdx < LHSWidth*2) {
12764 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012765 Src = SVI->getOperand(1);
12766 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012767 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012768 }
Eric Christopher1ba36872009-07-25 02:28:41 +000012769 return ExtractElementInst::Create(Src,
Chris Lattner78628292009-08-30 19:47:22 +000012770 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12771 false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012772 }
12773 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000012774 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012775 }
12776 return 0;
12777}
12778
12779/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12780/// elements from either LHS or RHS, return the shuffle mask and true.
12781/// Otherwise, return false.
12782static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000012783 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012784 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012785 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12786 "Invalid CollectSingleShuffleElements");
12787 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12788
12789 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012790 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012791 return true;
12792 } else if (V == LHS) {
12793 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012794 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012795 return true;
12796 } else if (V == RHS) {
12797 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012798 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012799 return true;
12800 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12801 // If this is an insert of an extract from some other vector, include it.
12802 Value *VecOp = IEI->getOperand(0);
12803 Value *ScalarOp = IEI->getOperand(1);
12804 Value *IdxOp = IEI->getOperand(2);
12805
12806 if (!isa<ConstantInt>(IdxOp))
12807 return false;
12808 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12809
12810 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12811 // Okay, we can handle this if the vector we are insertinting into is
12812 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012813 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012814 // If so, update the mask to reflect the inserted undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012815 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012816 return true;
12817 }
12818 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12819 if (isa<ConstantInt>(EI->getOperand(1)) &&
12820 EI->getOperand(0)->getType() == V->getType()) {
12821 unsigned ExtractedIdx =
12822 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12823
12824 // This must be extracting from either LHS or RHS.
12825 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12826 // Okay, we can handle this if the vector we are insertinting into is
12827 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012828 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012829 // If so, update the mask to reflect the inserted value.
12830 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012831 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012832 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012833 } else {
12834 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012835 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012836 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012837
12838 }
12839 return true;
12840 }
12841 }
12842 }
12843 }
12844 }
12845 // TODO: Handle shufflevector here!
12846
12847 return false;
12848}
12849
12850/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12851/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12852/// that computes V and the LHS value of the shuffle.
12853static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012854 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012855 assert(isa<VectorType>(V->getType()) &&
12856 (RHS == 0 || V->getType() == RHS->getType()) &&
12857 "Invalid shuffle!");
12858 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12859
12860 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012861 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012862 return V;
12863 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012864 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012865 return V;
12866 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12867 // If this is an insert of an extract from some other vector, include it.
12868 Value *VecOp = IEI->getOperand(0);
12869 Value *ScalarOp = IEI->getOperand(1);
12870 Value *IdxOp = IEI->getOperand(2);
12871
12872 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12873 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12874 EI->getOperand(0)->getType() == V->getType()) {
12875 unsigned ExtractedIdx =
12876 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12877 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12878
12879 // Either the extracted from or inserted into vector must be RHSVec,
12880 // otherwise we'd end up with a shuffle of three inputs.
12881 if (EI->getOperand(0) == RHS || RHS == 0) {
12882 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000012883 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012884 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012885 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012886 return V;
12887 }
12888
12889 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012890 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12891 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012892 // Everything but the extracted element is replaced with the RHS.
12893 for (unsigned i = 0; i != NumElts; ++i) {
12894 if (i != InsertedIdx)
Owen Anderson35b47072009-08-13 21:58:54 +000012895 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012896 }
12897 return V;
12898 }
12899
12900 // If this insertelement is a chain that comes from exactly these two
12901 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000012902 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12903 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012904 return EI->getOperand(0);
12905
12906 }
12907 }
12908 }
12909 // TODO: Handle shufflevector here!
12910
12911 // Otherwise, can't do anything fancy. Return an identity vector.
12912 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012913 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012914 return V;
12915}
12916
12917Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12918 Value *VecOp = IE.getOperand(0);
12919 Value *ScalarOp = IE.getOperand(1);
12920 Value *IdxOp = IE.getOperand(2);
12921
12922 // Inserting an undef or into an undefined place, remove this.
12923 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12924 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000012925
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012926 // If the inserted element was extracted from some other vector, and if the
12927 // indexes are constant, try to turn this into a shufflevector operation.
12928 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12929 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12930 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000012931 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012932 unsigned ExtractedIdx =
12933 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12934 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12935
12936 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12937 return ReplaceInstUsesWith(IE, VecOp);
12938
12939 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012940 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012941
12942 // If we are extracting a value from a vector, then inserting it right
12943 // back into the same place, just use the input vector.
12944 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12945 return ReplaceInstUsesWith(IE, VecOp);
12946
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012947 // If this insertelement isn't used by some other insertelement, turn it
12948 // (and any insertelements it points to), into one big shuffle.
12949 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12950 std::vector<Constant*> Mask;
12951 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000012952 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Andersonb99ecca2009-07-30 23:03:37 +000012953 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012954 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000012955 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +000012956 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012957 }
12958 }
12959 }
12960
Eli Friedmanbefee262009-06-06 20:08:03 +000012961 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12962 APInt UndefElts(VWidth, 0);
12963 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12964 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12965 return &IE;
12966
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012967 return 0;
12968}
12969
12970
12971Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12972 Value *LHS = SVI.getOperand(0);
12973 Value *RHS = SVI.getOperand(1);
12974 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12975
12976 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012977
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012978 // Undefined shuffle mask -> undefined value.
12979 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012980 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012981
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012982 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012983
12984 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12985 return 0;
12986
Evan Cheng63295ab2009-02-03 10:05:09 +000012987 APInt UndefElts(VWidth, 0);
12988 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12989 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012990 LHS = SVI.getOperand(0);
12991 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012992 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012993 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012994
12995 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12996 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12997 if (LHS == RHS || isa<UndefValue>(LHS)) {
12998 if (isa<UndefValue>(LHS) && LHS == RHS) {
12999 // shuffle(undef,undef,mask) -> undef.
13000 return ReplaceInstUsesWith(SVI, LHS);
13001 }
13002
13003 // Remap any references to RHS to use LHS.
13004 std::vector<Constant*> Elts;
13005 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13006 if (Mask[i] >= 2*e)
Owen Anderson35b47072009-08-13 21:58:54 +000013007 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013008 else {
13009 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000013010 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013011 Mask[i] = 2*e; // Turn into undef.
Owen Anderson35b47072009-08-13 21:58:54 +000013012 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanbba96b92008-08-06 18:17:32 +000013013 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000013014 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson35b47072009-08-13 21:58:54 +000013015 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000013016 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013017 }
13018 }
13019 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +000013020 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +000013021 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013022 LHS = SVI.getOperand(0);
13023 RHS = SVI.getOperand(1);
13024 MadeChange = true;
13025 }
13026
13027 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
13028 bool isLHSID = true, isRHSID = true;
13029
13030 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13031 if (Mask[i] >= e*2) continue; // Ignore undef values.
13032 // Is this an identity shuffle of the LHS value?
13033 isLHSID &= (Mask[i] == i);
13034
13035 // Is this an identity shuffle of the RHS value?
13036 isRHSID &= (Mask[i]-e == i);
13037 }
13038
13039 // Eliminate identity shuffles.
13040 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13041 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
13042
13043 // If the LHS is a shufflevector itself, see if we can combine it with this
13044 // one without producing an unusual shuffle. Here we are really conservative:
13045 // we are absolutely afraid of producing a shuffle mask not in the input
13046 // program, because the code gen may not be smart enough to turn a merged
13047 // shuffle into two specific shuffles: it may produce worse code. As such,
13048 // we only merge two shuffles if the result is one of the two input shuffle
13049 // masks. In this case, merging the shuffles just removes one instruction,
13050 // which we know is safe. This is good for things like turning:
13051 // (splat(splat)) -> splat.
13052 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13053 if (isa<UndefValue>(RHS)) {
13054 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13055
David Greeneb736b5d2009-11-16 21:52:23 +000013056 if (LHSMask.size() == Mask.size()) {
13057 std::vector<unsigned> NewMask;
13058 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sandse7f89b02009-11-20 13:19:51 +000013059 if (Mask[i] >= e)
David Greeneb736b5d2009-11-16 21:52:23 +000013060 NewMask.push_back(2*e);
13061 else
13062 NewMask.push_back(LHSMask[Mask[i]]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013063
David Greeneb736b5d2009-11-16 21:52:23 +000013064 // If the result mask is equal to the src shuffle or this
13065 // shuffle mask, do the replacement.
13066 if (NewMask == LHSMask || NewMask == Mask) {
13067 unsigned LHSInNElts =
13068 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13069 getNumElements();
13070 std::vector<Constant*> Elts;
13071 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13072 if (NewMask[i] >= LHSInNElts*2) {
13073 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13074 } else {
13075 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13076 NewMask[i]));
13077 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013078 }
David Greeneb736b5d2009-11-16 21:52:23 +000013079 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13080 LHSSVI->getOperand(1),
13081 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013082 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013083 }
13084 }
13085 }
13086
13087 return MadeChange ? &SVI : 0;
13088}
13089
13090
13091
13092
13093/// TryToSinkInstruction - Try to move the specified instruction from its
13094/// current block into the beginning of DestBlock, which can only happen if it's
13095/// safe to move the instruction past all of the instructions between it and the
13096/// end of its block.
13097static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13098 assert(I->hasOneUse() && "Invariants didn't hold!");
13099
13100 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000013101 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000013102 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013103
13104 // Do not sink alloca instructions out of the entry block.
13105 if (isa<AllocaInst>(I) && I->getParent() ==
13106 &DestBlock->getParent()->getEntryBlock())
13107 return false;
13108
13109 // We can only sink load instructions if there is nothing between the load and
13110 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000013111 if (I->mayReadFromMemory()) {
13112 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013113 Scan != E; ++Scan)
13114 if (Scan->mayWriteToMemory())
13115 return false;
13116 }
13117
Dan Gohman514277c2008-05-23 21:05:58 +000013118 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013119
Dale Johannesen24339f12009-03-03 01:09:07 +000013120 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013121 I->moveBefore(InsertPos);
13122 ++NumSunkInst;
13123 return true;
13124}
13125
13126
13127/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13128/// all reachable code to the worklist.
13129///
13130/// This has a couple of tricks to make the code faster and more powerful. In
13131/// particular, we constant fold and DCE instructions as we go, to avoid adding
13132/// them to the worklist (this significantly speeds up instcombine on code where
13133/// many instructions are dead or constant). Additionally, if we find a branch
13134/// whose condition is a known constant, we only visit the reachable successors.
13135///
Chris Lattnerc4269e52009-10-15 04:59:28 +000013136static bool AddReachableCodeToWorklist(BasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013137 SmallPtrSet<BasicBlock*, 64> &Visited,
13138 InstCombiner &IC,
13139 const TargetData *TD) {
Chris Lattnerc4269e52009-10-15 04:59:28 +000013140 bool MadeIRChange = false;
Chris Lattnera06291a2008-08-15 04:03:01 +000013141 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013142 Worklist.push_back(BB);
Chris Lattnerb5663c72009-10-12 03:58:40 +000013143
13144 std::vector<Instruction*> InstrsForInstCombineWorklist;
13145 InstrsForInstCombineWorklist.reserve(128);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013146
Chris Lattnerc4269e52009-10-15 04:59:28 +000013147 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13148
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013149 while (!Worklist.empty()) {
13150 BB = Worklist.back();
13151 Worklist.pop_back();
13152
13153 // We have now visited this block! If we've already been here, ignore it.
13154 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000013155
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013156 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13157 Instruction *Inst = BBI++;
13158
13159 // DCE instruction if trivially dead.
13160 if (isInstructionTriviallyDead(Inst)) {
13161 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +000013162 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013163 Inst->eraseFromParent();
13164 continue;
13165 }
13166
13167 // ConstantProp instruction if trivially constant.
Chris Lattneree5839b2009-10-15 04:13:44 +000013168 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +000013169 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +000013170 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13171 << *Inst << '\n');
13172 Inst->replaceAllUsesWith(C);
13173 ++NumConstProp;
13174 Inst->eraseFromParent();
13175 continue;
13176 }
Chris Lattnerc4269e52009-10-15 04:59:28 +000013177
13178
13179
13180 if (TD) {
13181 // See if we can constant fold its operands.
13182 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13183 i != e; ++i) {
13184 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13185 if (CE == 0) continue;
13186
13187 // If we already folded this constant, don't try again.
13188 if (!FoldedConstants.insert(CE))
13189 continue;
13190
Chris Lattner6070c012009-11-06 04:27:31 +000013191 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattnerc4269e52009-10-15 04:59:28 +000013192 if (NewC && NewC != CE) {
13193 *i = NewC;
13194 MadeIRChange = true;
13195 }
13196 }
13197 }
13198
Devang Patel794140c2008-11-19 18:56:50 +000013199
Chris Lattnerb5663c72009-10-12 03:58:40 +000013200 InstrsForInstCombineWorklist.push_back(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013201 }
13202
13203 // Recursively visit successors. If this is a branch or switch on a
13204 // constant, only visit the reachable successor.
13205 TerminatorInst *TI = BB->getTerminator();
13206 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13207 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13208 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000013209 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000013210 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013211 continue;
13212 }
13213 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13214 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13215 // See if this is an explicit destination.
13216 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13217 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000013218 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000013219 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013220 continue;
13221 }
13222
13223 // Otherwise it is the default destination.
13224 Worklist.push_back(SI->getSuccessor(0));
13225 continue;
13226 }
13227 }
13228
13229 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13230 Worklist.push_back(TI->getSuccessor(i));
13231 }
Chris Lattnerb5663c72009-10-12 03:58:40 +000013232
13233 // Once we've found all of the instructions to add to instcombine's worklist,
13234 // add them in reverse order. This way instcombine will visit from the top
13235 // of the function down. This jives well with the way that it adds all uses
13236 // of instructions to the worklist after doing a transformation, thus avoiding
13237 // some N^2 behavior in pathological cases.
13238 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13239 InstrsForInstCombineWorklist.size());
Chris Lattnerc4269e52009-10-15 04:59:28 +000013240
13241 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013242}
13243
13244bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner21d79e22009-08-31 06:57:37 +000013245 MadeIRChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013246
Daniel Dunbar005975c2009-07-25 00:23:56 +000013247 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13248 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013249
13250 {
13251 // Do a depth-first traversal of the function, populate the worklist with
13252 // the reachable instructions. Ignore blocks that are not reachable. Keep
13253 // track of which blocks we visit.
13254 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerc4269e52009-10-15 04:59:28 +000013255 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013256
13257 // Do a quick scan over the function. If we find any blocks that are
13258 // unreachable, remove any instructions inside of them. This prevents
13259 // the instcombine code from having to deal with some bad special cases.
13260 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13261 if (!Visited.count(BB)) {
13262 Instruction *Term = BB->getTerminator();
13263 while (Term != BB->begin()) { // Remove instrs bottom-up
13264 BasicBlock::iterator I = Term; --I;
13265
Chris Lattner8a6411c2009-08-23 04:37:46 +000013266 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +000013267 // A debug intrinsic shouldn't force another iteration if we weren't
13268 // going to do one without it.
13269 if (!isa<DbgInfoIntrinsic>(I)) {
13270 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000013271 MadeIRChange = true;
Dale Johannesendf356c62009-03-10 21:19:49 +000013272 }
Devang Patele3829c82009-10-13 22:56:32 +000013273
Devang Patele3829c82009-10-13 22:56:32 +000013274 // If I is not void type then replaceAllUsesWith undef.
13275 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +000013276 if (!I->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +000013277 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013278 I->eraseFromParent();
13279 }
13280 }
13281 }
13282
Chris Lattner5119c702009-08-30 05:55:36 +000013283 while (!Worklist.isEmpty()) {
13284 Instruction *I = Worklist.RemoveOne();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013285 if (I == 0) continue; // skip null values.
13286
13287 // Check to see if we can DCE the instruction.
13288 if (isInstructionTriviallyDead(I)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000013289 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner3183fb62009-08-30 06:13:40 +000013290 EraseInstFromFunction(*I);
13291 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +000013292 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013293 continue;
13294 }
13295
13296 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattneree5839b2009-10-15 04:13:44 +000013297 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +000013298 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +000013299 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013300
Chris Lattneree5839b2009-10-15 04:13:44 +000013301 // Add operands to the worklist.
13302 ReplaceInstUsesWith(*I, C);
13303 ++NumConstProp;
13304 EraseInstFromFunction(*I);
13305 MadeIRChange = true;
13306 continue;
13307 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013308
13309 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000013310 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013311 BasicBlock *BB = I->getParent();
Chris Lattnerf27a0432009-10-14 15:21:58 +000013312 Instruction *UserInst = cast<Instruction>(I->use_back());
13313 BasicBlock *UserParent;
13314
13315 // Get the block the use occurs in.
13316 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13317 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13318 else
13319 UserParent = UserInst->getParent();
13320
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013321 if (UserParent != BB) {
13322 bool UserIsSuccessor = false;
13323 // See if the user is one of our successors.
13324 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13325 if (*SI == UserParent) {
13326 UserIsSuccessor = true;
13327 break;
13328 }
13329
13330 // If the user is one of our immediate successors, and if that successor
13331 // only has us as a predecessors (we'd have to split the critical edge
13332 // otherwise), we can keep going.
Chris Lattnerf27a0432009-10-14 15:21:58 +000013333 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013334 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattner21d79e22009-08-31 06:57:37 +000013335 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013336 }
13337 }
13338
Chris Lattnerc7694852009-08-30 07:44:24 +000013339 // Now that we have an instruction, try combining it to simplify it.
13340 Builder->SetInsertPoint(I->getParent(), I);
13341
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013342#ifndef NDEBUG
13343 std::string OrigI;
13344#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +000013345 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin17091f02009-10-08 00:12:24 +000013346 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13347
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013348 if (Instruction *Result = visit(*I)) {
13349 ++NumCombined;
13350 // Should we replace the old instruction with a new one?
13351 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000013352 DEBUG(errs() << "IC: Old = " << *I << '\n'
13353 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013354
13355 // Everything uses the new instruction now.
13356 I->replaceAllUsesWith(Result);
13357
13358 // Push the new instruction and any users onto the worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +000013359 Worklist.Add(Result);
Chris Lattner4796b622009-08-30 06:22:51 +000013360 Worklist.AddUsersToWorkList(*Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013361
13362 // Move the name to the new instruction first.
13363 Result->takeName(I);
13364
13365 // Insert the new instruction into the basic block...
13366 BasicBlock *InstParent = I->getParent();
13367 BasicBlock::iterator InsertPos = I;
13368
13369 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13370 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13371 ++InsertPos;
13372
13373 InstParent->getInstList().insert(InsertPos, Result);
13374
Chris Lattner3183fb62009-08-30 06:13:40 +000013375 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013376 } else {
13377#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +000013378 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13379 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013380#endif
13381
13382 // If the instruction was modified, it's possible that it is now dead.
13383 // if so, remove it.
13384 if (isInstructionTriviallyDead(I)) {
Chris Lattner3183fb62009-08-30 06:13:40 +000013385 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013386 } else {
Chris Lattner3183fb62009-08-30 06:13:40 +000013387 Worklist.Add(I);
Chris Lattner4796b622009-08-30 06:22:51 +000013388 Worklist.AddUsersToWorkList(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013389 }
13390 }
Chris Lattner21d79e22009-08-31 06:57:37 +000013391 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013392 }
13393 }
13394
Chris Lattner5119c702009-08-30 05:55:36 +000013395 Worklist.Zap();
Chris Lattner21d79e22009-08-31 06:57:37 +000013396 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013397}
13398
13399
13400bool InstCombiner::runOnFunction(Function &F) {
13401 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000013402 Context = &F.getContext();
Chris Lattneree5839b2009-10-15 04:13:44 +000013403 TD = getAnalysisIfAvailable<TargetData>();
13404
Chris Lattnerc7694852009-08-30 07:44:24 +000013405
13406 /// Builder - This is an IRBuilder that automatically inserts new
13407 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +000013408 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattner002e65d2009-11-06 05:59:53 +000013409 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattnerc7694852009-08-30 07:44:24 +000013410 InstCombineIRInserter(Worklist));
13411 Builder = &TheBuilder;
13412
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013413 bool EverMadeChange = false;
13414
13415 // Iterate while there is work to do.
13416 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000013417 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013418 EverMadeChange = true;
Chris Lattnerc7694852009-08-30 07:44:24 +000013419
13420 Builder = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013421 return EverMadeChange;
13422}
13423
13424FunctionPass *llvm::createInstructionCombiningPass() {
13425 return new InstCombiner();
13426}