blob: 2bfa8d54a3bdafcb3cffdb86f63cf6edec94efa1 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 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.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 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.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000045#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner173234a2008-06-02 01:18:21 +000046#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000047#include "llvm/Target/TargetData.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000051#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000052#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000053#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000054#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000055#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000056#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000057#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000058#include "llvm/Support/PatternMatch.h"
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000059#include "llvm/Support/TargetFolder.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000060#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000061#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000062#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000063#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000064#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000065#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000066#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000067#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000068using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000069using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000070
Chris Lattner0e5f4992006-12-19 21:40:18 +000071STATISTIC(NumCombined , "Number of insts combined");
72STATISTIC(NumConstProp, "Number of constant folds");
73STATISTIC(NumDeadInst , "Number of dead inst eliminated");
74STATISTIC(NumDeadStore, "Number of dead stores eliminated");
75STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000076
Chris Lattner0e5f4992006-12-19 21:40:18 +000077namespace {
Chris Lattner873ff012009-08-30 05:55:36 +000078 /// InstCombineWorklist - This is the worklist management logic for
79 /// InstCombine.
80 class InstCombineWorklist {
81 SmallVector<Instruction*, 256> Worklist;
82 DenseMap<Instruction*, unsigned> WorklistMap;
83
84 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
85 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
86 public:
87 InstCombineWorklist() {}
88
89 bool isEmpty() const { return Worklist.empty(); }
90
91 /// Add - Add the specified instruction to the worklist if it isn't already
92 /// in it.
93 void Add(Instruction *I) {
Jeffrey Yasskin43069632009-10-08 00:12:24 +000094 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
95 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner873ff012009-08-30 05:55:36 +000096 Worklist.push_back(I);
Jeffrey Yasskin43069632009-10-08 00:12:24 +000097 }
Chris Lattner873ff012009-08-30 05:55:36 +000098 }
99
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000100 void AddValue(Value *V) {
101 if (Instruction *I = dyn_cast<Instruction>(V))
102 Add(I);
103 }
104
Chris Lattner67f7d542009-10-12 03:58:40 +0000105 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
106 /// which should only be done when the worklist is empty and when the group
107 /// has no duplicates.
108 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
109 assert(Worklist.empty() && "Worklist must be empty to add initial group");
110 Worklist.reserve(NumEntries+16);
111 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
112 for (; NumEntries; --NumEntries) {
113 Instruction *I = List[NumEntries-1];
114 WorklistMap.insert(std::make_pair(I, Worklist.size()));
115 Worklist.push_back(I);
116 }
117 }
118
Chris Lattner7a1e9242009-08-30 06:13:40 +0000119 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000120 void Remove(Instruction *I) {
121 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
122 if (It == WorklistMap.end()) return; // Not in worklist.
123
124 // Don't bother moving everything down, just null out the slot.
125 Worklist[It->second] = 0;
126
127 WorklistMap.erase(It);
128 }
129
130 Instruction *RemoveOne() {
131 Instruction *I = Worklist.back();
132 Worklist.pop_back();
133 WorklistMap.erase(I);
134 return I;
135 }
136
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000137 /// AddUsersToWorkList - When an instruction is simplified, add all users of
138 /// the instruction to the work lists because they might get more simplified
139 /// now.
140 ///
141 void AddUsersToWorkList(Instruction &I) {
142 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
143 UI != UE; ++UI)
144 Add(cast<Instruction>(*UI));
145 }
146
Chris Lattner873ff012009-08-30 05:55:36 +0000147
148 /// Zap - check that the worklist is empty and nuke the backing store for
149 /// the map if it is large.
150 void Zap() {
151 assert(WorklistMap.empty() && "Worklist empty, but map not?");
152
153 // Do an explicit clear, this shrinks the map if needed.
154 WorklistMap.clear();
155 }
156 };
157} // end anonymous namespace.
158
159
160namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000161 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
162 /// just like the normal insertion helper, but also adds any new instructions
163 /// to the instcombine worklist.
164 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
165 InstCombineWorklist &Worklist;
166 public:
167 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
168
169 void InsertHelper(Instruction *I, const Twine &Name,
170 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
171 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
172 Worklist.Add(I);
173 }
174 };
175} // end anonymous namespace
176
177
178namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000179 class InstCombiner : public FunctionPass,
180 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000181 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000182 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000183 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000184 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000185 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000186 InstCombineWorklist Worklist;
187
Chris Lattner74381062009-08-30 07:44:24 +0000188 /// Builder - This is an IRBuilder that automatically inserts new
189 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +0000190 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000191 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000192
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000193 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000194 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000195
Owen Andersone922c022009-07-22 00:24:57 +0000196 LLVMContext *Context;
197 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000198
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000199 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000200 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000201
202 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000203
Chris Lattner97e52e42002-04-28 21:27:06 +0000204 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000205 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000206 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000207 }
208
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000209 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000210
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000211 // Visitation implementation - Implement instruction combining for different
212 // instruction types. The semantics are as follows:
213 // Return Value:
214 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000215 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000216 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000217 //
Chris Lattner7e708292002-06-25 16:13:24 +0000218 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000219 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner092543c2009-11-04 08:05:20 +0000220 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
Chris Lattner7e708292002-06-25 16:13:24 +0000221 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000222 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000223 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000224 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000225 Instruction *visitURem(BinaryOperator &I);
226 Instruction *visitSRem(BinaryOperator &I);
227 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000228 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000229 Instruction *commonRemTransforms(BinaryOperator &I);
230 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000231 Instruction *commonDivTransforms(BinaryOperator &I);
232 Instruction *commonIDivTransforms(BinaryOperator &I);
233 Instruction *visitUDiv(BinaryOperator &I);
234 Instruction *visitSDiv(BinaryOperator &I);
235 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000236 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000237 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000238 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000239 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000240 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000241 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000242 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000243 Instruction *visitOr (BinaryOperator &I);
244 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000245 Instruction *visitShl(BinaryOperator &I);
246 Instruction *visitAShr(BinaryOperator &I);
247 Instruction *visitLShr(BinaryOperator &I);
248 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000249 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
250 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000251 Instruction *visitFCmpInst(FCmpInst &I);
252 Instruction *visitICmpInst(ICmpInst &I);
253 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000254 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
255 Instruction *LHS,
256 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000257 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
258 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000259
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000260 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000261 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000262 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000263 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000264 Instruction *commonCastTransforms(CastInst &CI);
265 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000266 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000267 Instruction *visitTrunc(TruncInst &CI);
268 Instruction *visitZExt(ZExtInst &CI);
269 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000270 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000271 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000272 Instruction *visitFPToUI(FPToUIInst &FI);
273 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000274 Instruction *visitUIToFP(CastInst &CI);
275 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000276 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000277 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000278 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000279 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
280 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000281 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000282 Instruction *visitSelectInst(SelectInst &SI);
283 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000284 Instruction *visitCallInst(CallInst &CI);
285 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000286 Instruction *visitPHINode(PHINode &PN);
287 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000288 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000289 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000290 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000291 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000292 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000293 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000294 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000295 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000296 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000297 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000298
299 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000300 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000301
Chris Lattner9fe38862003-06-19 17:00:31 +0000302 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000303 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000304 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000305 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000306 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
307 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000308 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000309 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
310
Chris Lattner9fe38862003-06-19 17:00:31 +0000311
Chris Lattner28977af2004-04-05 01:30:19 +0000312 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000313 // InsertNewInstBefore - insert an instruction New before instruction Old
314 // in the program. Add the new instruction to the worklist.
315 //
Chris Lattner955f3312004-09-28 21:48:02 +0000316 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000317 assert(New && New->getParent() == 0 &&
318 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000319 BasicBlock *BB = Old.getParent();
320 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000321 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000322 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000323 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000324
Chris Lattner8b170942002-08-09 23:47:40 +0000325 // ReplaceInstUsesWith - This method is to be used when an instruction is
326 // found to be dead, replacable with another preexisting expression. Here
327 // we add all uses of I to the worklist, replace all uses of I with the new
328 // value, then return I, so that the inst combiner will know that I was
329 // modified.
330 //
331 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000332 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000333
334 // If we are replacing the instruction with itself, this must be in a
335 // segment of unreachable code, so just clobber the instruction.
336 if (&I == V)
337 V = UndefValue::get(I.getType());
338
339 I.replaceAllUsesWith(V);
340 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000341 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000342
343 // EraseInstFromFunction - When dealing with an instruction that has side
344 // effects or produces a void value, we can't rely on DCE to delete the
345 // instruction. Instead, visit methods should return the value returned by
346 // this function.
347 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000348 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000349
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000350 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000351 // Make sure that we reprocess all operands now that we reduced their
352 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000353 if (I.getNumOperands() < 8) {
354 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
355 if (Instruction *Op = dyn_cast<Instruction>(*i))
356 Worklist.Add(Op);
357 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000358 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000359 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000360 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000361 return 0; // Don't do anything with FI
362 }
Chris Lattner173234a2008-06-02 01:18:21 +0000363
364 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
365 APInt &KnownOne, unsigned Depth = 0) const {
366 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
367 }
368
369 bool MaskedValueIsZero(Value *V, const APInt &Mask,
370 unsigned Depth = 0) const {
371 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
372 }
373 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
374 return llvm::ComputeNumSignBits(Op, TD, Depth);
375 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000376
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000377 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000378
Reid Spencere4d87aa2006-12-23 06:05:41 +0000379 /// SimplifyCommutative - This performs a few simplifications for
380 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000381 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000382
Reid Spencere4d87aa2006-12-23 06:05:41 +0000383 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
384 /// most-complex to least-complex order.
385 bool SimplifyCompare(CmpInst &I);
386
Chris Lattner886ab6c2009-01-31 08:15:18 +0000387 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
388 /// based on the demanded bits.
389 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
390 APInt& KnownZero, APInt& KnownOne,
391 unsigned Depth);
392 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000393 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000394 unsigned Depth=0);
395
396 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
397 /// SimplifyDemandedBits knows about. See if the instruction has any
398 /// properties that allow us to simplify its operands.
399 bool SimplifyDemandedInstructionBits(Instruction &Inst);
400
Evan Cheng388df622009-02-03 10:05:09 +0000401 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
402 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000403
Chris Lattner5d1704d2009-09-27 19:57:57 +0000404 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
405 // which has a PHI node as operand #0, see if we can fold the instruction
406 // into the PHI (which is only possible if all operands to the PHI are
407 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000408 //
409 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
410 // that would normally be unprofitable because they strongly encourage jump
411 // threading.
412 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000413
Chris Lattnerbac32862004-11-14 19:13:23 +0000414 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
415 // operator and they all are only used by the PHI, PHI together their
416 // inputs, and do the operation once, to the result of the PHI.
417 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000418 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000419 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner751a3622009-11-01 20:04:24 +0000420 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000421
Chris Lattner7da52b22006-11-01 04:51:18 +0000422
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000423 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
424 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000425
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000426 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000427 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000428 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000429 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000430 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000431 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000432 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000433 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000434 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000435
Chris Lattnerafe91a52006-06-15 19:07:26 +0000436
Reid Spencerc55b2432006-12-13 18:21:21 +0000437 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000438
Dan Gohman6de29f82009-06-15 22:12:54 +0000439 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000440 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000441 unsigned GetOrEnforceKnownAlignment(Value *V,
442 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000443
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000444 };
Chris Lattner873ff012009-08-30 05:55:36 +0000445} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000446
Dan Gohman844731a2008-05-13 00:00:25 +0000447char InstCombiner::ID = 0;
448static RegisterPass<InstCombiner>
449X("instcombine", "Combine redundant instructions");
450
Chris Lattner4f98c562003-03-10 21:43:22 +0000451// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000452// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000453static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000454 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000455 if (BinaryOperator::isNeg(V) ||
456 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000457 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000458 return 3;
459 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000460 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000461 if (isa<Argument>(V)) return 3;
462 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000463}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000464
Chris Lattnerc8802d22003-03-11 00:12:48 +0000465// isOnlyUse - Return true if this instruction will be deleted if we stop using
466// it.
467static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000468 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000469}
470
Chris Lattner4cb170c2004-02-23 06:38:22 +0000471// getPromotedType - Return the specified type promoted as it would be to pass
472// though a va_arg area...
473static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000474 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
475 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000476 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000477 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000478 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000479}
480
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000481/// getBitCastOperand - If the specified operand is a CastInst, a constant
482/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
483/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000484static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000485 if (Operator *O = dyn_cast<Operator>(V)) {
486 if (O->getOpcode() == Instruction::BitCast)
487 return O->getOperand(0);
488 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
489 if (GEP->hasAllZeroIndices())
490 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000491 }
Chris Lattnereed48272005-09-13 00:40:14 +0000492 return 0;
493}
494
Reid Spencer3da59db2006-11-27 01:05:10 +0000495/// This function is a wrapper around CastInst::isEliminableCastPair. It
496/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000497static Instruction::CastOps
498isEliminableCastPair(
499 const CastInst *CI, ///< The first cast instruction
500 unsigned opcode, ///< The opcode of the second cast instruction
501 const Type *DstTy, ///< The target type for the second cast instruction
502 TargetData *TD ///< The target data for pointer size
503) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000504
Reid Spencer3da59db2006-11-27 01:05:10 +0000505 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
506 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000507
Reid Spencer3da59db2006-11-27 01:05:10 +0000508 // Get the opcodes of the two Cast instructions
509 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
510 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000511
Chris Lattnera0e69692009-03-24 18:35:40 +0000512 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000513 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000514 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000515
516 // We don't want to form an inttoptr or ptrtoint that converts to an integer
517 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000518 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000519 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000520 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000521 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000522 Res = 0;
523
524 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000525}
526
527/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
528/// in any code being generated. It does not require codegen if V is simple
529/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000530static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
531 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000532 if (V->getType() == Ty || isa<Constant>(V)) return false;
533
Chris Lattner01575b72006-05-25 23:24:33 +0000534 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000535 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000536 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000537 return false;
538 return true;
539}
540
Chris Lattner4f98c562003-03-10 21:43:22 +0000541// SimplifyCommutative - This performs a few simplifications for commutative
542// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000543//
Chris Lattner4f98c562003-03-10 21:43:22 +0000544// 1. Order operands such that they are listed from right (least complex) to
545// left (most complex). This puts constants before unary operators before
546// binary operators.
547//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000548// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
549// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000550//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000551bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000552 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000553 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000554 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000555
Chris Lattner4f98c562003-03-10 21:43:22 +0000556 if (!I.isAssociative()) return Changed;
557 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000558 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
559 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
560 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000561 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000562 cast<Constant>(I.getOperand(1)),
563 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000564 I.setOperand(0, Op->getOperand(0));
565 I.setOperand(1, Folded);
566 return true;
567 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
568 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
569 isOnlyUse(Op) && isOnlyUse(Op1)) {
570 Constant *C1 = cast<Constant>(Op->getOperand(1));
571 Constant *C2 = cast<Constant>(Op1->getOperand(1));
572
573 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000574 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000575 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000576 Op1->getOperand(0),
577 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000578 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000579 I.setOperand(0, New);
580 I.setOperand(1, Folded);
581 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000582 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000583 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000584 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000585}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000586
Reid Spencere4d87aa2006-12-23 06:05:41 +0000587/// SimplifyCompare - For a CmpInst this function just orders the operands
588/// so that theyare listed from right (least complex) to left (most complex).
589/// This puts constants before unary operators before binary operators.
590bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000591 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000592 return false;
593 I.swapOperands();
594 // Compare instructions are not associative so there's nothing else we can do.
595 return true;
596}
597
Chris Lattner8d969642003-03-10 23:06:50 +0000598// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
599// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000600//
Dan Gohman186a6362009-08-12 16:04:34 +0000601static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000602 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000603 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000604
Chris Lattner0ce85802004-12-14 20:08:06 +0000605 // Constants can be considered to be negated values if they can be folded.
606 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000607 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000608
609 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
610 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000611 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000612
Chris Lattner8d969642003-03-10 23:06:50 +0000613 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000614}
615
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000616// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
617// instruction if the LHS is a constant negative zero (which is the 'negate'
618// form).
619//
Dan Gohman186a6362009-08-12 16:04:34 +0000620static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000621 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000622 return BinaryOperator::getFNegArgument(V);
623
624 // Constants can be considered to be negated values if they can be folded.
625 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000626 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000627
628 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
629 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000630 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000631
632 return 0;
633}
634
Chris Lattner48b59ec2009-10-26 15:40:07 +0000635/// isFreeToInvert - Return true if the specified value is free to invert (apply
636/// ~ to). This happens in cases where the ~ can be eliminated.
637static inline bool isFreeToInvert(Value *V) {
638 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000639 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000640 return true;
641
642 // Constants can be considered to be not'ed values.
643 if (isa<ConstantInt>(V))
644 return true;
645
646 // Compares can be inverted if they have a single use.
647 if (CmpInst *CI = dyn_cast<CmpInst>(V))
648 return CI->hasOneUse();
649
650 return false;
651}
652
653static inline Value *dyn_castNotVal(Value *V) {
654 // If this is not(not(x)) don't return that this is a not: we want the two
655 // not's to be folded first.
656 if (BinaryOperator::isNot(V)) {
657 Value *Operand = BinaryOperator::getNotArgument(V);
658 if (!isFreeToInvert(Operand))
659 return Operand;
660 }
Chris Lattner8d969642003-03-10 23:06:50 +0000661
662 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000663 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000664 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000665 return 0;
666}
667
Chris Lattner48b59ec2009-10-26 15:40:07 +0000668
669
Chris Lattnerc8802d22003-03-11 00:12:48 +0000670// dyn_castFoldableMul - If this value is a multiply that can be folded into
671// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000672// non-constant operand of the multiply, and set CST to point to the multiplier.
673// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000674//
Dan Gohman186a6362009-08-12 16:04:34 +0000675static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000676 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000677 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000678 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000679 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000680 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000681 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000682 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000683 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000684 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000685 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000686 CST = ConstantInt::get(V->getType()->getContext(),
687 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000688 return I->getOperand(0);
689 }
690 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000691 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000692}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000693
Reid Spencer7177c3a2007-03-25 05:33:51 +0000694/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000695static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000696 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000697 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000698}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000699/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000700static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000701 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000702 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000703}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000704/// MultiplyOverflows - True if the multiply can not be expressed in an int
705/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000706static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000707 uint32_t W = C1->getBitWidth();
708 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
709 if (sign) {
710 LHSExt.sext(W * 2);
711 RHSExt.sext(W * 2);
712 } else {
713 LHSExt.zext(W * 2);
714 RHSExt.zext(W * 2);
715 }
716
717 APInt MulExt = LHSExt * RHSExt;
718
719 if (sign) {
720 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
721 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
722 return MulExt.slt(Min) || MulExt.sgt(Max);
723 } else
724 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
725}
Chris Lattner955f3312004-09-28 21:48:02 +0000726
Reid Spencere7816b52007-03-08 01:52:58 +0000727
Chris Lattner255d8912006-02-11 09:31:47 +0000728/// ShrinkDemandedConstant - Check to see if the specified operand of the
729/// specified instruction is a constant integer. If so, check to see if there
730/// are any bits set in the constant that are not demanded. If so, shrink the
731/// constant and return true.
732static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000733 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000734 assert(I && "No instruction?");
735 assert(OpNo < I->getNumOperands() && "Operand index too large");
736
737 // If the operand is not a constant integer, nothing to do.
738 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
739 if (!OpC) return false;
740
741 // If there are no bits set that aren't demanded, nothing to do.
742 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
743 if ((~Demanded & OpC->getValue()) == 0)
744 return false;
745
746 // This instruction is producing bits that are not demanded. Shrink the RHS.
747 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000748 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000749 return true;
750}
751
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000752// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
753// set of known zero and one bits, compute the maximum and minimum values that
754// could have the specified known zero and known one bits, returning them in
755// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000756static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000757 const APInt& KnownOne,
758 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000759 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
760 KnownZero.getBitWidth() == Min.getBitWidth() &&
761 KnownZero.getBitWidth() == Max.getBitWidth() &&
762 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000763 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000764
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000765 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
766 // bit if it is unknown.
767 Min = KnownOne;
768 Max = KnownOne|UnknownBits;
769
Dan Gohman1c8491e2009-04-25 17:12:48 +0000770 if (UnknownBits.isNegative()) { // Sign bit is unknown
771 Min.set(Min.getBitWidth()-1);
772 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000773 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000774}
775
776// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
777// a set of known zero and one bits, compute the maximum and minimum values that
778// could have the specified known zero and known one bits, returning them in
779// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000780static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000781 const APInt &KnownOne,
782 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000783 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
784 KnownZero.getBitWidth() == Min.getBitWidth() &&
785 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000786 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000787 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000788
789 // The minimum value is when the unknown bits are all zeros.
790 Min = KnownOne;
791 // The maximum value is when the unknown bits are all ones.
792 Max = KnownOne|UnknownBits;
793}
Chris Lattner255d8912006-02-11 09:31:47 +0000794
Chris Lattner886ab6c2009-01-31 08:15:18 +0000795/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
796/// SimplifyDemandedBits knows about. See if the instruction has any
797/// properties that allow us to simplify its operands.
798bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000799 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000800 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
801 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
802
803 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
804 KnownZero, KnownOne, 0);
805 if (V == 0) return false;
806 if (V == &Inst) return true;
807 ReplaceInstUsesWith(Inst, V);
808 return true;
809}
810
811/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
812/// specified instruction operand if possible, updating it in place. It returns
813/// true if it made any change and false otherwise.
814bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
815 APInt &KnownZero, APInt &KnownOne,
816 unsigned Depth) {
817 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
818 KnownZero, KnownOne, Depth);
819 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000820 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000821 return true;
822}
823
824
825/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
826/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000827/// that only the bits set in DemandedMask of the result of V are ever used
828/// downstream. Consequently, depending on the mask and V, it may be possible
829/// to replace V with a constant or one of its operands. In such cases, this
830/// function does the replacement and returns true. In all other cases, it
831/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000832/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000833/// to be zero in the expression. These are provided to potentially allow the
834/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
835/// the expression. KnownOne and KnownZero always follow the invariant that
836/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
837/// the bits in KnownOne and KnownZero may only be accurate for those bits set
838/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
839/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000840///
841/// This returns null if it did not change anything and it permits no
842/// simplification. This returns V itself if it did some simplification of V's
843/// operands based on the information about what bits are demanded. This returns
844/// some other non-null value if it found out that V is equal to another value
845/// in the context where the specified bits are demanded, but not for all users.
846Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
847 APInt &KnownZero, APInt &KnownOne,
848 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000849 assert(V != 0 && "Null pointer of Value???");
850 assert(Depth <= 6 && "Limit Search Depth");
851 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000852 const Type *VTy = V->getType();
853 assert((TD || !isa<PointerType>(VTy)) &&
854 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000855 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
856 (!VTy->isIntOrIntVector() ||
857 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000858 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000859 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000860 "Value *V, DemandedMask, KnownZero and KnownOne "
861 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000862 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
863 // We know all of the bits for a constant!
864 KnownOne = CI->getValue() & DemandedMask;
865 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000866 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000867 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000868 if (isa<ConstantPointerNull>(V)) {
869 // We know all of the bits for a constant!
870 KnownOne.clear();
871 KnownZero = DemandedMask;
872 return 0;
873 }
874
Chris Lattner08d2cc72009-01-31 07:26:06 +0000875 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000876 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000877 if (DemandedMask == 0) { // Not demanding any bits from V.
878 if (isa<UndefValue>(V))
879 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000880 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000881 }
882
Chris Lattner4598c942009-01-31 08:24:16 +0000883 if (Depth == 6) // Limit search depth.
884 return 0;
885
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000886 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
887 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
888
Dan Gohman1c8491e2009-04-25 17:12:48 +0000889 Instruction *I = dyn_cast<Instruction>(V);
890 if (!I) {
891 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
892 return 0; // Only analyze instructions.
893 }
894
Chris Lattner4598c942009-01-31 08:24:16 +0000895 // If there are multiple uses of this value and we aren't at the root, then
896 // we can't do any simplifications of the operands, because DemandedMask
897 // only reflects the bits demanded by *one* of the users.
898 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000899 // Despite the fact that we can't simplify this instruction in all User's
900 // context, we can at least compute the knownzero/knownone bits, and we can
901 // do simplifications that apply to *just* the one user if we know that
902 // this instruction has a simpler value in that context.
903 if (I->getOpcode() == Instruction::And) {
904 // If either the LHS or the RHS are Zero, the result is zero.
905 ComputeMaskedBits(I->getOperand(1), DemandedMask,
906 RHSKnownZero, RHSKnownOne, Depth+1);
907 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
908 LHSKnownZero, LHSKnownOne, Depth+1);
909
910 // If all of the demanded bits are known 1 on one side, return the other.
911 // These bits cannot contribute to the result of the 'and' in this
912 // context.
913 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
914 (DemandedMask & ~LHSKnownZero))
915 return I->getOperand(0);
916 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
917 (DemandedMask & ~RHSKnownZero))
918 return I->getOperand(1);
919
920 // If all of the demanded bits in the inputs are known zeros, return zero.
921 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000922 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000923
924 } else if (I->getOpcode() == Instruction::Or) {
925 // We can simplify (X|Y) -> X or Y in the user's context if we know that
926 // only bits from X or Y are demanded.
927
928 // If either the LHS or the RHS are One, the result is One.
929 ComputeMaskedBits(I->getOperand(1), DemandedMask,
930 RHSKnownZero, RHSKnownOne, Depth+1);
931 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
932 LHSKnownZero, LHSKnownOne, Depth+1);
933
934 // If all of the demanded bits are known zero on one side, return the
935 // other. These bits cannot contribute to the result of the 'or' in this
936 // context.
937 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
938 (DemandedMask & ~LHSKnownOne))
939 return I->getOperand(0);
940 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
941 (DemandedMask & ~RHSKnownOne))
942 return I->getOperand(1);
943
944 // If all of the potentially set bits on one side are known to be set on
945 // the other side, just use the 'other' side.
946 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
947 (DemandedMask & (~RHSKnownZero)))
948 return I->getOperand(0);
949 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
950 (DemandedMask & (~LHSKnownZero)))
951 return I->getOperand(1);
952 }
953
Chris Lattner4598c942009-01-31 08:24:16 +0000954 // Compute the KnownZero/KnownOne bits to simplify things downstream.
955 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
956 return 0;
957 }
958
959 // If this is the root being simplified, allow it to have multiple uses,
960 // just set the DemandedMask to all bits so that we can try to simplify the
961 // operands. This allows visitTruncInst (for example) to simplify the
962 // operand of a trunc without duplicating all the logic below.
963 if (Depth == 0 && !V->hasOneUse())
964 DemandedMask = APInt::getAllOnesValue(BitWidth);
965
Reid Spencer8cb68342007-03-12 17:25:59 +0000966 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000967 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000968 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000969 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000970 case Instruction::And:
971 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000972 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
973 RHSKnownZero, RHSKnownOne, Depth+1) ||
974 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000975 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 return I;
977 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
978 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000979
980 // If all of the demanded bits are known 1 on one side, return the other.
981 // These bits cannot contribute to the result of the 'and'.
982 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
983 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000984 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000985 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
986 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000987 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000988
989 // If all of the demanded bits in the inputs are known zeros, return zero.
990 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000991 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000992
993 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000994 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000995 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000996
997 // Output known-1 bits are only known if set in both the LHS & RHS.
998 RHSKnownOne &= LHSKnownOne;
999 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1000 RHSKnownZero |= LHSKnownZero;
1001 break;
1002 case Instruction::Or:
1003 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001004 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1005 RHSKnownZero, RHSKnownOne, Depth+1) ||
1006 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +00001007 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001008 return I;
1009 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1010 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001011
1012 // If all of the demanded bits are known zero on one side, return the other.
1013 // These bits cannot contribute to the result of the 'or'.
1014 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1015 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001016 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001017 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1018 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001019 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001020
1021 // If all of the potentially set bits on one side are known to be set on
1022 // the other side, just use the 'other' side.
1023 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1024 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001025 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001026 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1027 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001028 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001029
1030 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001031 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001032 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001033
1034 // Output known-0 bits are only known if clear in both the LHS & RHS.
1035 RHSKnownZero &= LHSKnownZero;
1036 // Output known-1 are known to be set if set in either the LHS | RHS.
1037 RHSKnownOne |= LHSKnownOne;
1038 break;
1039 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001040 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1041 RHSKnownZero, RHSKnownOne, Depth+1) ||
1042 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001043 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001044 return I;
1045 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1046 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001047
1048 // If all of the demanded bits are known zero on one side, return the other.
1049 // These bits cannot contribute to the result of the 'xor'.
1050 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001051 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001052 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001053 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001054
1055 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1056 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1057 (RHSKnownOne & LHSKnownOne);
1058 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1059 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1060 (RHSKnownOne & LHSKnownZero);
1061
1062 // If all of the demanded bits are known to be zero on one side or the
1063 // other, turn this into an *inclusive* or.
1064 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001065 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1066 Instruction *Or =
1067 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1068 I->getName());
1069 return InsertNewInstBefore(Or, *I);
1070 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001071
1072 // If all of the demanded bits on one side are known, and all of the set
1073 // bits on that side are also known to be set on the other side, turn this
1074 // into an AND, as we know the bits will be cleared.
1075 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1076 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1077 // all known
1078 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001079 Constant *AndC = Constant::getIntegerValue(VTy,
1080 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001081 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001082 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001083 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001084 }
1085 }
1086
1087 // If the RHS is a constant, see if we can simplify it.
1088 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001089 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001090 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001091
Chris Lattnerd0883142009-10-11 22:22:13 +00001092 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1093 // are flipping are known to be set, then the xor is just resetting those
1094 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1095 // simplifying both of them.
1096 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1097 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1098 isa<ConstantInt>(I->getOperand(1)) &&
1099 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1100 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1101 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1102 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1103 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1104
1105 Constant *AndC =
1106 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1107 Instruction *NewAnd =
1108 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1109 InsertNewInstBefore(NewAnd, *I);
1110
1111 Constant *XorC =
1112 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1113 Instruction *NewXor =
1114 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1115 return InsertNewInstBefore(NewXor, *I);
1116 }
1117
1118
Reid Spencer8cb68342007-03-12 17:25:59 +00001119 RHSKnownZero = KnownZeroOut;
1120 RHSKnownOne = KnownOneOut;
1121 break;
1122 }
1123 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001124 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1125 RHSKnownZero, RHSKnownOne, Depth+1) ||
1126 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001127 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001128 return I;
1129 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1130 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001131
1132 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001133 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1134 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001135 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001136
1137 // Only known if known in both the LHS and RHS.
1138 RHSKnownOne &= LHSKnownOne;
1139 RHSKnownZero &= LHSKnownZero;
1140 break;
1141 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001142 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001143 DemandedMask.zext(truncBf);
1144 RHSKnownZero.zext(truncBf);
1145 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001146 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001147 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001148 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001149 DemandedMask.trunc(BitWidth);
1150 RHSKnownZero.trunc(BitWidth);
1151 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001152 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001153 break;
1154 }
1155 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001156 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001157 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001158
1159 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1160 if (const VectorType *SrcVTy =
1161 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1162 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1163 // Don't touch a bitcast between vectors of different element counts.
1164 return false;
1165 } else
1166 // Don't touch a scalar-to-vector bitcast.
1167 return false;
1168 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1169 // Don't touch a vector-to-scalar bitcast.
1170 return false;
1171
Chris Lattner886ab6c2009-01-31 08:15:18 +00001172 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001173 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001174 return I;
1175 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001176 break;
1177 case Instruction::ZExt: {
1178 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001179 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001180
Zhou Shengd48653a2007-03-29 04:45:55 +00001181 DemandedMask.trunc(SrcBitWidth);
1182 RHSKnownZero.trunc(SrcBitWidth);
1183 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001184 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001185 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001186 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001187 DemandedMask.zext(BitWidth);
1188 RHSKnownZero.zext(BitWidth);
1189 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001190 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001191 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001192 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001193 break;
1194 }
1195 case Instruction::SExt: {
1196 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001197 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001198
Reid Spencer8cb68342007-03-12 17:25:59 +00001199 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001200 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001201
Zhou Sheng01542f32007-03-29 02:26:30 +00001202 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001203 // If any of the sign extended bits are demanded, we know that the sign
1204 // bit is demanded.
1205 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001206 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001207
Zhou Shengd48653a2007-03-29 04:45:55 +00001208 InputDemandedBits.trunc(SrcBitWidth);
1209 RHSKnownZero.trunc(SrcBitWidth);
1210 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001211 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001212 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001213 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001214 InputDemandedBits.zext(BitWidth);
1215 RHSKnownZero.zext(BitWidth);
1216 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001217 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001218
1219 // If the sign bit of the input is known set or clear, then we know the
1220 // top bits of the result.
1221
1222 // If the input sign bit is known zero, or if the NewBits are not demanded
1223 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001224 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001225 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001226 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1227 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001228 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001229 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001230 }
1231 break;
1232 }
1233 case Instruction::Add: {
1234 // Figure out what the input bits are. If the top bits of the and result
1235 // are not demanded, then the add doesn't demand them from its input
1236 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001237 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001238
1239 // If there is a constant on the RHS, there are a variety of xformations
1240 // we can do.
1241 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1242 // If null, this should be simplified elsewhere. Some of the xforms here
1243 // won't work if the RHS is zero.
1244 if (RHS->isZero())
1245 break;
1246
1247 // If the top bit of the output is demanded, demand everything from the
1248 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001249 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001250
1251 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001252 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001253 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001254 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001255
1256 // If the RHS of the add has bits set that can't affect the input, reduce
1257 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001258 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001259 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001260
1261 // Avoid excess work.
1262 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1263 break;
1264
1265 // Turn it into OR if input bits are zero.
1266 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1267 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001268 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001269 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001270 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001271 }
1272
1273 // We can say something about the output known-zero and known-one bits,
1274 // depending on potential carries from the input constant and the
1275 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1276 // bits set and the RHS constant is 0x01001, then we know we have a known
1277 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1278
1279 // To compute this, we first compute the potential carry bits. These are
1280 // the bits which may be modified. I'm not aware of a better way to do
1281 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001282 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001283 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001284
1285 // Now that we know which bits have carries, compute the known-1/0 sets.
1286
1287 // Bits are known one if they are known zero in one operand and one in the
1288 // other, and there is no input carry.
1289 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1290 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1291
1292 // Bits are known zero if they are known zero in both operands and there
1293 // is no input carry.
1294 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1295 } else {
1296 // If the high-bits of this ADD are not demanded, then it does not demand
1297 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001298 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001299 // Right fill the mask of bits for this ADD to demand the most
1300 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001301 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001302 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1303 LHSKnownZero, LHSKnownOne, Depth+1) ||
1304 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001305 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001306 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001307 }
1308 }
1309 break;
1310 }
1311 case Instruction::Sub:
1312 // If the high-bits of this SUB are not demanded, then it does not demand
1313 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001314 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001315 // Right fill the mask of bits for this SUB to demand the most
1316 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001317 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001318 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001319 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1320 LHSKnownZero, LHSKnownOne, Depth+1) ||
1321 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001322 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001323 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001324 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001325 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1326 // the known zeros and ones.
1327 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001328 break;
1329 case Instruction::Shl:
1330 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001331 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001332 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001333 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001334 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001335 return I;
1336 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001337 RHSKnownZero <<= ShiftAmt;
1338 RHSKnownOne <<= ShiftAmt;
1339 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001340 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001341 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001342 }
1343 break;
1344 case Instruction::LShr:
1345 // For a logical shift right
1346 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001347 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001348
Reid Spencer8cb68342007-03-12 17:25:59 +00001349 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001350 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001351 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001352 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001353 return I;
1354 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001355 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1356 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001357 if (ShiftAmt) {
1358 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001359 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001360 RHSKnownZero |= HighBits; // high bits known zero.
1361 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001362 }
1363 break;
1364 case Instruction::AShr:
1365 // If this is an arithmetic shift right and only the low-bit is set, we can
1366 // always convert this into a logical shr, even if the shift amount is
1367 // variable. The low bit of the shift cannot be an input sign bit unless
1368 // the shift amount is >= the size of the datatype, which is undefined.
1369 if (DemandedMask == 1) {
1370 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001371 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001372 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001373 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001374 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001375
1376 // If the sign bit is the only bit demanded by this ashr, then there is no
1377 // need to do it, the shift doesn't change the high bit.
1378 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001379 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001380
1381 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001382 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001383
Reid Spencer8cb68342007-03-12 17:25:59 +00001384 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001385 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001386 // If any of the "high bits" are demanded, we should set the sign bit as
1387 // demanded.
1388 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1389 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001390 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001391 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001392 return I;
1393 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001394 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001395 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001396 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1397 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1398
1399 // Handle the sign bits.
1400 APInt SignBit(APInt::getSignBit(BitWidth));
1401 // Adjust to where it is now in the mask.
1402 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1403
1404 // If the input sign bit is known to be zero, or if none of the top bits
1405 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001406 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001407 (HighBits & ~DemandedMask) == HighBits) {
1408 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001409 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001410 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001411 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001412 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1413 RHSKnownOne |= HighBits;
1414 }
1415 }
1416 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001417 case Instruction::SRem:
1418 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001419 APInt RA = Rem->getValue().abs();
1420 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001421 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001422 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001423
Nick Lewycky8e394322008-11-02 02:41:50 +00001424 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001425 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001426 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001427 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001428 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001429
1430 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1431 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001432
1433 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001434
Chris Lattner886ab6c2009-01-31 08:15:18 +00001435 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001436 }
1437 }
1438 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001439 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001440 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1441 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001442 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1443 KnownZero2, KnownOne2, Depth+1) ||
1444 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001445 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001446 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001447
Chris Lattner455e9ab2009-01-21 18:09:24 +00001448 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001449 Leaders = std::max(Leaders,
1450 KnownZero2.countLeadingOnes());
1451 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001452 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001453 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001454 case Instruction::Call:
1455 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1456 switch (II->getIntrinsicID()) {
1457 default: break;
1458 case Intrinsic::bswap: {
1459 // If the only bits demanded come from one byte of the bswap result,
1460 // just shift the input byte into position to eliminate the bswap.
1461 unsigned NLZ = DemandedMask.countLeadingZeros();
1462 unsigned NTZ = DemandedMask.countTrailingZeros();
1463
1464 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1465 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1466 // have 14 leading zeros, round to 8.
1467 NLZ &= ~7;
1468 NTZ &= ~7;
1469 // If we need exactly one byte, we can do this transformation.
1470 if (BitWidth-NLZ-NTZ == 8) {
1471 unsigned ResultBit = NTZ;
1472 unsigned InputBit = BitWidth-NTZ-8;
1473
1474 // Replace this with either a left or right shift to get the byte into
1475 // the right place.
1476 Instruction *NewVal;
1477 if (InputBit > ResultBit)
1478 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001479 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001480 else
1481 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001482 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001483 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001484 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001485 }
1486
1487 // TODO: Could compute known zero/one bits based on the input.
1488 break;
1489 }
1490 }
1491 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001492 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001493 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001494 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001495
1496 // If the client is only demanding bits that we know, return the known
1497 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001498 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1499 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001500 return false;
1501}
1502
Chris Lattner867b99f2006-10-05 06:55:50 +00001503
Mon P Wangaeb06d22008-11-10 04:46:22 +00001504/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001505/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001506/// actually used by the caller. This method analyzes which elements of the
1507/// operand are undef and returns that information in UndefElts.
1508///
1509/// If the information about demanded elements can be used to simplify the
1510/// operation, the operation is simplified, then the resultant value is
1511/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001512Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1513 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001514 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001515 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001516 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001517 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001518
1519 if (isa<UndefValue>(V)) {
1520 // If the entire vector is undefined, just return this info.
1521 UndefElts = EltMask;
1522 return 0;
1523 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1524 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001525 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001526 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001527
Chris Lattner867b99f2006-10-05 06:55:50 +00001528 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001529 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1530 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001531 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001532
1533 std::vector<Constant*> Elts;
1534 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001535 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001536 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001537 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001538 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1539 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001540 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001541 } else { // Otherwise, defined.
1542 Elts.push_back(CP->getOperand(i));
1543 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001544
Chris Lattner867b99f2006-10-05 06:55:50 +00001545 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001546 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001547 return NewCP != CP ? NewCP : 0;
1548 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001549 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001550 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001551
1552 // Check if this is identity. If so, return 0 since we are not simplifying
1553 // anything.
1554 if (DemandedElts == ((1ULL << VWidth) -1))
1555 return 0;
1556
Reid Spencer9d6565a2007-02-15 02:26:10 +00001557 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001558 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001559 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001560 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001561 for (unsigned i = 0; i != VWidth; ++i) {
1562 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1563 Elts.push_back(Elt);
1564 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001565 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001566 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001567 }
1568
Dan Gohman488fbfc2008-09-09 18:11:14 +00001569 // Limit search depth.
1570 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001571 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001572
1573 // If multiple users are using the root value, procede with
1574 // simplification conservatively assuming that all elements
1575 // are needed.
1576 if (!V->hasOneUse()) {
1577 // Quit if we find multiple users of a non-root value though.
1578 // They'll be handled when it's their turn to be visited by
1579 // the main instcombine process.
1580 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001581 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001582 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001583
1584 // Conservatively assume that all elements are needed.
1585 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001586 }
1587
1588 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001589 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001590
1591 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001592 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001593 Value *TmpV;
1594 switch (I->getOpcode()) {
1595 default: break;
1596
1597 case Instruction::InsertElement: {
1598 // If this is a variable index, we don't know which element it overwrites.
1599 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001600 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001601 if (Idx == 0) {
1602 // Note that we can't propagate undef elt info, because we don't know
1603 // which elt is getting updated.
1604 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1605 UndefElts2, Depth+1);
1606 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1607 break;
1608 }
1609
1610 // If this is inserting an element that isn't demanded, remove this
1611 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001612 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001613 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1614 Worklist.Add(I);
1615 return I->getOperand(0);
1616 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001617
1618 // Otherwise, the element inserted overwrites whatever was there, so the
1619 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001620 APInt DemandedElts2 = DemandedElts;
1621 DemandedElts2.clear(IdxNo);
1622 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001623 UndefElts, Depth+1);
1624 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1625
1626 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001627 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001628 break;
1629 }
1630 case Instruction::ShuffleVector: {
1631 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001632 uint64_t LHSVWidth =
1633 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001634 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001635 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001636 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001637 unsigned MaskVal = Shuffle->getMaskValue(i);
1638 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001639 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001640 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001641 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001642 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001643 else
Evan Cheng388df622009-02-03 10:05:09 +00001644 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001645 }
1646 }
1647 }
1648
Nate Begeman7b254672009-02-11 22:36:25 +00001649 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001650 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001651 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001652 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1653
Nate Begeman7b254672009-02-11 22:36:25 +00001654 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001655 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1656 UndefElts3, Depth+1);
1657 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1658
1659 bool NewUndefElts = false;
1660 for (unsigned i = 0; i < VWidth; i++) {
1661 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001662 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001663 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001664 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001665 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001666 NewUndefElts = true;
1667 UndefElts.set(i);
1668 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001669 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001670 if (UndefElts3[MaskVal - LHSVWidth]) {
1671 NewUndefElts = true;
1672 UndefElts.set(i);
1673 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001674 }
1675 }
1676
1677 if (NewUndefElts) {
1678 // Add additional discovered undefs.
1679 std::vector<Constant*> Elts;
1680 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001681 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001682 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001683 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001684 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001685 Shuffle->getMaskValue(i)));
1686 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001687 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001688 MadeChange = true;
1689 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001690 break;
1691 }
Chris Lattner69878332007-04-14 22:29:23 +00001692 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001693 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001694 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1695 if (!VTy) break;
1696 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001697 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001698 unsigned Ratio;
1699
1700 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001701 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001702 // elements as are demanded of us.
1703 Ratio = 1;
1704 InputDemandedElts = DemandedElts;
1705 } else if (VWidth > InVWidth) {
1706 // Untested so far.
1707 break;
1708
1709 // If there are more elements in the result than there are in the source,
1710 // then an input element is live if any of the corresponding output
1711 // elements are live.
1712 Ratio = VWidth/InVWidth;
1713 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001714 if (DemandedElts[OutIdx])
1715 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001716 }
1717 } else {
1718 // Untested so far.
1719 break;
1720
1721 // If there are more elements in the source than there are in the result,
1722 // then an input element is live if the corresponding output element is
1723 // live.
1724 Ratio = InVWidth/VWidth;
1725 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001726 if (DemandedElts[InIdx/Ratio])
1727 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001728 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001729
Chris Lattner69878332007-04-14 22:29:23 +00001730 // div/rem demand all inputs, because they don't want divide by zero.
1731 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1732 UndefElts2, Depth+1);
1733 if (TmpV) {
1734 I->setOperand(0, TmpV);
1735 MadeChange = true;
1736 }
1737
1738 UndefElts = UndefElts2;
1739 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001740 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001741 // If there are more elements in the result than there are in the source,
1742 // then an output element is undef if the corresponding input element is
1743 // undef.
1744 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001745 if (UndefElts2[OutIdx/Ratio])
1746 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001747 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001748 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001749 // If there are more elements in the source than there are in the result,
1750 // then a result element is undef if all of the corresponding input
1751 // elements are undef.
1752 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1753 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001754 if (!UndefElts2[InIdx]) // Not undef?
1755 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001756 }
1757 break;
1758 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001759 case Instruction::And:
1760 case Instruction::Or:
1761 case Instruction::Xor:
1762 case Instruction::Add:
1763 case Instruction::Sub:
1764 case Instruction::Mul:
1765 // div/rem demand all inputs, because they don't want divide by zero.
1766 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1767 UndefElts, Depth+1);
1768 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1769 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1770 UndefElts2, Depth+1);
1771 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1772
1773 // Output elements are undefined if both are undefined. Consider things
1774 // like undef&0. The result is known zero, not undef.
1775 UndefElts &= UndefElts2;
1776 break;
1777
1778 case Instruction::Call: {
1779 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1780 if (!II) break;
1781 switch (II->getIntrinsicID()) {
1782 default: break;
1783
1784 // Binary vector operations that work column-wise. A dest element is a
1785 // function of the corresponding input elements from the two inputs.
1786 case Intrinsic::x86_sse_sub_ss:
1787 case Intrinsic::x86_sse_mul_ss:
1788 case Intrinsic::x86_sse_min_ss:
1789 case Intrinsic::x86_sse_max_ss:
1790 case Intrinsic::x86_sse2_sub_sd:
1791 case Intrinsic::x86_sse2_mul_sd:
1792 case Intrinsic::x86_sse2_min_sd:
1793 case Intrinsic::x86_sse2_max_sd:
1794 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1795 UndefElts, Depth+1);
1796 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1797 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1798 UndefElts2, Depth+1);
1799 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1800
1801 // If only the low elt is demanded and this is a scalarizable intrinsic,
1802 // scalarize it now.
1803 if (DemandedElts == 1) {
1804 switch (II->getIntrinsicID()) {
1805 default: break;
1806 case Intrinsic::x86_sse_sub_ss:
1807 case Intrinsic::x86_sse_mul_ss:
1808 case Intrinsic::x86_sse2_sub_sd:
1809 case Intrinsic::x86_sse2_mul_sd:
1810 // TODO: Lower MIN/MAX/ABS/etc
1811 Value *LHS = II->getOperand(1);
1812 Value *RHS = II->getOperand(2);
1813 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001814 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001815 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001816 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001817 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001818
1819 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001820 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001821 case Intrinsic::x86_sse_sub_ss:
1822 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001823 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001824 II->getName()), *II);
1825 break;
1826 case Intrinsic::x86_sse_mul_ss:
1827 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001828 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001829 II->getName()), *II);
1830 break;
1831 }
1832
1833 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001834 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001835 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001836 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001837 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001838 return New;
1839 }
1840 }
1841
1842 // Output elements are undefined if both are undefined. Consider things
1843 // like undef&0. The result is known zero, not undef.
1844 UndefElts &= UndefElts2;
1845 break;
1846 }
1847 break;
1848 }
1849 }
1850 return MadeChange ? I : 0;
1851}
1852
Dan Gohman45b4e482008-05-19 22:14:15 +00001853
Chris Lattner564a7272003-08-13 19:01:45 +00001854/// AssociativeOpt - Perform an optimization on an associative operator. This
1855/// function is designed to check a chain of associative operators for a
1856/// potential to apply a certain optimization. Since the optimization may be
1857/// applicable if the expression was reassociated, this checks the chain, then
1858/// reassociates the expression as necessary to expose the optimization
1859/// opportunity. This makes use of a special Functor, which must define
1860/// 'shouldApply' and 'apply' methods.
1861///
1862template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001863static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001864 unsigned Opcode = Root.getOpcode();
1865 Value *LHS = Root.getOperand(0);
1866
1867 // Quick check, see if the immediate LHS matches...
1868 if (F.shouldApply(LHS))
1869 return F.apply(Root);
1870
1871 // Otherwise, if the LHS is not of the same opcode as the root, return.
1872 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001873 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001874 // Should we apply this transform to the RHS?
1875 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1876
1877 // If not to the RHS, check to see if we should apply to the LHS...
1878 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1879 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1880 ShouldApply = true;
1881 }
1882
1883 // If the functor wants to apply the optimization to the RHS of LHSI,
1884 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1885 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001886 // Now all of the instructions are in the current basic block, go ahead
1887 // and perform the reassociation.
1888 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1889
1890 // First move the selected RHS to the LHS of the root...
1891 Root.setOperand(0, LHSI->getOperand(1));
1892
1893 // Make what used to be the LHS of the root be the user of the root...
1894 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001895 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001896 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001897 return 0;
1898 }
Chris Lattner65725312004-04-16 18:08:07 +00001899 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001900 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001901 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001902 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001903 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001904
1905 // Now propagate the ExtraOperand down the chain of instructions until we
1906 // get to LHSI.
1907 while (TmpLHSI != LHSI) {
1908 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001909 // Move the instruction to immediately before the chain we are
1910 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001911 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001912 ARI = NextLHSI;
1913
Chris Lattner564a7272003-08-13 19:01:45 +00001914 Value *NextOp = NextLHSI->getOperand(1);
1915 NextLHSI->setOperand(1, ExtraOperand);
1916 TmpLHSI = NextLHSI;
1917 ExtraOperand = NextOp;
1918 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001919
Chris Lattner564a7272003-08-13 19:01:45 +00001920 // Now that the instructions are reassociated, have the functor perform
1921 // the transformation...
1922 return F.apply(Root);
1923 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001924
Chris Lattner564a7272003-08-13 19:01:45 +00001925 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1926 }
1927 return 0;
1928}
1929
Dan Gohman844731a2008-05-13 00:00:25 +00001930namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001931
Nick Lewycky02d639f2008-05-23 04:34:58 +00001932// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001933struct AddRHS {
1934 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001935 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001936 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1937 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001938 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001939 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001940 }
1941};
1942
1943// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1944// iff C1&C2 == 0
1945struct AddMaskingAnd {
1946 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001947 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001948 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001949 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001950 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001951 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001952 }
1953 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001954 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001955 }
1956};
1957
Dan Gohman844731a2008-05-13 00:00:25 +00001958}
1959
Chris Lattner6e7ba452005-01-01 16:22:27 +00001960static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001961 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001962 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001963 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001964
Chris Lattner2eefe512004-04-09 19:05:30 +00001965 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001966 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1967 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001968
Chris Lattner2eefe512004-04-09 19:05:30 +00001969 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1970 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001971 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1972 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001973 }
1974
1975 Value *Op0 = SO, *Op1 = ConstOperand;
1976 if (!ConstIsRHS)
1977 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001978
Chris Lattner6e7ba452005-01-01 16:22:27 +00001979 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001980 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1981 SO->getName()+".op");
1982 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1983 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1984 SO->getName()+".cmp");
1985 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1986 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1987 SO->getName()+".cmp");
1988 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001989}
1990
1991// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1992// constant as the other operand, try to fold the binary operator into the
1993// select arguments. This also works for Cast instructions, which obviously do
1994// not have a second operand.
1995static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1996 InstCombiner *IC) {
1997 // Don't modify shared select instructions
1998 if (!SI->hasOneUse()) return 0;
1999 Value *TV = SI->getOperand(1);
2000 Value *FV = SI->getOperand(2);
2001
2002 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002003 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00002004 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002005
Chris Lattner6e7ba452005-01-01 16:22:27 +00002006 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2007 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2008
Gabor Greif051a9502008-04-06 20:25:17 +00002009 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2010 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002011 }
2012 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002013}
2014
Chris Lattner4e998b22004-09-29 05:07:12 +00002015
Chris Lattner5d1704d2009-09-27 19:57:57 +00002016/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2017/// has a PHI node as operand #0, see if we can fold the instruction into the
2018/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002019///
2020/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2021/// that would normally be unprofitable because they strongly encourage jump
2022/// threading.
2023Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2024 bool AllowAggressive) {
2025 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002026 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002027 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002028 if (NumPHIValues == 0 ||
2029 // We normally only transform phis with a single use, unless we're trying
2030 // hard to make jump threading happen.
2031 (!PN->hasOneUse() && !AllowAggressive))
2032 return 0;
2033
2034
Chris Lattner5d1704d2009-09-27 19:57:57 +00002035 // Check to see if all of the operands of the PHI are simple constants
2036 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002037 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2038 // bail out. We don't do arbitrary constant expressions here because moving
2039 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002040 BasicBlock *NonConstBB = 0;
2041 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002042 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2043 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002044 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002045 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002046 NonConstBB = PN->getIncomingBlock(i);
2047
2048 // If the incoming non-constant value is in I's block, we have an infinite
2049 // loop.
2050 if (NonConstBB == I.getParent())
2051 return 0;
2052 }
2053
2054 // If there is exactly one non-constant value, we can insert a copy of the
2055 // operation in that block. However, if this is a critical edge, we would be
2056 // inserting the computation one some other paths (e.g. inside a loop). Only
2057 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002058 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002059 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2060 if (!BI || !BI->isUnconditional()) return 0;
2061 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002062
2063 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002064 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002065 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002066 InsertNewInstBefore(NewPN, *PN);
2067 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002068
2069 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002070 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2071 // We only currently try to fold the condition of a select when it is a phi,
2072 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002073 Value *TrueV = SI->getTrueValue();
2074 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002075 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002076 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002077 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002078 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2079 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002080 Value *InV = 0;
2081 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002082 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002083 } else {
2084 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002085 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2086 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002087 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002088 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002089 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002090 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002091 }
2092 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002093 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002094 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002095 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002096 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002097 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002098 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002099 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002100 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002101 } else {
2102 assert(PN->getIncomingBlock(i) == NonConstBB);
2103 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002104 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002105 PN->getIncomingValue(i), C, "phitmp",
2106 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002107 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002108 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002109 CI->getPredicate(),
2110 PN->getIncomingValue(i), C, "phitmp",
2111 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002112 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002113 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002114
2115 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002116 }
2117 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002118 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002119 } else {
2120 CastInst *CI = cast<CastInst>(&I);
2121 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002122 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002123 Value *InV;
2124 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002125 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002126 } else {
2127 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002128 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002129 I.getType(), "phitmp",
2130 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002131 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002132 }
2133 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002134 }
2135 }
2136 return ReplaceInstUsesWith(I, NewPN);
2137}
2138
Chris Lattner2454a2e2008-01-29 06:52:45 +00002139
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002140/// WillNotOverflowSignedAdd - Return true if we can prove that:
2141/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2142/// This basically requires proving that the add in the original type would not
2143/// overflow to change the sign bit or have a carry out.
2144bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2145 // There are different heuristics we can use for this. Here are some simple
2146 // ones.
2147
2148 // Add has the property that adding any two 2's complement numbers can only
2149 // have one carry bit which can change a sign. As such, if LHS and RHS each
2150 // have at least two sign bits, we know that the addition of the two values will
2151 // sign extend fine.
2152 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2153 return true;
2154
2155
2156 // If one of the operands only has one non-zero bit, and if the other operand
2157 // has a known-zero bit in a more significant place than it (not including the
2158 // sign bit) the ripple may go up to and fill the zero, but won't change the
2159 // sign. For example, (X & ~4) + 1.
2160
2161 // TODO: Implement.
2162
2163 return false;
2164}
2165
Chris Lattner2454a2e2008-01-29 06:52:45 +00002166
Chris Lattner7e708292002-06-25 16:13:24 +00002167Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002168 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002169 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002170
Chris Lattner66331a42004-04-10 22:01:55 +00002171 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002172 // X + undef -> undef
2173 if (isa<UndefValue>(RHS))
2174 return ReplaceInstUsesWith(I, RHS);
2175
Chris Lattner66331a42004-04-10 22:01:55 +00002176 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002177 if (RHSC->isNullValue())
2178 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002179
Chris Lattner66331a42004-04-10 22:01:55 +00002180 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002181 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002182 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002183 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002184 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002185 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002186
2187 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2188 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002189 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002190 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002191
Eli Friedman709b33d2009-07-13 22:27:52 +00002192 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002193 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002194 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002195 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002196 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002197
2198 if (isa<PHINode>(LHS))
2199 if (Instruction *NV = FoldOpIntoPhi(I))
2200 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002201
Chris Lattner4f637d42006-01-06 17:59:59 +00002202 ConstantInt *XorRHS = 0;
2203 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002204 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002205 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002206 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002207 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002208
Zhou Sheng4351c642007-04-02 08:20:41 +00002209 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002210 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2211 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002212 do {
2213 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002214 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2215 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002216 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2217 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002218 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002219 if (!MaskedValueIsZero(XorLHS,
2220 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002221 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002222 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002223 }
2224 }
2225 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002226 C0080Val = APIntOps::lshr(C0080Val, Size);
2227 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2228 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002229
Reid Spencer35c38852007-03-28 01:36:16 +00002230 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002231 // with funny bit widths then this switch statement should be removed. It
2232 // is just here to get the size of the "middle" type back up to something
2233 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002234 const Type *MiddleType = 0;
2235 switch (Size) {
2236 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002237 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2238 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2239 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002240 }
2241 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002242 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002243 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002244 }
2245 }
Chris Lattner66331a42004-04-10 22:01:55 +00002246 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002247
Owen Anderson1d0be152009-08-13 21:58:54 +00002248 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002249 return BinaryOperator::CreateXor(LHS, RHS);
2250
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002251 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002252 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002253 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002254 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002255
2256 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2257 if (RHSI->getOpcode() == Instruction::Sub)
2258 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2259 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2260 }
2261 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2262 if (LHSI->getOpcode() == Instruction::Sub)
2263 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2264 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2265 }
Robert Bocchino71698282004-07-27 21:02:21 +00002266 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002267
Chris Lattner5c4afb92002-05-08 22:46:53 +00002268 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002269 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002270 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002271 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002272 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002273 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002274 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002275 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002276 }
2277
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002278 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002279 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002280
2281 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002282 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002283 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002284 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002285
Misha Brukmanfd939082005-04-21 23:48:37 +00002286
Chris Lattner50af16a2004-11-13 19:50:12 +00002287 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002288 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002289 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002290 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002291
2292 // X*C1 + X*C2 --> X * (C1+C2)
2293 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002294 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002295 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002296 }
2297
2298 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002299 if (dyn_castFoldableMul(RHS, C2) == LHS)
2300 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002301
Chris Lattnere617c9e2007-01-05 02:17:46 +00002302 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002303 if (dyn_castNotVal(LHS) == RHS ||
2304 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002305 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002306
Chris Lattnerad3448c2003-02-18 19:57:07 +00002307
Chris Lattner564a7272003-08-13 19:01:45 +00002308 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002309 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2310 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002311 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002312
2313 // A+B --> A|B iff A and B have no bits set in common.
2314 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2315 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2316 APInt LHSKnownOne(IT->getBitWidth(), 0);
2317 APInt LHSKnownZero(IT->getBitWidth(), 0);
2318 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2319 if (LHSKnownZero != 0) {
2320 APInt RHSKnownOne(IT->getBitWidth(), 0);
2321 APInt RHSKnownZero(IT->getBitWidth(), 0);
2322 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2323
2324 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002325 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002326 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002327 }
2328 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002329
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002330 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002331 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002332 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002333 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2334 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002335 if (W != Y) {
2336 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002337 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002338 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002339 std::swap(W, X);
2340 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002341 std::swap(Y, Z);
2342 std::swap(W, X);
2343 }
2344 }
2345
2346 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002347 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002348 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002349 }
2350 }
2351 }
2352
Chris Lattner6b032052003-10-02 15:11:26 +00002353 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002354 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002355 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002356 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002357
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002358 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002359 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002360 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002361 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002362 if (Anded == CRHS) {
2363 // See if all bits from the first bit set in the Add RHS up are included
2364 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002365 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002366
2367 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002368 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002369
2370 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002371 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002372
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002373 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2374 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002375 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002376 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002377 }
2378 }
2379 }
2380
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002381 // Try to fold constant add into select arguments.
2382 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002383 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002384 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002385 }
2386
Chris Lattner42790482007-12-20 01:56:58 +00002387 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002388 {
2389 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002390 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002391 if (!SI) {
2392 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002393 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002394 }
Chris Lattner42790482007-12-20 01:56:58 +00002395 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002396 Value *TV = SI->getTrueValue();
2397 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002398 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002399
2400 // Can we fold the add into the argument of the select?
2401 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002402 if (match(FV, m_Zero()) &&
2403 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002404 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002405 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002406 if (match(TV, m_Zero()) &&
2407 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002408 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002409 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002410 }
2411 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002412
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002413 // Check for (add (sext x), y), see if we can merge this into an
2414 // integer add followed by a sext.
2415 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2416 // (add (sext x), cst) --> (sext (add x, cst'))
2417 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2418 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002419 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002420 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002421 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002422 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2423 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002424 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2425 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002426 return new SExtInst(NewAdd, I.getType());
2427 }
2428 }
2429
2430 // (add (sext x), (sext y)) --> (sext (add int x, y))
2431 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2432 // Only do this if x/y have the same type, if at last one of them has a
2433 // single use (so we don't increase the number of sexts), and if the
2434 // integer add will not overflow.
2435 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2436 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2437 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2438 RHSConv->getOperand(0))) {
2439 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002440 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2441 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002442 return new SExtInst(NewAdd, I.getType());
2443 }
2444 }
2445 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002446
2447 return Changed ? &I : 0;
2448}
2449
2450Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2451 bool Changed = SimplifyCommutative(I);
2452 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2453
2454 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2455 // X + 0 --> X
2456 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002457 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002458 (I.getType())->getValueAPF()))
2459 return ReplaceInstUsesWith(I, LHS);
2460 }
2461
2462 if (isa<PHINode>(LHS))
2463 if (Instruction *NV = FoldOpIntoPhi(I))
2464 return NV;
2465 }
2466
2467 // -A + B --> B - A
2468 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002469 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002470 return BinaryOperator::CreateFSub(RHS, LHSV);
2471
2472 // A + -B --> A - B
2473 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002474 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002475 return BinaryOperator::CreateFSub(LHS, V);
2476
2477 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2478 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2479 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2480 return ReplaceInstUsesWith(I, LHS);
2481
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002482 // Check for (add double (sitofp x), y), see if we can merge this into an
2483 // integer add followed by a promotion.
2484 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2485 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2486 // ... if the constant fits in the integer value. This is useful for things
2487 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2488 // requires a constant pool load, and generally allows the add to be better
2489 // instcombined.
2490 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2491 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002492 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002493 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002494 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002495 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2496 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002497 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2498 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002499 return new SIToFPInst(NewAdd, I.getType());
2500 }
2501 }
2502
2503 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2504 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2505 // Only do this if x/y have the same type, if at last one of them has a
2506 // single use (so we don't increase the number of int->fp conversions),
2507 // and if the integer add will not overflow.
2508 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2509 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2510 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2511 RHSConv->getOperand(0))) {
2512 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002513 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00002514 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002515 return new SIToFPInst(NewAdd, I.getType());
2516 }
2517 }
2518 }
2519
Chris Lattner7e708292002-06-25 16:13:24 +00002520 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002521}
2522
Chris Lattner092543c2009-11-04 08:05:20 +00002523
2524/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2525/// code necessary to compute the offset from the base pointer (without adding
2526/// in the base pointer). Return the result as a signed integer of intptr size.
2527static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2528 TargetData &TD = *IC.getTargetData();
2529 gep_type_iterator GTI = gep_type_begin(GEP);
2530 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2531 Value *Result = Constant::getNullValue(IntPtrTy);
2532
2533 // Build a mask for high order bits.
2534 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2535 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2536
2537 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2538 ++i, ++GTI) {
2539 Value *Op = *i;
2540 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2541 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2542 if (OpC->isZero()) continue;
2543
2544 // Handle a struct index, which adds its field offset to the pointer.
2545 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2546 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2547
2548 Result = IC.Builder->CreateAdd(Result,
2549 ConstantInt::get(IntPtrTy, Size),
2550 GEP->getName()+".offs");
2551 continue;
2552 }
2553
2554 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2555 Constant *OC =
2556 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2557 Scale = ConstantExpr::getMul(OC, Scale);
2558 // Emit an add instruction.
2559 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2560 continue;
2561 }
2562 // Convert to correct type.
2563 if (Op->getType() != IntPtrTy)
2564 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2565 if (Size != 1) {
2566 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2567 // We'll let instcombine(mul) convert this to a shl if possible.
2568 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2569 }
2570
2571 // Emit an add instruction.
2572 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2573 }
2574 return Result;
2575}
2576
2577
2578/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2579/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2580/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2581/// be complex, and scales are involved. The above expression would also be
2582/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2583/// This later form is less amenable to optimization though, and we are allowed
2584/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2585///
2586/// If we can't emit an optimized form for this expression, this returns null.
2587///
2588static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2589 InstCombiner &IC) {
2590 TargetData &TD = *IC.getTargetData();
2591 gep_type_iterator GTI = gep_type_begin(GEP);
2592
2593 // Check to see if this gep only has a single variable index. If so, and if
2594 // any constant indices are a multiple of its scale, then we can compute this
2595 // in terms of the scale of the variable index. For example, if the GEP
2596 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2597 // because the expression will cross zero at the same point.
2598 unsigned i, e = GEP->getNumOperands();
2599 int64_t Offset = 0;
2600 for (i = 1; i != e; ++i, ++GTI) {
2601 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2602 // Compute the aggregate offset of constant indices.
2603 if (CI->isZero()) continue;
2604
2605 // Handle a struct index, which adds its field offset to the pointer.
2606 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2607 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2608 } else {
2609 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2610 Offset += Size*CI->getSExtValue();
2611 }
2612 } else {
2613 // Found our variable index.
2614 break;
2615 }
2616 }
2617
2618 // If there are no variable indices, we must have a constant offset, just
2619 // evaluate it the general way.
2620 if (i == e) return 0;
2621
2622 Value *VariableIdx = GEP->getOperand(i);
2623 // Determine the scale factor of the variable element. For example, this is
2624 // 4 if the variable index is into an array of i32.
2625 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2626
2627 // Verify that there are no other variable indices. If so, emit the hard way.
2628 for (++i, ++GTI; i != e; ++i, ++GTI) {
2629 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2630 if (!CI) return 0;
2631
2632 // Compute the aggregate offset of constant indices.
2633 if (CI->isZero()) continue;
2634
2635 // Handle a struct index, which adds its field offset to the pointer.
2636 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2637 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2638 } else {
2639 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2640 Offset += Size*CI->getSExtValue();
2641 }
2642 }
2643
2644 // Okay, we know we have a single variable index, which must be a
2645 // pointer/array/vector index. If there is no offset, life is simple, return
2646 // the index.
2647 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2648 if (Offset == 0) {
2649 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2650 // we don't need to bother extending: the extension won't affect where the
2651 // computation crosses zero.
2652 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2653 VariableIdx = new TruncInst(VariableIdx,
2654 TD.getIntPtrType(VariableIdx->getContext()),
2655 VariableIdx->getName(), &I);
2656 return VariableIdx;
2657 }
2658
2659 // Otherwise, there is an index. The computation we will do will be modulo
2660 // the pointer size, so get it.
2661 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2662
2663 Offset &= PtrSizeMask;
2664 VariableScale &= PtrSizeMask;
2665
2666 // To do this transformation, any constant index must be a multiple of the
2667 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2668 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2669 // multiple of the variable scale.
2670 int64_t NewOffs = Offset / (int64_t)VariableScale;
2671 if (Offset != NewOffs*(int64_t)VariableScale)
2672 return 0;
2673
2674 // Okay, we can do this evaluation. Start by converting the index to intptr.
2675 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2676 if (VariableIdx->getType() != IntPtrTy)
2677 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2678 true /*SExt*/,
2679 VariableIdx->getName(), &I);
2680 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2681 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2682}
2683
2684
2685/// Optimize pointer differences into the same array into a size. Consider:
2686/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2687/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2688///
2689Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2690 const Type *Ty) {
2691 assert(TD && "Must have target data info for this");
2692
2693 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2694 // this.
2695 bool Swapped;
2696 GetElementPtrInst *GEP;
2697
2698 if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2699 GEP->getOperand(0) == RHS)
2700 Swapped = false;
2701 else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2702 GEP->getOperand(0) == LHS)
2703 Swapped = true;
2704 else
2705 return 0;
2706
2707 // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2708
2709 // Emit the offset of the GEP and an intptr_t.
2710 Value *Result = EmitGEPOffset(GEP, *this);
2711
2712 // If we have p - gep(p, ...) then we have to negate the result.
2713 if (Swapped)
2714 Result = Builder->CreateNeg(Result, "diff.neg");
2715
2716 return Builder->CreateIntCast(Result, Ty, true);
2717}
2718
2719
Chris Lattner7e708292002-06-25 16:13:24 +00002720Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002721 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002722
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002723 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002724 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002725
Chris Lattner092543c2009-11-04 08:05:20 +00002726 // If this is a 'B = x-(-A)', change to B = x+A.
Dan Gohman186a6362009-08-12 16:04:34 +00002727 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002728 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002729
Chris Lattnere87597f2004-10-16 18:11:37 +00002730 if (isa<UndefValue>(Op0))
2731 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2732 if (isa<UndefValue>(Op1))
2733 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner092543c2009-11-04 08:05:20 +00002734 if (I.getType() == Type::getInt1Ty(*Context))
2735 return BinaryOperator::CreateXor(Op0, Op1);
2736
Chris Lattnerd65460f2003-11-05 01:06:05 +00002737 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00002738 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00002739 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002740 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002741
Chris Lattnerd65460f2003-11-05 01:06:05 +00002742 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002743 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002744 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002745 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002746
Chris Lattner76b7a062007-01-15 07:02:54 +00002747 // -(X >>u 31) -> (X >>s 31)
2748 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002749 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002750 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002751 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002752 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002753 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002754 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002755 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002756 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002757 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002758 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002759 }
2760 }
Chris Lattner092543c2009-11-04 08:05:20 +00002761 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002762 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2763 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002764 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002765 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002766 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002767 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002768 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002769 }
2770 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002771 }
2772 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002773 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002774
2775 // Try to fold constant sub into select arguments.
2776 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002777 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002778 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002779
2780 // C - zext(bool) -> bool ? C - 1 : C
2781 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002782 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002783 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002784 }
2785
Chris Lattner43d84d62005-04-07 16:15:25 +00002786 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002787 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002788 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002789 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002790 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002791 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002792 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002793 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002794 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2795 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2796 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002797 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002798 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002799 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002800 }
2801
Chris Lattnerfd059242003-10-15 16:48:29 +00002802 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002803 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2804 // is not used by anyone else...
2805 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002806 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002807 // Swap the two operands of the subexpr...
2808 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2809 Op1I->setOperand(0, IIOp1);
2810 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002811
Chris Lattnera2881962003-02-18 19:28:33 +00002812 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002813 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002814 }
2815
2816 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2817 //
2818 if (Op1I->getOpcode() == Instruction::And &&
2819 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2820 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2821
Chris Lattner74381062009-08-30 07:44:24 +00002822 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002823 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002824 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002825
Reid Spencerac5209e2006-10-16 23:08:08 +00002826 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002827 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002828 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002829 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002830 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002831 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002832 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002833
Chris Lattnerad3448c2003-02-18 19:57:07 +00002834 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002835 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002836 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002837 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002838 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002839 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002840 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002841 }
Chris Lattner40371712002-05-09 01:29:19 +00002842 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002843 }
Chris Lattnera2881962003-02-18 19:28:33 +00002844
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002845 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2846 if (Op0I->getOpcode() == Instruction::Add) {
2847 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2848 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2849 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2850 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2851 } else if (Op0I->getOpcode() == Instruction::Sub) {
2852 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002853 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002854 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002855 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002856 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002857
Chris Lattner50af16a2004-11-13 19:50:12 +00002858 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002859 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002860 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002861 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002862
Chris Lattner50af16a2004-11-13 19:50:12 +00002863 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002864 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002865 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002866 }
Chris Lattner092543c2009-11-04 08:05:20 +00002867
2868 // Optimize pointer differences into the same array into a size. Consider:
2869 // &A[10] - &A[0]: we should compile this to "10".
2870 if (TD) {
2871 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2872 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2873 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2874 RHS->getOperand(0),
2875 I.getType()))
2876 return ReplaceInstUsesWith(I, Res);
2877
2878 // trunc(p)-trunc(q) -> trunc(p-q)
2879 if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2880 if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2881 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2882 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2883 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2884 RHS->getOperand(0),
2885 I.getType()))
2886 return ReplaceInstUsesWith(I, Res);
2887 }
2888
Chris Lattner3f5b8772002-05-06 16:14:14 +00002889 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002890}
2891
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002892Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2893 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2894
2895 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002896 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002897 return BinaryOperator::CreateFAdd(Op0, V);
2898
2899 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2900 if (Op1I->getOpcode() == Instruction::FAdd) {
2901 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002902 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002903 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002904 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002905 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002906 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002907 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002908 }
2909
2910 return 0;
2911}
2912
Chris Lattnera0141b92007-07-15 20:42:37 +00002913/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2914/// comparison only checks the sign bit. If it only checks the sign bit, set
2915/// TrueIfSigned if the result of the comparison is true when the input value is
2916/// signed.
2917static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2918 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002919 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002920 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2921 TrueIfSigned = true;
2922 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002923 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2924 TrueIfSigned = true;
2925 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002926 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2927 TrueIfSigned = false;
2928 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002929 case ICmpInst::ICMP_UGT:
2930 // True if LHS u> RHS and RHS == high-bit-mask - 1
2931 TrueIfSigned = true;
2932 return RHS->getValue() ==
2933 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2934 case ICmpInst::ICMP_UGE:
2935 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2936 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002937 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002938 default:
2939 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002940 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002941}
2942
Chris Lattner7e708292002-06-25 16:13:24 +00002943Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002944 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002945 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002946
Chris Lattnera2498472009-10-11 21:36:10 +00002947 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002948 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002949
Chris Lattner8af304a2009-10-11 07:53:15 +00002950 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002951 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2952 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002953
2954 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002955 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002956 if (SI->getOpcode() == Instruction::Shl)
2957 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002958 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002959 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002960
Zhou Sheng843f07672007-04-19 05:39:12 +00002961 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002962 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002963 if (CI->equalsInt(1)) // X * 1 == X
2964 return ReplaceInstUsesWith(I, Op0);
2965 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002966 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002967
Zhou Sheng97b52c22007-03-29 01:57:21 +00002968 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002969 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002970 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002971 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002972 }
Chris Lattnera2498472009-10-11 21:36:10 +00002973 } else if (isa<VectorType>(Op1C->getType())) {
2974 if (Op1C->isNullValue())
2975 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002976
Chris Lattnera2498472009-10-11 21:36:10 +00002977 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002978 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002979 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002980
2981 // As above, vector X*splat(1.0) -> X in all defined cases.
2982 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002983 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2984 if (CI->equalsInt(1))
2985 return ReplaceInstUsesWith(I, Op0);
2986 }
2987 }
Chris Lattnera2881962003-02-18 19:28:33 +00002988 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002989
2990 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2991 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002992 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002993 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00002994 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2995 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002996 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002997
2998 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002999
3000 // Try to fold constant mul into select arguments.
3001 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003002 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003003 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003004
3005 if (isa<PHINode>(Op0))
3006 if (Instruction *NV = FoldOpIntoPhi(I))
3007 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003008 }
3009
Dan Gohman186a6362009-08-12 16:04:34 +00003010 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003011 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003012 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003013
Nick Lewycky0c730792008-11-21 07:33:58 +00003014 // (X / Y) * Y = X - (X % Y)
3015 // (X / Y) * -Y = (X % Y) - X
3016 {
Chris Lattnera2498472009-10-11 21:36:10 +00003017 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00003018 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3019 if (!BO ||
3020 (BO->getOpcode() != Instruction::UDiv &&
3021 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00003022 Op1C = Op0;
3023 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00003024 }
Chris Lattnera2498472009-10-11 21:36:10 +00003025 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00003026 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003027 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00003028 (BO->getOpcode() == Instruction::UDiv ||
3029 BO->getOpcode() == Instruction::SDiv)) {
3030 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3031
Dan Gohmanfa94b942009-08-12 16:33:09 +00003032 // If the division is exact, X % Y is zero.
3033 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3034 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00003035 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00003036 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00003037 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00003038 }
3039
Chris Lattner74381062009-08-30 07:44:24 +00003040 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00003041 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00003042 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003043 else
Chris Lattner74381062009-08-30 07:44:24 +00003044 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003045 Rem->takeName(BO);
3046
Chris Lattnera2498472009-10-11 21:36:10 +00003047 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00003048 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00003049 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003050 }
3051 }
3052
Chris Lattner8af304a2009-10-11 07:53:15 +00003053 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00003054 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00003055 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003056
Chris Lattner8af304a2009-10-11 07:53:15 +00003057 // X*(1 << Y) --> X << Y
3058 // (1 << Y)*X --> X << Y
3059 {
3060 Value *Y;
3061 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00003062 return BinaryOperator::CreateShl(Op1, Y);
3063 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00003064 return BinaryOperator::CreateShl(Op0, Y);
3065 }
3066
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003067 // If one of the operands of the multiply is a cast from a boolean value, then
3068 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00003069 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3070 if (!isa<VectorType>(I.getType())) {
3071 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00003072 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00003073
Chris Lattnerd2c58362009-10-11 21:29:45 +00003074 Value *BoolCast = 0, *OtherOp = 0;
3075 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00003076 BoolCast = Op0, OtherOp = Op1;
3077 else if (MaskedValueIsZero(Op1, Negative2))
3078 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00003079
Chris Lattner0036e3a2009-10-11 21:22:21 +00003080 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00003081 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3082 BoolCast, "tmp");
3083 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003084 }
3085 }
3086
Chris Lattner7e708292002-06-25 16:13:24 +00003087 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003088}
3089
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003090Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3091 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003092 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003093
3094 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00003095 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3096 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003097 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3098 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3099 if (Op1F->isExactlyValue(1.0))
3100 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00003101 } else if (isa<VectorType>(Op1C->getType())) {
3102 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003103 // As above, vector X*splat(1.0) -> X in all defined cases.
3104 if (Constant *Splat = Op1V->getSplatValue()) {
3105 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3106 if (F->isExactlyValue(1.0))
3107 return ReplaceInstUsesWith(I, Op0);
3108 }
3109 }
3110 }
3111
3112 // Try to fold constant mul into select arguments.
3113 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3114 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3115 return R;
3116
3117 if (isa<PHINode>(Op0))
3118 if (Instruction *NV = FoldOpIntoPhi(I))
3119 return NV;
3120 }
3121
Dan Gohman186a6362009-08-12 16:04:34 +00003122 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003123 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003124 return BinaryOperator::CreateFMul(Op0v, Op1v);
3125
3126 return Changed ? &I : 0;
3127}
3128
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003129/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3130/// instruction.
3131bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3132 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3133
3134 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3135 int NonNullOperand = -1;
3136 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3137 if (ST->isNullValue())
3138 NonNullOperand = 2;
3139 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3140 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3141 if (ST->isNullValue())
3142 NonNullOperand = 1;
3143
3144 if (NonNullOperand == -1)
3145 return false;
3146
3147 Value *SelectCond = SI->getOperand(0);
3148
3149 // Change the div/rem to use 'Y' instead of the select.
3150 I.setOperand(1, SI->getOperand(NonNullOperand));
3151
3152 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3153 // problem. However, the select, or the condition of the select may have
3154 // multiple uses. Based on our knowledge that the operand must be non-zero,
3155 // propagate the known value for the select into other uses of it, and
3156 // propagate a known value of the condition into its other users.
3157
3158 // If the select and condition only have a single use, don't bother with this,
3159 // early exit.
3160 if (SI->use_empty() && SelectCond->hasOneUse())
3161 return true;
3162
3163 // Scan the current block backward, looking for other uses of SI.
3164 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3165
3166 while (BBI != BBFront) {
3167 --BBI;
3168 // If we found a call to a function, we can't assume it will return, so
3169 // information from below it cannot be propagated above it.
3170 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3171 break;
3172
3173 // Replace uses of the select or its condition with the known values.
3174 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3175 I != E; ++I) {
3176 if (*I == SI) {
3177 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003178 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003179 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00003180 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3181 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003182 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003183 }
3184 }
3185
3186 // If we past the instruction, quit looking for it.
3187 if (&*BBI == SI)
3188 SI = 0;
3189 if (&*BBI == SelectCond)
3190 SelectCond = 0;
3191
3192 // If we ran out of things to eliminate, break out of the loop.
3193 if (SelectCond == 0 && SI == 0)
3194 break;
3195
3196 }
3197 return true;
3198}
3199
3200
Reid Spencer1628cec2006-10-26 06:15:43 +00003201/// This function implements the transforms on div instructions that work
3202/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3203/// used by the visitors to those instructions.
3204/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003205Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003206 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003207
Chris Lattner50b2ca42008-02-19 06:12:18 +00003208 // undef / X -> 0 for integer.
3209 // undef / X -> undef for FP (the undef could be a snan).
3210 if (isa<UndefValue>(Op0)) {
3211 if (Op0->getType()->isFPOrFPVector())
3212 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00003213 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003214 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003215
3216 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003217 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003218 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003219
Reid Spencer1628cec2006-10-26 06:15:43 +00003220 return 0;
3221}
Misha Brukmanfd939082005-04-21 23:48:37 +00003222
Reid Spencer1628cec2006-10-26 06:15:43 +00003223/// This function implements the transforms common to both integer division
3224/// instructions (udiv and sdiv). It is called by the visitors to those integer
3225/// division instructions.
3226/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003227Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003228 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3229
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003230 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003231 if (Op0 == Op1) {
3232 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003233 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003234 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003235 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003236 }
3237
Owen Andersoneed707b2009-07-24 23:12:02 +00003238 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003239 return ReplaceInstUsesWith(I, CI);
3240 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003241
Reid Spencer1628cec2006-10-26 06:15:43 +00003242 if (Instruction *Common = commonDivTransforms(I))
3243 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003244
3245 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3246 // This does not apply for fdiv.
3247 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3248 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003249
3250 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3251 // div X, 1 == X
3252 if (RHS->equalsInt(1))
3253 return ReplaceInstUsesWith(I, Op0);
3254
3255 // (X / C1) / C2 -> X / (C1*C2)
3256 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3257 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3258 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003259 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003260 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003261 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003262 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003263 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003264 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003265 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003266
Reid Spencerbca0e382007-03-23 20:05:17 +00003267 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003268 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3269 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3270 return R;
3271 if (isa<PHINode>(Op0))
3272 if (Instruction *NV = FoldOpIntoPhi(I))
3273 return NV;
3274 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003275 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003276
Chris Lattnera2881962003-02-18 19:28:33 +00003277 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003278 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003279 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003280 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003281
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003282 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003283 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003284 return ReplaceInstUsesWith(I, Op0);
3285
Nick Lewycky895f0852008-11-27 20:21:08 +00003286 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3287 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3288 // div X, 1 == X
3289 if (X->isOne())
3290 return ReplaceInstUsesWith(I, Op0);
3291 }
3292
Reid Spencer1628cec2006-10-26 06:15:43 +00003293 return 0;
3294}
3295
3296Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3297 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3298
3299 // Handle the integer div common cases
3300 if (Instruction *Common = commonIDivTransforms(I))
3301 return Common;
3302
Reid Spencer1628cec2006-10-26 06:15:43 +00003303 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003304 // X udiv C^2 -> X >> C
3305 // Check to see if this is an unsigned division with an exact power of 2,
3306 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003307 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003308 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003309 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003310
3311 // X udiv C, where C >= signbit
3312 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003313 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003314 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003315 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003316 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003317 }
3318
3319 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003320 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003321 if (RHSI->getOpcode() == Instruction::Shl &&
3322 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003323 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003324 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003325 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003326 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003327 if (uint32_t C2 = C1.logBase2())
3328 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003329 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003330 }
3331 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003332 }
3333
Reid Spencer1628cec2006-10-26 06:15:43 +00003334 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3335 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003336 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003337 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003338 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003339 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003340 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003341 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003342 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003343 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003344 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003345 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003346
3347 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003348 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003349 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003350
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003351 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003352 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003353 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003354 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003355 return 0;
3356}
3357
Reid Spencer1628cec2006-10-26 06:15:43 +00003358Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3359 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3360
3361 // Handle the integer div common cases
3362 if (Instruction *Common = commonIDivTransforms(I))
3363 return Common;
3364
3365 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3366 // sdiv X, -1 == -X
3367 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003368 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003369
Dan Gohmanfa94b942009-08-12 16:33:09 +00003370 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003371 if (cast<SDivOperator>(&I)->isExact() &&
3372 RHS->getValue().isNonNegative() &&
3373 RHS->getValue().isPowerOf2()) {
3374 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3375 RHS->getValue().exactLogBase2());
3376 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3377 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003378
3379 // -X/C --> X/-C provided the negation doesn't overflow.
3380 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3381 if (isa<Constant>(Sub->getOperand(0)) &&
3382 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003383 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003384 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3385 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003386 }
3387
3388 // If the sign bits of both operands are zero (i.e. we can prove they are
3389 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003390 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003391 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003392 if (MaskedValueIsZero(Op0, Mask)) {
3393 if (MaskedValueIsZero(Op1, Mask)) {
3394 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3395 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3396 }
3397 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003398 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003399 ShiftedInt->getValue().isPowerOf2()) {
3400 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3401 // Safe because the only negative value (1 << Y) can take on is
3402 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3403 // the sign bit set.
3404 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3405 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003406 }
Eli Friedman8be17392009-07-18 09:53:21 +00003407 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003408
3409 return 0;
3410}
3411
3412Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3413 return commonDivTransforms(I);
3414}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003415
Reid Spencer0a783f72006-11-02 01:53:59 +00003416/// This function implements the transforms on rem instructions that work
3417/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3418/// is used by the visitors to those instructions.
3419/// @brief Transforms common to all three rem instructions
3420Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003421 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003422
Chris Lattner50b2ca42008-02-19 06:12:18 +00003423 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3424 if (I.getType()->isFPOrFPVector())
3425 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003426 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003427 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003428 if (isa<UndefValue>(Op1))
3429 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003430
3431 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003432 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3433 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003434
Reid Spencer0a783f72006-11-02 01:53:59 +00003435 return 0;
3436}
3437
3438/// This function implements the transforms common to both integer remainder
3439/// instructions (urem and srem). It is called by the visitors to those integer
3440/// remainder instructions.
3441/// @brief Common integer remainder transforms
3442Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3443 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3444
3445 if (Instruction *common = commonRemTransforms(I))
3446 return common;
3447
Dale Johannesened6af242009-01-21 00:35:19 +00003448 // 0 % X == 0 for integer, we don't need to preserve faults!
3449 if (Constant *LHS = dyn_cast<Constant>(Op0))
3450 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003451 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003452
Chris Lattner857e8cd2004-12-12 21:48:58 +00003453 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003454 // X % 0 == undef, we don't need to preserve faults!
3455 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003456 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003457
Chris Lattnera2881962003-02-18 19:28:33 +00003458 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003459 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003460
Chris Lattner97943922006-02-28 05:49:21 +00003461 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3462 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3463 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3464 return R;
3465 } else if (isa<PHINode>(Op0I)) {
3466 if (Instruction *NV = FoldOpIntoPhi(I))
3467 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003468 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003469
3470 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003471 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003472 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003473 }
Chris Lattnera2881962003-02-18 19:28:33 +00003474 }
3475
Reid Spencer0a783f72006-11-02 01:53:59 +00003476 return 0;
3477}
3478
3479Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3480 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3481
3482 if (Instruction *common = commonIRemTransforms(I))
3483 return common;
3484
3485 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3486 // X urem C^2 -> X and C
3487 // Check to see if this is an unsigned remainder with an exact power of 2,
3488 // if so, convert to a bitwise and.
3489 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003490 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003491 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003492 }
3493
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003494 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003495 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3496 if (RHSI->getOpcode() == Instruction::Shl &&
3497 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003498 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003499 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003500 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003501 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003502 }
3503 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003504 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003505
Reid Spencer0a783f72006-11-02 01:53:59 +00003506 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3507 // where C1&C2 are powers of two.
3508 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3509 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3510 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3511 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003512 if ((STO->getValue().isPowerOf2()) &&
3513 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003514 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3515 SI->getName()+".t");
3516 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3517 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003518 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003519 }
3520 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003521 }
3522
Chris Lattner3f5b8772002-05-06 16:14:14 +00003523 return 0;
3524}
3525
Reid Spencer0a783f72006-11-02 01:53:59 +00003526Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3527 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3528
Dan Gohmancff55092007-11-05 23:16:33 +00003529 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003530 if (Instruction *Common = commonIRemTransforms(I))
3531 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003532
Dan Gohman186a6362009-08-12 16:04:34 +00003533 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003534 if (!isa<Constant>(RHSNeg) ||
3535 (isa<ConstantInt>(RHSNeg) &&
3536 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003537 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003538 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003539 I.setOperand(1, RHSNeg);
3540 return &I;
3541 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003542
Dan Gohmancff55092007-11-05 23:16:33 +00003543 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003544 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003545 if (I.getType()->isInteger()) {
3546 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3547 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3548 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003549 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003550 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003551 }
3552
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003553 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003554 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3555 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003556
Nick Lewycky9dce8732008-12-20 16:48:00 +00003557 bool hasNegative = false;
3558 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3559 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3560 if (RHS->getValue().isNegative())
3561 hasNegative = true;
3562
3563 if (hasNegative) {
3564 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003565 for (unsigned i = 0; i != VWidth; ++i) {
3566 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3567 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003568 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003569 else
3570 Elts[i] = RHS;
3571 }
3572 }
3573
Owen Andersonaf7ec972009-07-28 21:19:26 +00003574 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003575 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003576 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003577 I.setOperand(1, NewRHSV);
3578 return &I;
3579 }
3580 }
3581 }
3582
Reid Spencer0a783f72006-11-02 01:53:59 +00003583 return 0;
3584}
3585
3586Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003587 return commonRemTransforms(I);
3588}
3589
Chris Lattner457dd822004-06-09 07:59:58 +00003590// isOneBitSet - Return true if there is exactly one bit set in the specified
3591// constant.
3592static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003593 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003594}
3595
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003596// isHighOnes - Return true if the constant is of the form 1+0+.
3597// This is the same as lowones(~X).
3598static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003599 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003600}
3601
Reid Spencere4d87aa2006-12-23 06:05:41 +00003602/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003603/// are carefully arranged to allow folding of expressions such as:
3604///
3605/// (A < B) | (A > B) --> (A != B)
3606///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003607/// Note that this is only valid if the first and second predicates have the
3608/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003609///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003610/// Three bits are used to represent the condition, as follows:
3611/// 0 A > B
3612/// 1 A == B
3613/// 2 A < B
3614///
3615/// <=> Value Definition
3616/// 000 0 Always false
3617/// 001 1 A > B
3618/// 010 2 A == B
3619/// 011 3 A >= B
3620/// 100 4 A < B
3621/// 101 5 A != B
3622/// 110 6 A <= B
3623/// 111 7 Always true
3624///
3625static unsigned getICmpCode(const ICmpInst *ICI) {
3626 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003627 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003628 case ICmpInst::ICMP_UGT: return 1; // 001
3629 case ICmpInst::ICMP_SGT: return 1; // 001
3630 case ICmpInst::ICMP_EQ: return 2; // 010
3631 case ICmpInst::ICMP_UGE: return 3; // 011
3632 case ICmpInst::ICMP_SGE: return 3; // 011
3633 case ICmpInst::ICMP_ULT: return 4; // 100
3634 case ICmpInst::ICMP_SLT: return 4; // 100
3635 case ICmpInst::ICMP_NE: return 5; // 101
3636 case ICmpInst::ICMP_ULE: return 6; // 110
3637 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003638 // True -> 7
3639 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003640 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003641 return 0;
3642 }
3643}
3644
Evan Cheng8db90722008-10-14 17:15:11 +00003645/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3646/// predicate into a three bit mask. It also returns whether it is an ordered
3647/// predicate by reference.
3648static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3649 isOrdered = false;
3650 switch (CC) {
3651 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3652 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003653 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3654 case FCmpInst::FCMP_UGT: return 1; // 001
3655 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3656 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003657 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3658 case FCmpInst::FCMP_UGE: return 3; // 011
3659 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3660 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003661 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3662 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003663 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3664 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003665 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003666 default:
3667 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003668 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003669 return 0;
3670 }
3671}
3672
Reid Spencere4d87aa2006-12-23 06:05:41 +00003673/// getICmpValue - This is the complement of getICmpCode, which turns an
3674/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003675/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003676/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003677static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003678 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003679 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003680 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003681 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003682 case 1:
3683 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003684 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003685 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003686 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3687 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003688 case 3:
3689 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003690 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003691 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003692 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003693 case 4:
3694 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003695 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003696 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003697 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3698 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003699 case 6:
3700 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003701 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003702 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003703 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003704 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003705 }
3706}
3707
Evan Cheng8db90722008-10-14 17:15:11 +00003708/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3709/// opcode and two operands into either a FCmp instruction. isordered is passed
3710/// in to determine which kind of predicate to use in the new fcmp instruction.
3711static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003712 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003713 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003714 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003715 case 0:
3716 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003717 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003718 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003719 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003720 case 1:
3721 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003722 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003723 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003724 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003725 case 2:
3726 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003727 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003728 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003729 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003730 case 3:
3731 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003732 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003733 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003734 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003735 case 4:
3736 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003737 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003738 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003739 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003740 case 5:
3741 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003742 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003743 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003744 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003745 case 6:
3746 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003747 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003748 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003749 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003750 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003751 }
3752}
3753
Chris Lattnerb9553d62008-11-16 04:55:20 +00003754/// PredicatesFoldable - Return true if both predicates match sign or if at
3755/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003756static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003757 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3758 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3759 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003760}
3761
3762namespace {
3763// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3764struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003765 InstCombiner &IC;
3766 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003767 ICmpInst::Predicate pred;
3768 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3769 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3770 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003771 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003772 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3773 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003774 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3775 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003776 return false;
3777 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003778 Instruction *apply(Instruction &Log) const {
3779 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3780 if (ICI->getOperand(0) != LHS) {
3781 assert(ICI->getOperand(1) == LHS);
3782 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003783 }
3784
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003785 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003786 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003787 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003788 unsigned Code;
3789 switch (Log.getOpcode()) {
3790 case Instruction::And: Code = LHSCode & RHSCode; break;
3791 case Instruction::Or: Code = LHSCode | RHSCode; break;
3792 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003793 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003794 }
3795
Nick Lewycky4a134af2009-10-25 05:20:17 +00003796 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003797 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003798 if (Instruction *I = dyn_cast<Instruction>(RV))
3799 return I;
3800 // Otherwise, it's a constant boolean value...
3801 return IC.ReplaceInstUsesWith(Log, RV);
3802 }
3803};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003804} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003805
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003806// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3807// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003808// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003809Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003810 ConstantInt *OpRHS,
3811 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003812 BinaryOperator &TheAnd) {
3813 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003814 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003815 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003816 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003817
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003818 switch (Op->getOpcode()) {
3819 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003820 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003821 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003822 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003823 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003824 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003825 }
3826 break;
3827 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003828 if (Together == AndRHS) // (X | C) & C --> C
3829 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003830
Chris Lattner6e7ba452005-01-01 16:22:27 +00003831 if (Op->hasOneUse() && Together != OpRHS) {
3832 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003833 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003834 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003835 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003836 }
3837 break;
3838 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003839 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003840 // Adding a one to a single bit bit-field should be turned into an XOR
3841 // of the bit. First thing to check is to see if this AND is with a
3842 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003843 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003844
3845 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003846 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003847 // Ok, at this point, we know that we are masking the result of the
3848 // ADD down to exactly one bit. If the constant we are adding has
3849 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003850 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003851
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003852 // Check to see if any bits below the one bit set in AndRHSV are set.
3853 if ((AddRHS & (AndRHSV-1)) == 0) {
3854 // If not, the only thing that can effect the output of the AND is
3855 // the bit specified by AndRHSV. If that bit is set, the effect of
3856 // the XOR is to toggle the bit. If it is clear, then the ADD has
3857 // no effect.
3858 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3859 TheAnd.setOperand(0, X);
3860 return &TheAnd;
3861 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003862 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003863 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003864 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003865 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003866 }
3867 }
3868 }
3869 }
3870 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003871
3872 case Instruction::Shl: {
3873 // We know that the AND will not produce any of the bits shifted in, so if
3874 // the anded constant includes them, clear them now!
3875 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003876 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003877 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003878 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003879 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003880
Zhou Sheng290bec52007-03-29 08:15:12 +00003881 if (CI->getValue() == ShlMask) {
3882 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003883 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3884 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003885 TheAnd.setOperand(1, CI);
3886 return &TheAnd;
3887 }
3888 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003889 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003890 case Instruction::LShr:
3891 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003892 // We know that the AND will not produce any of the bits shifted in, so if
3893 // the anded constant includes them, clear them now! This only applies to
3894 // unsigned shifts, because a signed shr may bring in set bits!
3895 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003896 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003897 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003898 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003899 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003900
Zhou Sheng290bec52007-03-29 08:15:12 +00003901 if (CI->getValue() == ShrMask) {
3902 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003903 return ReplaceInstUsesWith(TheAnd, Op);
3904 } else if (CI != AndRHS) {
3905 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3906 return &TheAnd;
3907 }
3908 break;
3909 }
3910 case Instruction::AShr:
3911 // Signed shr.
3912 // See if this is shifting in some sign extension, then masking it out
3913 // with an and.
3914 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003915 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003916 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003917 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003918 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003919 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003920 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003921 // Make the argument unsigned.
3922 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003923 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003924 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003925 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003926 }
3927 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003928 }
3929 return 0;
3930}
3931
Chris Lattner8b170942002-08-09 23:47:40 +00003932
Chris Lattnera96879a2004-09-29 17:40:11 +00003933/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3934/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003935/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3936/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003937/// insert new instructions.
3938Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003939 bool isSigned, bool Inside,
3940 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003941 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003942 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003943 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003944
Chris Lattnera96879a2004-09-29 17:40:11 +00003945 if (Inside) {
3946 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003947 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003948
Reid Spencere4d87aa2006-12-23 06:05:41 +00003949 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003950 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003951 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003952 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003953 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003954 }
3955
3956 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003957 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003958 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003959 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003960 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003961 }
3962
3963 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003964 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003965
Reid Spencere4e40032007-03-21 23:19:50 +00003966 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003967 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003968 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003969 ICmpInst::Predicate pred = (isSigned ?
3970 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003971 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003972 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003973
Reid Spencere4e40032007-03-21 23:19:50 +00003974 // Emit V-Lo >u Hi-1-Lo
3975 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003976 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003977 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003978 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003979 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003980}
3981
Chris Lattner7203e152005-09-18 07:22:02 +00003982// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3983// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3984// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3985// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003986static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003987 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003988 uint32_t BitWidth = Val->getType()->getBitWidth();
3989 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003990
3991 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003992 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003993 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003994 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003995 return true;
3996}
3997
Chris Lattner7203e152005-09-18 07:22:02 +00003998/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3999/// where isSub determines whether the operator is a sub. If we can fold one of
4000/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00004001///
4002/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4003/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4004/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4005///
4006/// return (A +/- B).
4007///
4008Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004009 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00004010 Instruction &I) {
4011 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4012 if (!LHSI || LHSI->getNumOperands() != 2 ||
4013 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4014
4015 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4016
4017 switch (LHSI->getOpcode()) {
4018 default: return 0;
4019 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00004020 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004021 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004022 if ((Mask->getValue().countLeadingZeros() +
4023 Mask->getValue().countPopulation()) ==
4024 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004025 break;
4026
4027 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4028 // part, we don't need any explicit masks to take them out of A. If that
4029 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004030 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004031 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004032 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004033 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004034 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004035 break;
4036 }
4037 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004038 return 0;
4039 case Instruction::Or:
4040 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004041 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004042 if ((Mask->getValue().countLeadingZeros() +
4043 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00004044 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004045 break;
4046 return 0;
4047 }
4048
Chris Lattnerc8e77562005-09-18 04:24:45 +00004049 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00004050 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4051 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004052}
4053
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004054/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4055Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4056 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00004057 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004058 ConstantInt *LHSCst, *RHSCst;
4059 ICmpInst::Predicate LHSCC, RHSCC;
4060
Chris Lattnerea065fb2008-11-16 05:10:52 +00004061 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004062 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004063 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004064 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004065 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004066 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00004067
4068 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4069 // where C is a power of 2
4070 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
4071 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00004072 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004073 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00004074 }
4075
4076 // From here on, we only handle:
4077 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4078 if (Val != Val2) return 0;
4079
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004080 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4081 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4082 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4083 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4084 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4085 return 0;
4086
4087 // We can't fold (ugt x, C) & (sgt x, C2).
4088 if (!PredicatesFoldable(LHSCC, RHSCC))
4089 return 0;
4090
4091 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00004092 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004093 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004094 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004095 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00004096 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004097 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00004098 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4099
4100 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004101 std::swap(LHS, RHS);
4102 std::swap(LHSCst, RHSCst);
4103 std::swap(LHSCC, RHSCC);
4104 }
4105
4106 // At this point, we know we have have two icmp instructions
4107 // comparing a value against two constants and and'ing the result
4108 // together. Because of the above check, we know that we only have
4109 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4110 // (from the FoldICmpLogical check above), that the two constants
4111 // are not equal and that the larger constant is on the RHS
4112 assert(LHSCst != RHSCst && "Compares not folded above?");
4113
4114 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004115 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004116 case ICmpInst::ICMP_EQ:
4117 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004118 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004119 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4120 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4121 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004122 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004123 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4124 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4125 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4126 return ReplaceInstUsesWith(I, LHS);
4127 }
4128 case ICmpInst::ICMP_NE:
4129 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004130 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004131 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00004132 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004133 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004134 break; // (X != 13 & X u< 15) -> no change
4135 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00004136 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004137 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004138 break; // (X != 13 & X s< 15) -> no change
4139 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4140 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4141 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4142 return ReplaceInstUsesWith(I, RHS);
4143 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004144 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00004145 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004146 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004147 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00004148 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004149 }
4150 break; // (X != 13 & X != 15) -> no change
4151 }
4152 break;
4153 case ICmpInst::ICMP_ULT:
4154 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004155 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004156 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4157 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004158 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004159 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4160 break;
4161 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4162 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4163 return ReplaceInstUsesWith(I, LHS);
4164 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4165 break;
4166 }
4167 break;
4168 case ICmpInst::ICMP_SLT:
4169 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004170 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004171 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4172 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004173 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004174 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4175 break;
4176 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4177 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4178 return ReplaceInstUsesWith(I, LHS);
4179 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4180 break;
4181 }
4182 break;
4183 case ICmpInst::ICMP_UGT:
4184 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004185 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004186 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4187 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4188 return ReplaceInstUsesWith(I, RHS);
4189 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4190 break;
4191 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004192 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004193 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004194 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004195 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00004196 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004197 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004198 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4199 break;
4200 }
4201 break;
4202 case ICmpInst::ICMP_SGT:
4203 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004204 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004205 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4206 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4207 return ReplaceInstUsesWith(I, RHS);
4208 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4209 break;
4210 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004211 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004212 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004213 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004214 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00004215 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004216 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004217 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4218 break;
4219 }
4220 break;
4221 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004222
4223 return 0;
4224}
4225
Chris Lattner42d1be02009-07-23 05:14:02 +00004226Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4227 FCmpInst *RHS) {
4228
4229 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4230 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4231 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4232 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4233 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4234 // If either of the constants are nans, then the whole thing returns
4235 // false.
4236 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004237 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004238 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004239 LHS->getOperand(0), RHS->getOperand(0));
4240 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004241
4242 // Handle vector zeros. This occurs because the canonical form of
4243 // "fcmp ord x,x" is "fcmp ord x, 0".
4244 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4245 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004246 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004247 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004248 return 0;
4249 }
4250
4251 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4252 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4253 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4254
4255
4256 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4257 // Swap RHS operands to match LHS.
4258 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4259 std::swap(Op1LHS, Op1RHS);
4260 }
4261
4262 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4263 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4264 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004265 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004266
4267 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004268 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004269 if (Op0CC == FCmpInst::FCMP_TRUE)
4270 return ReplaceInstUsesWith(I, RHS);
4271 if (Op1CC == FCmpInst::FCMP_TRUE)
4272 return ReplaceInstUsesWith(I, LHS);
4273
4274 bool Op0Ordered;
4275 bool Op1Ordered;
4276 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4277 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4278 if (Op1Pred == 0) {
4279 std::swap(LHS, RHS);
4280 std::swap(Op0Pred, Op1Pred);
4281 std::swap(Op0Ordered, Op1Ordered);
4282 }
4283 if (Op0Pred == 0) {
4284 // uno && ueq -> uno && (uno || eq) -> ueq
4285 // ord && olt -> ord && (ord && lt) -> olt
4286 if (Op0Ordered == Op1Ordered)
4287 return ReplaceInstUsesWith(I, RHS);
4288
4289 // uno && oeq -> uno && (ord && eq) -> false
4290 // uno && ord -> false
4291 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004292 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004293 // ord && ueq -> ord && (uno || eq) -> oeq
4294 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4295 Op0LHS, Op0RHS, Context));
4296 }
4297 }
4298
4299 return 0;
4300}
4301
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004302
Chris Lattner7e708292002-06-25 16:13:24 +00004303Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004304 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004305 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004306
Chris Lattnere87597f2004-10-16 18:11:37 +00004307 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004308 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004309
Chris Lattner6e7ba452005-01-01 16:22:27 +00004310 // and X, X = X
4311 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004312 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004313
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004314 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004315 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004316 if (SimplifyDemandedInstructionBits(I))
4317 return &I;
4318 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004319 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004320 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004321 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004322 } else if (isa<ConstantAggregateZero>(Op1)) {
4323 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004324 }
4325 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004326
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004327 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004328 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004329 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004330
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004331 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004332 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004333 Value *Op0LHS = Op0I->getOperand(0);
4334 Value *Op0RHS = Op0I->getOperand(1);
4335 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004336 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004337 case Instruction::Xor:
4338 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004339 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004340 if (!Op0I->hasOneUse()) break;
4341
4342 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4343 // Not masking anything out for the LHS, move to RHS.
4344 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4345 Op0RHS->getName()+".masked");
4346 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4347 }
4348 if (!isa<Constant>(Op0RHS) &&
4349 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4350 // Not masking anything out for the RHS, move to LHS.
4351 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4352 Op0LHS->getName()+".masked");
4353 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004354 }
4355
Chris Lattner6e7ba452005-01-01 16:22:27 +00004356 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004357 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004358 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4359 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4360 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4361 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004362 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004363 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004364 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004365 break;
4366
4367 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004368 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4369 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4370 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4371 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004372 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004373
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004374 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4375 // has 1's for all bits that the subtraction with A might affect.
4376 if (Op0I->hasOneUse()) {
4377 uint32_t BitWidth = AndRHSMask.getBitWidth();
4378 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4379 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4380
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004381 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004382 if (!(A && A->isZero()) && // avoid infinite recursion.
4383 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004384 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004385 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4386 }
4387 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004388 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004389
4390 case Instruction::Shl:
4391 case Instruction::LShr:
4392 // (1 << x) & 1 --> zext(x == 0)
4393 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004394 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004395 Value *NewICmp =
4396 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004397 return new ZExtInst(NewICmp, I.getType());
4398 }
4399 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004400 }
4401
Chris Lattner58403262003-07-23 19:25:52 +00004402 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004403 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004404 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004405 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004406 // If this is an integer truncation or change from signed-to-unsigned, and
4407 // if the source is an and/or with immediate, transform it. This
4408 // frequently occurs for bitfield accesses.
4409 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004410 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004411 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004412 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004413 if (CastOp->getOpcode() == Instruction::And) {
4414 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004415 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4416 // This will fold the two constants together, which may allow
4417 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004418 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004419 CastOp->getOperand(0), I.getType(),
4420 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004421 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004422 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004423 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004424 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004425 } else if (CastOp->getOpcode() == Instruction::Or) {
4426 // Change: and (cast (or X, C1) to T), C2
4427 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004428 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004429 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004430 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004431 return ReplaceInstUsesWith(I, AndRHS);
4432 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004433 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004434 }
Chris Lattner06782f82003-07-23 19:36:21 +00004435 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004436
4437 // Try to fold constant and into select arguments.
4438 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004439 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004440 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004441 if (isa<PHINode>(Op0))
4442 if (Instruction *NV = FoldOpIntoPhi(I))
4443 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004444 }
4445
Dan Gohman186a6362009-08-12 16:04:34 +00004446 Value *Op0NotVal = dyn_castNotVal(Op0);
4447 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004448
Chris Lattner5b62aa72004-06-18 06:07:51 +00004449 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004450 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004451
Misha Brukmancb6267b2004-07-30 12:50:08 +00004452 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004453 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004454 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4455 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004456 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004457 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004458
4459 {
Chris Lattner003b6202007-06-15 05:58:24 +00004460 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004461 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004462 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4463 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004464
4465 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004466 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004467 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004468 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004469 }
4470 }
4471
Dan Gohman4ae51262009-08-12 16:23:25 +00004472 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004473 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4474 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004475
4476 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004477 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004478 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004479 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004480 }
4481 }
Chris Lattner64daab52006-04-01 08:03:55 +00004482
4483 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004484 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004485 if (A == Op1) { // (A^B)&A -> A&(A^B)
4486 I.swapOperands(); // Simplify below
4487 std::swap(Op0, Op1);
4488 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4489 cast<BinaryOperator>(Op0)->swapOperands();
4490 I.swapOperands(); // Simplify below
4491 std::swap(Op0, Op1);
4492 }
4493 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004494
Chris Lattner64daab52006-04-01 08:03:55 +00004495 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004496 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004497 if (B == Op0) { // B&(A^B) -> B&(B^A)
4498 cast<BinaryOperator>(Op1)->swapOperands();
4499 std::swap(A, B);
4500 }
Chris Lattner74381062009-08-30 07:44:24 +00004501 if (A == Op0) // A&(A^B) -> A & ~B
4502 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004503 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004504
4505 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004506 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4507 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004508 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004509 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4510 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004511 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004512 }
4513
Reid Spencere4d87aa2006-12-23 06:05:41 +00004514 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4515 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004516 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004517 return R;
4518
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004519 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4520 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4521 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004522 }
4523
Chris Lattner6fc205f2006-05-05 06:39:07 +00004524 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004525 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4526 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4527 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4528 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004529 if (SrcTy == Op1C->getOperand(0)->getType() &&
4530 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004531 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004532 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4533 I.getType(), TD) &&
4534 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4535 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004536 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4537 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004538 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004539 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004540 }
Chris Lattnere511b742006-11-14 07:46:50 +00004541
4542 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004543 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4544 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4545 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004546 SI0->getOperand(1) == SI1->getOperand(1) &&
4547 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004548 Value *NewOp =
4549 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4550 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004551 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004552 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004553 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004554 }
4555
Evan Cheng8db90722008-10-14 17:15:11 +00004556 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004557 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004558 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4559 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4560 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004561 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004562
Chris Lattner7e708292002-06-25 16:13:24 +00004563 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004564}
4565
Chris Lattner8c34cd22008-10-05 02:13:19 +00004566/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4567/// capable of providing pieces of a bswap. The subexpression provides pieces
4568/// of a bswap if it is proven that each of the non-zero bytes in the output of
4569/// the expression came from the corresponding "byte swapped" byte in some other
4570/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4571/// we know that the expression deposits the low byte of %X into the high byte
4572/// of the bswap result and that all other bytes are zero. This expression is
4573/// accepted, the high byte of ByteValues is set to X to indicate a correct
4574/// match.
4575///
4576/// This function returns true if the match was unsuccessful and false if so.
4577/// On entry to the function the "OverallLeftShift" is a signed integer value
4578/// indicating the number of bytes that the subexpression is later shifted. For
4579/// example, if the expression is later right shifted by 16 bits, the
4580/// OverallLeftShift value would be -2 on entry. This is used to specify which
4581/// byte of ByteValues is actually being set.
4582///
4583/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4584/// byte is masked to zero by a user. For example, in (X & 255), X will be
4585/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4586/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4587/// always in the local (OverallLeftShift) coordinate space.
4588///
4589static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4590 SmallVector<Value*, 8> &ByteValues) {
4591 if (Instruction *I = dyn_cast<Instruction>(V)) {
4592 // If this is an or instruction, it may be an inner node of the bswap.
4593 if (I->getOpcode() == Instruction::Or) {
4594 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4595 ByteValues) ||
4596 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4597 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004598 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004599
4600 // If this is a logical shift by a constant multiple of 8, recurse with
4601 // OverallLeftShift and ByteMask adjusted.
4602 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4603 unsigned ShAmt =
4604 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4605 // Ensure the shift amount is defined and of a byte value.
4606 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4607 return true;
4608
4609 unsigned ByteShift = ShAmt >> 3;
4610 if (I->getOpcode() == Instruction::Shl) {
4611 // X << 2 -> collect(X, +2)
4612 OverallLeftShift += ByteShift;
4613 ByteMask >>= ByteShift;
4614 } else {
4615 // X >>u 2 -> collect(X, -2)
4616 OverallLeftShift -= ByteShift;
4617 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004618 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004619 }
4620
4621 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4622 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4623
4624 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4625 ByteValues);
4626 }
4627
4628 // If this is a logical 'and' with a mask that clears bytes, clear the
4629 // corresponding bytes in ByteMask.
4630 if (I->getOpcode() == Instruction::And &&
4631 isa<ConstantInt>(I->getOperand(1))) {
4632 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4633 unsigned NumBytes = ByteValues.size();
4634 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4635 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4636
4637 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4638 // If this byte is masked out by a later operation, we don't care what
4639 // the and mask is.
4640 if ((ByteMask & (1 << i)) == 0)
4641 continue;
4642
4643 // If the AndMask is all zeros for this byte, clear the bit.
4644 APInt MaskB = AndMask & Byte;
4645 if (MaskB == 0) {
4646 ByteMask &= ~(1U << i);
4647 continue;
4648 }
4649
4650 // If the AndMask is not all ones for this byte, it's not a bytezap.
4651 if (MaskB != Byte)
4652 return true;
4653
4654 // Otherwise, this byte is kept.
4655 }
4656
4657 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4658 ByteValues);
4659 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004660 }
4661
Chris Lattner8c34cd22008-10-05 02:13:19 +00004662 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4663 // the input value to the bswap. Some observations: 1) if more than one byte
4664 // is demanded from this input, then it could not be successfully assembled
4665 // into a byteswap. At least one of the two bytes would not be aligned with
4666 // their ultimate destination.
4667 if (!isPowerOf2_32(ByteMask)) return true;
4668 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004669
Chris Lattner8c34cd22008-10-05 02:13:19 +00004670 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4671 // is demanded, it needs to go into byte 0 of the result. This means that the
4672 // byte needs to be shifted until it lands in the right byte bucket. The
4673 // shift amount depends on the position: if the byte is coming from the high
4674 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4675 // low part, it must be shifted left.
4676 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4677 if (InputByteNo < ByteValues.size()/2) {
4678 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4679 return true;
4680 } else {
4681 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4682 return true;
4683 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004684
4685 // If the destination byte value is already defined, the values are or'd
4686 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004687 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004688 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004689 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004690 return false;
4691}
4692
4693/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4694/// If so, insert the new bswap intrinsic and return it.
4695Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004696 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004697 if (!ITy || ITy->getBitWidth() % 16 ||
4698 // ByteMask only allows up to 32-byte values.
4699 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004700 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004701
4702 /// ByteValues - For each byte of the result, we keep track of which value
4703 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004704 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004705 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004706
4707 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004708 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4709 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004710 return 0;
4711
4712 // Check to see if all of the bytes come from the same value.
4713 Value *V = ByteValues[0];
4714 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4715
4716 // Check to make sure that all of the bytes come from the same value.
4717 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4718 if (ByteValues[i] != V)
4719 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004720 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004721 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004722 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004723 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004724}
4725
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004726/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4727/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4728/// we can simplify this expression to "cond ? C : D or B".
4729static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004730 Value *C, Value *D,
4731 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004732 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004733 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004734 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004735 return 0;
4736
Chris Lattnera6a474d2008-11-16 04:26:55 +00004737 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004738 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004739 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004740 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004741 return SelectInst::Create(Cond, C, B);
4742 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004743 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004744 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004745 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004746 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004747 return 0;
4748}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004749
Chris Lattner69d4ced2008-11-16 05:20:07 +00004750/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4751Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4752 ICmpInst *LHS, ICmpInst *RHS) {
4753 Value *Val, *Val2;
4754 ConstantInt *LHSCst, *RHSCst;
4755 ICmpInst::Predicate LHSCC, RHSCC;
4756
4757 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004758 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004759 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004760 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004761 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004762 return 0;
4763
4764 // From here on, we only handle:
4765 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4766 if (Val != Val2) return 0;
4767
4768 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4769 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4770 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4771 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4772 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4773 return 0;
4774
4775 // We can't fold (ugt x, C) | (sgt x, C2).
4776 if (!PredicatesFoldable(LHSCC, RHSCC))
4777 return 0;
4778
4779 // Ensure that the larger constant is on the RHS.
4780 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004781 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004782 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004783 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004784 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4785 else
4786 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4787
4788 if (ShouldSwap) {
4789 std::swap(LHS, RHS);
4790 std::swap(LHSCst, RHSCst);
4791 std::swap(LHSCC, RHSCC);
4792 }
4793
4794 // At this point, we know we have have two icmp instructions
4795 // comparing a value against two constants and or'ing the result
4796 // together. Because of the above check, we know that we only have
4797 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4798 // FoldICmpLogical check above), that the two constants are not
4799 // equal.
4800 assert(LHSCst != RHSCst && "Compares not folded above?");
4801
4802 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004803 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004804 case ICmpInst::ICMP_EQ:
4805 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004806 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004807 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004808 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004809 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004810 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004811 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004812 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004813 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004814 }
4815 break; // (X == 13 | X == 15) -> no change
4816 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4817 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4818 break;
4819 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4820 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4821 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4822 return ReplaceInstUsesWith(I, RHS);
4823 }
4824 break;
4825 case ICmpInst::ICMP_NE:
4826 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004827 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004828 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4829 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4830 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4831 return ReplaceInstUsesWith(I, LHS);
4832 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4833 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4834 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004835 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004836 }
4837 break;
4838 case ICmpInst::ICMP_ULT:
4839 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004840 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004841 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4842 break;
4843 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4844 // If RHSCst is [us]MAXINT, it is always false. Not handling
4845 // this can cause overflow.
4846 if (RHSCst->isMaxValue(false))
4847 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004848 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004849 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004850 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4851 break;
4852 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4853 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4854 return ReplaceInstUsesWith(I, RHS);
4855 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4856 break;
4857 }
4858 break;
4859 case ICmpInst::ICMP_SLT:
4860 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004861 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004862 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4863 break;
4864 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4865 // If RHSCst is [us]MAXINT, it is always false. Not handling
4866 // this can cause overflow.
4867 if (RHSCst->isMaxValue(true))
4868 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004869 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004870 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004871 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4872 break;
4873 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4874 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4875 return ReplaceInstUsesWith(I, RHS);
4876 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4877 break;
4878 }
4879 break;
4880 case ICmpInst::ICMP_UGT:
4881 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004882 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004883 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4884 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4885 return ReplaceInstUsesWith(I, LHS);
4886 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4887 break;
4888 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4889 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004890 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004891 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4892 break;
4893 }
4894 break;
4895 case ICmpInst::ICMP_SGT:
4896 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004897 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004898 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4899 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4900 return ReplaceInstUsesWith(I, LHS);
4901 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4902 break;
4903 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4904 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004905 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004906 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4907 break;
4908 }
4909 break;
4910 }
4911 return 0;
4912}
4913
Chris Lattner5414cc52009-07-23 05:46:22 +00004914Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4915 FCmpInst *RHS) {
4916 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4917 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4918 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4919 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4920 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4921 // If either of the constants are nans, then the whole thing returns
4922 // true.
4923 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004924 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004925
4926 // Otherwise, no need to compare the two constants, compare the
4927 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004928 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004929 LHS->getOperand(0), RHS->getOperand(0));
4930 }
4931
4932 // Handle vector zeros. This occurs because the canonical form of
4933 // "fcmp uno x,x" is "fcmp uno x, 0".
4934 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4935 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004936 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004937 LHS->getOperand(0), RHS->getOperand(0));
4938
4939 return 0;
4940 }
4941
4942 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4943 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4944 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4945
4946 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4947 // Swap RHS operands to match LHS.
4948 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4949 std::swap(Op1LHS, Op1RHS);
4950 }
4951 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4952 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4953 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004954 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004955 Op0LHS, Op0RHS);
4956 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004957 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004958 if (Op0CC == FCmpInst::FCMP_FALSE)
4959 return ReplaceInstUsesWith(I, RHS);
4960 if (Op1CC == FCmpInst::FCMP_FALSE)
4961 return ReplaceInstUsesWith(I, LHS);
4962 bool Op0Ordered;
4963 bool Op1Ordered;
4964 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4965 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4966 if (Op0Ordered == Op1Ordered) {
4967 // If both are ordered or unordered, return a new fcmp with
4968 // or'ed predicates.
4969 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4970 Op0LHS, Op0RHS, Context);
4971 if (Instruction *I = dyn_cast<Instruction>(RV))
4972 return I;
4973 // Otherwise, it's a constant boolean value...
4974 return ReplaceInstUsesWith(I, RV);
4975 }
4976 }
4977 return 0;
4978}
4979
Bill Wendlinga698a472008-12-01 08:23:25 +00004980/// FoldOrWithConstants - This helper function folds:
4981///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004982/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004983///
4984/// into:
4985///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004986/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004987///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004988/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004989Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004990 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004991 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4992 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004993
Bill Wendling286a0542008-12-02 06:24:20 +00004994 Value *V1 = 0;
4995 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004996 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004997
Bill Wendling29976b92008-12-02 06:18:11 +00004998 APInt Xor = CI1->getValue() ^ CI2->getValue();
4999 if (!Xor.isAllOnesValue()) return 0;
5000
Bill Wendling286a0542008-12-02 06:24:20 +00005001 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00005002 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00005003 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00005004 }
5005
5006 return 0;
5007}
5008
Chris Lattner7e708292002-06-25 16:13:24 +00005009Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005010 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005011 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005012
Chris Lattner42593e62007-03-24 23:56:43 +00005013 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00005014 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005015
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005016 // or X, X = X
5017 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00005018 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005019
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005020 // See if we can simplify any instructions used by the instruction whose sole
5021 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005022 if (SimplifyDemandedInstructionBits(I))
5023 return &I;
5024 if (isa<VectorType>(I.getType())) {
5025 if (isa<ConstantAggregateZero>(Op1)) {
5026 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
5027 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
5028 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
5029 return ReplaceInstUsesWith(I, I.getOperand(1));
5030 }
Chris Lattner42593e62007-03-24 23:56:43 +00005031 }
Chris Lattner041a6c92007-06-15 05:26:55 +00005032
Chris Lattner3f5b8772002-05-06 16:14:14 +00005033 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005034 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00005035 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005036 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005037 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005038 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005039 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005040 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005041 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005042 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005043 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005044
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005045 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005046 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005047 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005048 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005049 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005050 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005051 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005052 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005053
5054 // Try to fold constant and into select arguments.
5055 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005056 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005057 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005058 if (isa<PHINode>(Op0))
5059 if (Instruction *NV = FoldOpIntoPhi(I))
5060 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005061 }
5062
Chris Lattner4f637d42006-01-06 17:59:59 +00005063 Value *A = 0, *B = 0;
5064 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005065
Dan Gohman4ae51262009-08-12 16:23:25 +00005066 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005067 if (A == Op1 || B == Op1) // (A & ?) | A --> A
5068 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00005069 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005070 if (A == Op0 || B == Op0) // A | (A & ?) --> A
5071 return ReplaceInstUsesWith(I, Op0);
5072
Chris Lattner6423d4c2006-07-10 20:25:24 +00005073 // (A | B) | C and A | (B | C) -> bswap if possible.
5074 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00005075 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5076 match(Op1, m_Or(m_Value(), m_Value())) ||
5077 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5078 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00005079 if (Instruction *BSwap = MatchBSwap(I))
5080 return BSwap;
5081 }
5082
Chris Lattner6e4c6492005-05-09 04:58:36 +00005083 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005084 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005085 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005086 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005087 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00005088 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005089 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005090 }
5091
5092 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005093 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005094 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005095 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005096 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00005097 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005098 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005099 }
5100
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005101 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00005102 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005103 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5104 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005105 Value *V1 = 0, *V2 = 0, *V3 = 0;
5106 C1 = dyn_cast<ConstantInt>(C);
5107 C2 = dyn_cast<ConstantInt>(D);
5108 if (C1 && C2) { // (A & C1)|(B & C2)
5109 // If we have: ((V + N) & C1) | (V & C2)
5110 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5111 // replace with V+N.
5112 if (C1->getValue() == ~C2->getValue()) {
5113 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00005114 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005115 // Add commutes, try both ways.
5116 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5117 return ReplaceInstUsesWith(I, A);
5118 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5119 return ReplaceInstUsesWith(I, A);
5120 }
5121 // Or commutes, try both ways.
5122 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005123 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005124 // Add commutes, try both ways.
5125 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5126 return ReplaceInstUsesWith(I, B);
5127 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5128 return ReplaceInstUsesWith(I, B);
5129 }
5130 }
Chris Lattner044e5332007-04-08 08:01:49 +00005131 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00005132 }
5133
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005134 // Check to see if we have any common things being and'ed. If so, find the
5135 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005136 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5137 if (A == B) // (A & C)|(A & D) == A & (C|D)
5138 V1 = A, V2 = C, V3 = D;
5139 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5140 V1 = A, V2 = B, V3 = C;
5141 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5142 V1 = C, V2 = A, V3 = D;
5143 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5144 V1 = C, V2 = A, V3 = B;
5145
5146 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00005147 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005148 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00005149 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005150 }
Dan Gohmanb493b272008-10-28 22:38:57 +00005151
Dan Gohman1975d032008-10-30 20:40:10 +00005152 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005153 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005154 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005155 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005156 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005157 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005158 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005159 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005160 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00005161
Bill Wendlingb01865c2008-11-30 13:52:49 +00005162 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005163 if ((match(C, m_Not(m_Specific(D))) &&
5164 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005165 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005166 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005167 if ((match(A, m_Not(m_Specific(D))) &&
5168 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005169 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005170 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005171 if ((match(C, m_Not(m_Specific(B))) &&
5172 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005173 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005174 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005175 if ((match(A, m_Not(m_Specific(B))) &&
5176 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005177 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005178 }
Chris Lattnere511b742006-11-14 07:46:50 +00005179
5180 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00005181 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5182 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5183 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00005184 SI0->getOperand(1) == SI1->getOperand(1) &&
5185 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005186 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5187 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005188 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00005189 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00005190 }
5191 }
Chris Lattner67ca7682003-08-12 19:11:07 +00005192
Bill Wendlingb3833d12008-12-01 01:07:11 +00005193 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005194 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5195 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005196 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005197 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005198 }
5199 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005200 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5201 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005202 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005203 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005204 }
5205
Chris Lattner48b59ec2009-10-26 15:40:07 +00005206 if ((A = dyn_castNotVal(Op0))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005207 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00005208 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005209 } else {
5210 A = 0;
5211 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005212 // Note, A is still live here!
Chris Lattner48b59ec2009-10-26 15:40:07 +00005213 if ((B = dyn_castNotVal(Op1))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005214 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00005215 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00005216
Misha Brukmancb6267b2004-07-30 12:50:08 +00005217 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005218 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00005219 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00005220 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005221 }
Chris Lattnera27231a2003-03-10 23:13:59 +00005222 }
Chris Lattnera2881962003-02-18 19:28:33 +00005223
Reid Spencere4d87aa2006-12-23 06:05:41 +00005224 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5225 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005226 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005227 return R;
5228
Chris Lattner69d4ced2008-11-16 05:20:07 +00005229 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5230 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5231 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005232 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005233
5234 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005235 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005236 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005237 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005238 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5239 !isa<ICmpInst>(Op1C->getOperand(0))) {
5240 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005241 if (SrcTy == Op1C->getOperand(0)->getType() &&
5242 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005243 // Only do this if the casts both really cause code to be
5244 // generated.
5245 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5246 I.getType(), TD) &&
5247 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5248 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005249 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5250 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005251 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005252 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005253 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005254 }
Chris Lattner99c65742007-10-24 05:38:08 +00005255 }
5256
5257
5258 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5259 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005260 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5261 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5262 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005263 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005264
Chris Lattner7e708292002-06-25 16:13:24 +00005265 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005266}
5267
Dan Gohman844731a2008-05-13 00:00:25 +00005268namespace {
5269
Chris Lattnerc317d392004-02-16 01:20:27 +00005270// XorSelf - Implements: X ^ X --> 0
5271struct XorSelf {
5272 Value *RHS;
5273 XorSelf(Value *rhs) : RHS(rhs) {}
5274 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5275 Instruction *apply(BinaryOperator &Xor) const {
5276 return &Xor;
5277 }
5278};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005279
Dan Gohman844731a2008-05-13 00:00:25 +00005280}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005281
Chris Lattner7e708292002-06-25 16:13:24 +00005282Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005283 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005284 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005285
Evan Chengd34af782008-03-25 20:07:13 +00005286 if (isa<UndefValue>(Op1)) {
5287 if (isa<UndefValue>(Op0))
5288 // Handle undef ^ undef -> 0 special case. This is a common
5289 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005290 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005291 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005292 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005293
Chris Lattnerc317d392004-02-16 01:20:27 +00005294 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005295 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005296 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005297 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005298 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005299
5300 // See if we can simplify any instructions used by the instruction whose sole
5301 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005302 if (SimplifyDemandedInstructionBits(I))
5303 return &I;
5304 if (isa<VectorType>(I.getType()))
5305 if (isa<ConstantAggregateZero>(Op1))
5306 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005307
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005308 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005309 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005310 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5311 if (Op0I->getOpcode() == Instruction::And ||
5312 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005313 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5314 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5315 if (dyn_castNotVal(Op0I->getOperand(1)))
5316 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005317 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005318 Value *NotY =
5319 Builder->CreateNot(Op0I->getOperand(1),
5320 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005321 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005322 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005323 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005324 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005325
5326 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5327 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5328 if (isFreeToInvert(Op0I->getOperand(0)) &&
5329 isFreeToInvert(Op0I->getOperand(1))) {
5330 Value *NotX =
5331 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5332 Value *NotY =
5333 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5334 if (Op0I->getOpcode() == Instruction::And)
5335 return BinaryOperator::CreateOr(NotX, NotY);
5336 return BinaryOperator::CreateAnd(NotX, NotY);
5337 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005338 }
5339 }
5340 }
5341
5342
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005343 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005344 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005345 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005346 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005347 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005348 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005349
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005350 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005351 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005352 FCI->getOperand(0), FCI->getOperand(1));
5353 }
5354
Nick Lewycky517e1f52008-05-31 19:01:33 +00005355 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5356 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5357 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5358 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5359 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005360 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5361 (RHS == ConstantExpr::getCast(Opcode,
5362 ConstantInt::getTrue(*Context),
5363 Op0C->getDestTy()))) {
5364 CI->setPredicate(CI->getInversePredicate());
5365 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005366 }
5367 }
5368 }
5369 }
5370
Reid Spencere4d87aa2006-12-23 06:05:41 +00005371 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005372 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005373 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5374 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005375 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5376 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005377 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005378 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005379 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005380
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005381 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005382 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005383 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005384 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005385 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005386 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005387 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005388 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005389 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005390 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005391 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005392 Constant *C = ConstantInt::get(*Context,
5393 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005394 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005395
Chris Lattner7c4049c2004-01-12 19:35:11 +00005396 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005397 } else if (Op0I->getOpcode() == Instruction::Or) {
5398 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005399 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005400 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005401 // Anything in both C1 and C2 is known to be zero, remove it from
5402 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005403 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5404 NewRHS = ConstantExpr::getAnd(NewRHS,
5405 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005406 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005407 I.setOperand(0, Op0I->getOperand(0));
5408 I.setOperand(1, NewRHS);
5409 return &I;
5410 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005411 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005412 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005413 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005414
5415 // Try to fold constant and into select arguments.
5416 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005417 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005418 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005419 if (isa<PHINode>(Op0))
5420 if (Instruction *NV = FoldOpIntoPhi(I))
5421 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005422 }
5423
Dan Gohman186a6362009-08-12 16:04:34 +00005424 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005425 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005426 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005427
Dan Gohman186a6362009-08-12 16:04:34 +00005428 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005429 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005430 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005431
Chris Lattner318bf792007-03-18 22:51:34 +00005432
5433 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5434 if (Op1I) {
5435 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005436 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005437 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005438 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005439 I.swapOperands();
5440 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005441 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005442 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005443 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005444 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005445 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005446 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005447 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005448 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005449 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005450 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005451 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005452 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005453 std::swap(A, B);
5454 }
Chris Lattner318bf792007-03-18 22:51:34 +00005455 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005456 I.swapOperands(); // Simplified below.
5457 std::swap(Op0, Op1);
5458 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005459 }
Chris Lattner318bf792007-03-18 22:51:34 +00005460 }
5461
5462 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5463 if (Op0I) {
5464 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005465 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005466 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005467 if (A == Op1) // (B|A)^B == (A|B)^B
5468 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005469 if (B == Op1) // (A|B)^B == A & ~B
5470 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005471 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005472 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005473 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005474 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005475 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005476 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005477 if (A == Op1) // (A&B)^A -> (B&A)^A
5478 std::swap(A, B);
5479 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005480 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005481 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005482 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005483 }
Chris Lattner318bf792007-03-18 22:51:34 +00005484 }
5485
5486 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5487 if (Op0I && Op1I && Op0I->isShift() &&
5488 Op0I->getOpcode() == Op1I->getOpcode() &&
5489 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5490 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005491 Value *NewOp =
5492 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5493 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005494 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005495 Op1I->getOperand(1));
5496 }
5497
5498 if (Op0I && Op1I) {
5499 Value *A, *B, *C, *D;
5500 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005501 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5502 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005503 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005504 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005505 }
5506 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005507 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5508 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005509 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005510 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005511 }
5512
5513 // (A & B)^(C & D)
5514 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005515 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5516 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005517 // (X & Y)^(X & Y) -> (Y^Z) & X
5518 Value *X = 0, *Y = 0, *Z = 0;
5519 if (A == C)
5520 X = A, Y = B, Z = D;
5521 else if (A == D)
5522 X = A, Y = B, Z = C;
5523 else if (B == C)
5524 X = B, Y = A, Z = D;
5525 else if (B == D)
5526 X = B, Y = A, Z = C;
5527
5528 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005529 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005530 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005531 }
5532 }
5533 }
5534
Reid Spencere4d87aa2006-12-23 06:05:41 +00005535 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5536 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005537 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005538 return R;
5539
Chris Lattner6fc205f2006-05-05 06:39:07 +00005540 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005541 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005542 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005543 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5544 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005545 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005546 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005547 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5548 I.getType(), TD) &&
5549 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5550 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005551 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5552 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005553 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005554 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005555 }
Chris Lattner99c65742007-10-24 05:38:08 +00005556 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005557
Chris Lattner7e708292002-06-25 16:13:24 +00005558 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005559}
5560
Owen Andersond672ecb2009-07-03 00:17:18 +00005561static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005562 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005563 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005564}
Chris Lattnera96879a2004-09-29 17:40:11 +00005565
Dan Gohman6de29f82009-06-15 22:12:54 +00005566static bool HasAddOverflow(ConstantInt *Result,
5567 ConstantInt *In1, ConstantInt *In2,
5568 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005569 if (IsSigned)
5570 if (In2->getValue().isNegative())
5571 return Result->getValue().sgt(In1->getValue());
5572 else
5573 return Result->getValue().slt(In1->getValue());
5574 else
5575 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005576}
5577
Dan Gohman6de29f82009-06-15 22:12:54 +00005578/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005579/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005580static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005581 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005582 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005583 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005584
Dan Gohman6de29f82009-06-15 22:12:54 +00005585 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5586 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005587 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005588 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5589 ExtractElement(In1, Idx, Context),
5590 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005591 IsSigned))
5592 return true;
5593 }
5594 return false;
5595 }
5596
5597 return HasAddOverflow(cast<ConstantInt>(Result),
5598 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5599 IsSigned);
5600}
5601
5602static bool HasSubOverflow(ConstantInt *Result,
5603 ConstantInt *In1, ConstantInt *In2,
5604 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005605 if (IsSigned)
5606 if (In2->getValue().isNegative())
5607 return Result->getValue().slt(In1->getValue());
5608 else
5609 return Result->getValue().sgt(In1->getValue());
5610 else
5611 return Result->getValue().ugt(In1->getValue());
5612}
5613
Dan Gohman6de29f82009-06-15 22:12:54 +00005614/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5615/// overflowed for this type.
5616static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005617 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005618 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005619 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005620
5621 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5622 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005623 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005624 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5625 ExtractElement(In1, Idx, Context),
5626 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005627 IsSigned))
5628 return true;
5629 }
5630 return false;
5631 }
5632
5633 return HasSubOverflow(cast<ConstantInt>(Result),
5634 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5635 IsSigned);
5636}
5637
Chris Lattner10c0d912008-04-22 02:53:33 +00005638
Reid Spencere4d87aa2006-12-23 06:05:41 +00005639/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005640/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005641Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005642 ICmpInst::Predicate Cond,
5643 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005644 // Look through bitcasts.
5645 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5646 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005647
Chris Lattner574da9b2005-01-13 20:14:25 +00005648 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005649 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005650 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005651 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005652 // know pointers can't overflow since the gep is inbounds. See if we can
5653 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005654 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5655
5656 // If not, synthesize the offset the hard way.
5657 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00005658 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005659 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005660 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005661 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005662 // If the base pointers are different, but the indices are the same, just
5663 // compare the base pointer.
5664 if (PtrBase != GEPRHS->getOperand(0)) {
5665 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005666 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005667 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005668 if (IndicesTheSame)
5669 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5670 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5671 IndicesTheSame = false;
5672 break;
5673 }
5674
5675 // If all indices are the same, just compare the base pointers.
5676 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005677 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005678 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005679
5680 // Otherwise, the base pointers are different and the indices are
5681 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005682 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005683 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005684
Chris Lattnere9d782b2005-01-13 22:25:21 +00005685 // If one of the GEPs has all zero indices, recurse.
5686 bool AllZeros = true;
5687 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5688 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5689 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5690 AllZeros = false;
5691 break;
5692 }
5693 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005694 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5695 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005696
5697 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005698 AllZeros = true;
5699 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5700 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5701 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5702 AllZeros = false;
5703 break;
5704 }
5705 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005706 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005707
Chris Lattner4401c9c2005-01-14 00:20:05 +00005708 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5709 // If the GEPs only differ by one index, compare it.
5710 unsigned NumDifferences = 0; // Keep track of # differences.
5711 unsigned DiffOperand = 0; // The operand that differs.
5712 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5713 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005714 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5715 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005716 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005717 NumDifferences = 2;
5718 break;
5719 } else {
5720 if (NumDifferences++) break;
5721 DiffOperand = i;
5722 }
5723 }
5724
5725 if (NumDifferences == 0) // SAME GEP?
5726 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005727 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005728 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005729
Chris Lattner4401c9c2005-01-14 00:20:05 +00005730 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005731 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5732 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005733 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005734 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005735 }
5736 }
5737
Reid Spencere4d87aa2006-12-23 06:05:41 +00005738 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005739 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005740 if (TD &&
5741 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005742 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5743 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00005744 Value *L = EmitGEPOffset(GEPLHS, *this);
5745 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005746 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005747 }
5748 }
5749 return 0;
5750}
5751
Chris Lattnera5406232008-05-19 20:18:56 +00005752/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5753///
5754Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5755 Instruction *LHSI,
5756 Constant *RHSC) {
5757 if (!isa<ConstantFP>(RHSC)) return 0;
5758 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5759
5760 // Get the width of the mantissa. We don't want to hack on conversions that
5761 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005762 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005763 if (MantissaWidth == -1) return 0; // Unknown.
5764
5765 // Check to see that the input is converted from an integer type that is small
5766 // enough that preserves all bits. TODO: check here for "known" sign bits.
5767 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman6de29f82009-06-15 22:12:54 +00005768 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005769
5770 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005771 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5772 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005773 ++InputSize;
5774
5775 // If the conversion would lose info, don't hack on this.
5776 if ((int)InputSize > MantissaWidth)
5777 return 0;
5778
5779 // Otherwise, we can potentially simplify the comparison. We know that it
5780 // will always come through as an integer value and we know the constant is
5781 // not a NAN (it would have been previously simplified).
5782 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5783
5784 ICmpInst::Predicate Pred;
5785 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005786 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005787 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005788 case FCmpInst::FCMP_OEQ:
5789 Pred = ICmpInst::ICMP_EQ;
5790 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005791 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005792 case FCmpInst::FCMP_OGT:
5793 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5794 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005795 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005796 case FCmpInst::FCMP_OGE:
5797 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5798 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005799 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005800 case FCmpInst::FCMP_OLT:
5801 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5802 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005803 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005804 case FCmpInst::FCMP_OLE:
5805 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5806 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005807 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005808 case FCmpInst::FCMP_ONE:
5809 Pred = ICmpInst::ICMP_NE;
5810 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005811 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005812 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005813 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005814 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005815 }
5816
5817 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5818
5819 // Now we know that the APFloat is a normal number, zero or inf.
5820
Chris Lattner85162782008-05-20 03:50:52 +00005821 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005822 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005823 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005824
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005825 if (!LHSUnsigned) {
5826 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5827 // and large values.
5828 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5829 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5830 APFloat::rmNearestTiesToEven);
5831 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5832 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5833 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005834 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5835 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005836 }
5837 } else {
5838 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5839 // +INF and large values.
5840 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5841 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5842 APFloat::rmNearestTiesToEven);
5843 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5844 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5845 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005846 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5847 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005848 }
Chris Lattnera5406232008-05-19 20:18:56 +00005849 }
5850
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005851 if (!LHSUnsigned) {
5852 // See if the RHS value is < SignedMin.
5853 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5854 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5855 APFloat::rmNearestTiesToEven);
5856 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5857 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5858 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005859 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5860 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005861 }
Chris Lattnera5406232008-05-19 20:18:56 +00005862 }
5863
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005864 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5865 // [0, UMAX], but it may still be fractional. See if it is fractional by
5866 // casting the FP value to the integer value and back, checking for equality.
5867 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005868 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005869 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5870 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005871 if (!RHS.isZero()) {
5872 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005873 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5874 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005875 if (!Equal) {
5876 // If we had a comparison against a fractional value, we have to adjust
5877 // the compare predicate and sometimes the value. RHSC is rounded towards
5878 // zero at this point.
5879 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005880 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005881 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005882 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005883 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005884 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005885 case ICmpInst::ICMP_ULE:
5886 // (float)int <= 4.4 --> int <= 4
5887 // (float)int <= -4.4 --> false
5888 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005889 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005890 break;
5891 case ICmpInst::ICMP_SLE:
5892 // (float)int <= 4.4 --> int <= 4
5893 // (float)int <= -4.4 --> int < -4
5894 if (RHS.isNegative())
5895 Pred = ICmpInst::ICMP_SLT;
5896 break;
5897 case ICmpInst::ICMP_ULT:
5898 // (float)int < -4.4 --> false
5899 // (float)int < 4.4 --> int <= 4
5900 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005901 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005902 Pred = ICmpInst::ICMP_ULE;
5903 break;
5904 case ICmpInst::ICMP_SLT:
5905 // (float)int < -4.4 --> int < -4
5906 // (float)int < 4.4 --> int <= 4
5907 if (!RHS.isNegative())
5908 Pred = ICmpInst::ICMP_SLE;
5909 break;
5910 case ICmpInst::ICMP_UGT:
5911 // (float)int > 4.4 --> int > 4
5912 // (float)int > -4.4 --> true
5913 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005914 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005915 break;
5916 case ICmpInst::ICMP_SGT:
5917 // (float)int > 4.4 --> int > 4
5918 // (float)int > -4.4 --> int >= -4
5919 if (RHS.isNegative())
5920 Pred = ICmpInst::ICMP_SGE;
5921 break;
5922 case ICmpInst::ICMP_UGE:
5923 // (float)int >= -4.4 --> true
5924 // (float)int >= 4.4 --> int > 4
5925 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005926 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005927 Pred = ICmpInst::ICMP_UGT;
5928 break;
5929 case ICmpInst::ICMP_SGE:
5930 // (float)int >= -4.4 --> int >= -4
5931 // (float)int >= 4.4 --> int > 4
5932 if (!RHS.isNegative())
5933 Pred = ICmpInst::ICMP_SGT;
5934 break;
5935 }
Chris Lattnera5406232008-05-19 20:18:56 +00005936 }
5937 }
5938
5939 // Lower this FP comparison into an appropriate integer version of the
5940 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005941 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005942}
5943
Reid Spencere4d87aa2006-12-23 06:05:41 +00005944Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5945 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005946 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005947
Chris Lattner58e97462007-01-14 19:42:17 +00005948 // Fold trivial predicates.
5949 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005950 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005951 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005952 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005953
5954 // Simplify 'fcmp pred X, X'
5955 if (Op0 == Op1) {
5956 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005957 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005958 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5959 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5960 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner9e17b632009-09-02 05:12:37 +00005961 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005962 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5963 case FCmpInst::FCMP_OLT: // True if ordered and less than
5964 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner9e17b632009-09-02 05:12:37 +00005965 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005966
5967 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5968 case FCmpInst::FCMP_ULT: // True if unordered or less than
5969 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5970 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5971 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5972 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005973 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005974 return &I;
5975
5976 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5977 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5978 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5979 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5980 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5981 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005982 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005983 return &I;
5984 }
5985 }
5986
Reid Spencere4d87aa2006-12-23 06:05:41 +00005987 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005988 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005989
Reid Spencere4d87aa2006-12-23 06:05:41 +00005990 // Handle fcmp with constant RHS
5991 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005992 // If the constant is a nan, see if we can fold the comparison based on it.
5993 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5994 if (CFP->getValueAPF().isNaN()) {
5995 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005996 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005997 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5998 "Comparison must be either ordered or unordered!");
5999 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00006000 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00006001 }
6002 }
6003
Reid Spencere4d87aa2006-12-23 06:05:41 +00006004 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6005 switch (LHSI->getOpcode()) {
6006 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006007 // Only fold fcmp into the PHI if the phi and fcmp are in the same
6008 // block. If in the same block, we're encouraging jump threading. If
6009 // not, we are just pessimizing the code by making an i1 phi.
6010 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006011 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006012 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006013 break;
Chris Lattnera5406232008-05-19 20:18:56 +00006014 case Instruction::SIToFP:
6015 case Instruction::UIToFP:
6016 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6017 return NV;
6018 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006019 case Instruction::Select:
6020 // If either operand of the select is a constant, we can fold the
6021 // comparison into the select arms, which will cause one to be
6022 // constant folded and the select turned into a bitwise or.
6023 Value *Op1 = 0, *Op2 = 0;
6024 if (LHSI->hasOneUse()) {
6025 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6026 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006027 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006028 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006029 Op2 = Builder->CreateFCmp(I.getPredicate(),
6030 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006031 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6032 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006033 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006034 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006035 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6036 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006037 }
6038 }
6039
6040 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006041 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006042 break;
6043 }
6044 }
6045
6046 return Changed ? &I : 0;
6047}
6048
6049Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6050 bool Changed = SimplifyCompare(I);
6051 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6052 const Type *Ty = Op0->getType();
6053
6054 // icmp X, X
6055 if (Op0 == Op1)
Chris Lattner9e17b632009-09-02 05:12:37 +00006056 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006057 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00006058
6059 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00006060 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006061
Reid Spencere4d87aa2006-12-23 06:05:41 +00006062 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00006063 // addresses never equal each other! We already know that Op0 != Op1.
Chris Lattnerbbc33852009-10-05 02:47:47 +00006064 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
Misha Brukmanfd939082005-04-21 23:48:37 +00006065 isa<ConstantPointerNull>(Op0)) &&
Chris Lattnerbbc33852009-10-05 02:47:47 +00006066 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00006067 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00006068 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006069 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00006070
Reid Spencere4d87aa2006-12-23 06:05:41 +00006071 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006072 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006073 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006074 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006075 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006076 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006077 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006078 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006079 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006080 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006081
Reid Spencere4d87aa2006-12-23 06:05:41 +00006082 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006083 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006084 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006085 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006086 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006087 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006088 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006089 case ICmpInst::ICMP_SGT:
6090 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006091 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006092 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006093 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006094 return BinaryOperator::CreateAnd(Not, Op0);
6095 }
6096 case ICmpInst::ICMP_UGE:
6097 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6098 // FALL THROUGH
6099 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006100 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006101 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006102 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006103 case ICmpInst::ICMP_SGE:
6104 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6105 // FALL THROUGH
6106 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006107 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006108 return BinaryOperator::CreateOr(Not, Op0);
6109 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006110 }
Chris Lattner8b170942002-08-09 23:47:40 +00006111 }
6112
Dan Gohman1c8491e2009-04-25 17:12:48 +00006113 unsigned BitWidth = 0;
6114 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006115 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6116 else if (Ty->isIntOrIntVector())
6117 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006118
6119 bool isSignBit = false;
6120
Dan Gohman81b28ce2008-09-16 18:46:06 +00006121 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006122 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006123 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006124
Chris Lattnerb6566012008-01-05 01:18:20 +00006125 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6126 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006127 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006128 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006129 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006130 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006131
Dan Gohman81b28ce2008-09-16 18:46:06 +00006132 // If we have an icmp le or icmp ge instruction, turn it into the
6133 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6134 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006135 switch (I.getPredicate()) {
6136 default: break;
6137 case ICmpInst::ICMP_ULE:
6138 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006139 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006140 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006141 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006142 case ICmpInst::ICMP_SLE:
6143 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006144 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006145 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006146 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006147 case ICmpInst::ICMP_UGE:
6148 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006149 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006150 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006151 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006152 case ICmpInst::ICMP_SGE:
6153 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006154 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006155 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006156 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006157 }
6158
Chris Lattner183661e2008-07-11 05:40:05 +00006159 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006160 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006161 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006162 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6163 }
6164
6165 // See if we can fold the comparison based on range information we can get
6166 // by checking whether bits are known to be zero or one in the input.
6167 if (BitWidth != 0) {
6168 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6169 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6170
6171 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006172 isSignBit ? APInt::getSignBit(BitWidth)
6173 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006174 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006175 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006176 if (SimplifyDemandedBits(I.getOperandUse(1),
6177 APInt::getAllOnesValue(BitWidth),
6178 Op1KnownZero, Op1KnownOne, 0))
6179 return &I;
6180
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006181 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006182 // in. Compute the Min, Max and RHS values based on the known bits. For the
6183 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006184 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6185 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006186 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006187 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6188 Op0Min, Op0Max);
6189 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6190 Op1Min, Op1Max);
6191 } else {
6192 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6193 Op0Min, Op0Max);
6194 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6195 Op1Min, Op1Max);
6196 }
6197
Chris Lattner183661e2008-07-11 05:40:05 +00006198 // If Min and Max are known to be the same, then SimplifyDemandedBits
6199 // figured out that the LHS is a constant. Just constant fold this now so
6200 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006201 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006202 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006203 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006204 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006205 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006206 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006207
Chris Lattner183661e2008-07-11 05:40:05 +00006208 // Based on the range information we know about the LHS, see if we can
6209 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006210 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006211 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006212 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006213 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006214 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006215 break;
6216 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006217 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006218 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006219 break;
6220 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006221 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006222 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006223 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006224 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006225 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006226 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006227 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6228 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006229 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006230 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006231
6232 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6233 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006234 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006235 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006236 }
Chris Lattner84dff672008-07-11 05:08:55 +00006237 break;
6238 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006239 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006240 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006241 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006242 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006243
6244 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006245 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006246 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6247 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006248 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006249 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006250
6251 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6252 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006253 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006254 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006255 }
Chris Lattner84dff672008-07-11 05:08:55 +00006256 break;
6257 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006258 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006259 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006260 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006261 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006262 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006263 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006264 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6265 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006266 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006267 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006268 }
Chris Lattner84dff672008-07-11 05:08:55 +00006269 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006270 case ICmpInst::ICMP_SGT:
6271 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006272 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006273 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006274 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006275
6276 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006277 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006278 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6279 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006280 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006281 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006282 }
6283 break;
6284 case ICmpInst::ICMP_SGE:
6285 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6286 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006287 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006288 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006289 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006290 break;
6291 case ICmpInst::ICMP_SLE:
6292 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6293 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006294 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006295 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006296 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006297 break;
6298 case ICmpInst::ICMP_UGE:
6299 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6300 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006301 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006302 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006303 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006304 break;
6305 case ICmpInst::ICMP_ULE:
6306 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6307 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006308 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006309 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006310 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006311 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006312 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006313
6314 // Turn a signed comparison into an unsigned one if both operands
6315 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006316 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006317 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6318 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006319 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006320 }
6321
6322 // Test if the ICmpInst instruction is used exclusively by a select as
6323 // part of a minimum or maximum operation. If so, refrain from doing
6324 // any other folding. This helps out other analyses which understand
6325 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6326 // and CodeGen. And in this case, at least one of the comparison
6327 // operands has at least one user besides the compare (the select),
6328 // which would often largely negate the benefit of folding anyway.
6329 if (I.hasOneUse())
6330 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6331 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6332 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6333 return 0;
6334
6335 // See if we are doing a comparison between a constant and an instruction that
6336 // can be folded into the comparison.
6337 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006338 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006339 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006340 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006341 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006342 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6343 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006344 }
6345
Chris Lattner01deb9d2007-04-03 17:43:25 +00006346 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006347 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6348 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6349 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006350 case Instruction::GetElementPtr:
6351 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006352 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006353 bool isAllZeros = true;
6354 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6355 if (!isa<Constant>(LHSI->getOperand(i)) ||
6356 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6357 isAllZeros = false;
6358 break;
6359 }
6360 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006361 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006362 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006363 }
6364 break;
6365
Chris Lattner6970b662005-04-23 15:31:55 +00006366 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006367 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006368 // block. If in the same block, we're encouraging jump threading. If
6369 // not, we are just pessimizing the code by making an i1 phi.
6370 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006371 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006372 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006373 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006374 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006375 // If either operand of the select is a constant, we can fold the
6376 // comparison into the select arms, which will cause one to be
6377 // constant folded and the select turned into a bitwise or.
6378 Value *Op1 = 0, *Op2 = 0;
6379 if (LHSI->hasOneUse()) {
6380 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6381 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006382 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006383 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006384 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6385 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006386 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6387 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006388 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006389 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006390 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6391 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006392 }
6393 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006394
Chris Lattner6970b662005-04-23 15:31:55 +00006395 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006396 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006397 break;
6398 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006399 case Instruction::Call:
6400 // If we have (malloc != null), and if the malloc has a single use, we
6401 // can assume it is successful and remove the malloc.
6402 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6403 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006404 // Need to explicitly erase malloc call here, instead of adding it to
6405 // Worklist, because it won't get DCE'd from the Worklist since
6406 // isInstructionTriviallyDead() returns false for function calls.
6407 // It is OK to replace LHSI/MallocCall with Undef because the
6408 // instruction that uses it will be erased via Worklist.
6409 if (extractMallocCall(LHSI)) {
6410 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6411 EraseInstFromFunction(*LHSI);
6412 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006413 ConstantInt::get(Type::getInt1Ty(*Context),
6414 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006415 }
6416 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6417 if (MallocCall->hasOneUse()) {
6418 MallocCall->replaceAllUsesWith(
6419 UndefValue::get(MallocCall->getType()));
6420 EraseInstFromFunction(*MallocCall);
6421 Worklist.Add(LHSI); // The malloc's bitcast use.
6422 return ReplaceInstUsesWith(I,
6423 ConstantInt::get(Type::getInt1Ty(*Context),
6424 !I.isTrueWhenEqual()));
6425 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006426 }
6427 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006428 }
Chris Lattner6970b662005-04-23 15:31:55 +00006429 }
6430
Reid Spencere4d87aa2006-12-23 06:05:41 +00006431 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006432 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006433 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006434 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006435 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006436 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6437 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006438 return NI;
6439
Reid Spencere4d87aa2006-12-23 06:05:41 +00006440 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006441 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6442 // now.
6443 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6444 if (isa<PointerType>(Op0->getType()) &&
6445 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006446 // We keep moving the cast from the left operand over to the right
6447 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006448 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006449
Chris Lattner57d86372007-01-06 01:45:59 +00006450 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6451 // so eliminate it as well.
6452 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6453 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006454
Chris Lattnerde90b762003-11-03 04:25:02 +00006455 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006456 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006457 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006458 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006459 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006460 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006461 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006462 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006463 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006464 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006465 }
Chris Lattner57d86372007-01-06 01:45:59 +00006466 }
6467
6468 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006469 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006470 // This comes up when you have code like
6471 // int X = A < B;
6472 // if (X) ...
6473 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006474 // with a constant or another cast from the same type.
6475 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006476 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006477 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006478 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006479
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006480 // See if it's the same type of instruction on the left and right.
6481 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6482 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006483 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006484 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006485 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006486 default: break;
6487 case Instruction::Add:
6488 case Instruction::Sub:
6489 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006490 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006491 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006492 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006493 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6494 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6495 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006496 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006497 ? I.getUnsignedPredicate()
6498 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006499 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006500 Op1I->getOperand(0));
6501 }
6502
6503 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006504 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006505 ? I.getUnsignedPredicate()
6506 : I.getSignedPredicate();
6507 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006508 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006509 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006510 }
6511 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006512 break;
6513 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006514 if (!I.isEquality())
6515 break;
6516
Nick Lewycky5d52c452008-08-21 05:56:10 +00006517 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6518 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6519 // Mask = -1 >> count-trailing-zeros(Cst).
6520 if (!CI->isZero() && !CI->isOne()) {
6521 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006522 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006523 APInt::getLowBitsSet(AP.getBitWidth(),
6524 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006525 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006526 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6527 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006528 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006529 }
6530 }
6531 break;
6532 }
6533 }
6534 }
6535 }
6536
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006537 // ~x < ~y --> y < x
6538 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006539 if (match(Op0, m_Not(m_Value(A))) &&
6540 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006541 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006542 }
6543
Chris Lattner65b72ba2006-09-18 04:22:48 +00006544 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006545 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006546
6547 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006548 if (match(Op0, m_Neg(m_Value(A))) &&
6549 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006550 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006551
Dan Gohman4ae51262009-08-12 16:23:25 +00006552 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006553 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6554 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006555 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006556 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006557 }
6558
Dan Gohman4ae51262009-08-12 16:23:25 +00006559 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006560 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006561 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006562 if (match(B, m_ConstantInt(C1)) &&
6563 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006564 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006565 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006566 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6567 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006568 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006569
6570 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006571 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6572 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6573 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6574 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006575 }
6576 }
6577
Dan Gohman4ae51262009-08-12 16:23:25 +00006578 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006579 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006580 // A == (A^B) -> B == 0
6581 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006582 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006583 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006584 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006585
6586 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006587 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006588 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006589 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006590
6591 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006592 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006593 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006594 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006595
Chris Lattner9c2328e2006-11-14 06:06:06 +00006596 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6597 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006598 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6599 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006600 Value *X = 0, *Y = 0, *Z = 0;
6601
6602 if (A == C) {
6603 X = B; Y = D; Z = A;
6604 } else if (A == D) {
6605 X = B; Y = C; Z = A;
6606 } else if (B == C) {
6607 X = A; Y = D; Z = B;
6608 } else if (B == D) {
6609 X = A; Y = C; Z = B;
6610 }
6611
6612 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006613 Op1 = Builder->CreateXor(X, Y, "tmp");
6614 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006615 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006616 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006617 return &I;
6618 }
6619 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006620 }
Chris Lattner7e708292002-06-25 16:13:24 +00006621 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006622}
6623
Chris Lattner562ef782007-06-20 23:46:26 +00006624
6625/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6626/// and CmpRHS are both known to be integer constants.
6627Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6628 ConstantInt *DivRHS) {
6629 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6630 const APInt &CmpRHSV = CmpRHS->getValue();
6631
6632 // FIXME: If the operand types don't match the type of the divide
6633 // then don't attempt this transform. The code below doesn't have the
6634 // logic to deal with a signed divide and an unsigned compare (and
6635 // vice versa). This is because (x /s C1) <s C2 produces different
6636 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6637 // (x /u C1) <u C2. Simply casting the operands and result won't
6638 // work. :( The if statement below tests that condition and bails
6639 // if it finds it.
6640 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00006641 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00006642 return 0;
6643 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006644 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006645 if (DivIsSigned && DivRHS->isAllOnesValue())
6646 return 0; // The overflow computation also screws up here
6647 if (DivRHS->isOne())
6648 return 0; // Not worth bothering, and eliminates some funny cases
6649 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006650
6651 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6652 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6653 // C2 (CI). By solving for X we can turn this into a range check
6654 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006655 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006656
6657 // Determine if the product overflows by seeing if the product is
6658 // not equal to the divide. Make sure we do the same kind of divide
6659 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006660 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6661 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006662
6663 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006664 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006665
Chris Lattner1dbfd482007-06-21 18:11:19 +00006666 // Figure out the interval that is being checked. For example, a comparison
6667 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6668 // Compute this interval based on the constants involved and the signedness of
6669 // the compare/divide. This computes a half-open interval, keeping track of
6670 // whether either value in the interval overflows. After analysis each
6671 // overflow variable is set to 0 if it's corresponding bound variable is valid
6672 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6673 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006674 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006675
Chris Lattner562ef782007-06-20 23:46:26 +00006676 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006677 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006678 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006679 HiOverflow = LoOverflow = ProdOV;
6680 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006681 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006682 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006683 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006684 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006685 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006686 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006687 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006688 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6689 HiOverflow = LoOverflow = ProdOV;
6690 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006691 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006692 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006693 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006694 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006695 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6696 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006697 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006698 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006699 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006700 true) ? -1 : 0;
6701 }
Chris Lattner562ef782007-06-20 23:46:26 +00006702 }
Dan Gohman76491272008-02-13 22:09:18 +00006703 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006704 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006705 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006706 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006707 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006708 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6709 HiOverflow = 1; // [INTMIN+1, overflow)
6710 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6711 }
Dan Gohman76491272008-02-13 22:09:18 +00006712 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006713 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006714 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006715 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006716 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006717 LoOverflow = AddWithOverflow(LoBound, HiBound,
6718 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006719 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006720 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6721 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006722 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006723 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006724 }
6725
Chris Lattner1dbfd482007-06-21 18:11:19 +00006726 // Dividing by a negative swaps the condition. LT <-> GT
6727 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006728 }
6729
6730 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006731 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006732 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006733 case ICmpInst::ICMP_EQ:
6734 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006735 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006736 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006737 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006738 ICmpInst::ICMP_UGE, X, LoBound);
6739 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006740 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006741 ICmpInst::ICMP_ULT, X, HiBound);
6742 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006743 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006744 case ICmpInst::ICMP_NE:
6745 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006746 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006747 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006748 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006749 ICmpInst::ICMP_ULT, X, LoBound);
6750 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006751 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006752 ICmpInst::ICMP_UGE, X, HiBound);
6753 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006754 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006755 case ICmpInst::ICMP_ULT:
6756 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006757 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006758 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006759 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006760 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006761 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006762 case ICmpInst::ICMP_UGT:
6763 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006764 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006765 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006766 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006767 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006768 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006769 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006770 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006771 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006772 }
6773}
6774
6775
Chris Lattner01deb9d2007-04-03 17:43:25 +00006776/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6777///
6778Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6779 Instruction *LHSI,
6780 ConstantInt *RHS) {
6781 const APInt &RHSV = RHS->getValue();
6782
6783 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006784 case Instruction::Trunc:
6785 if (ICI.isEquality() && LHSI->hasOneUse()) {
6786 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6787 // of the high bits truncated out of x are known.
6788 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6789 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6790 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6791 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6792 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6793
6794 // If all the high bits are known, we can do this xform.
6795 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6796 // Pull in the high bits from known-ones set.
6797 APInt NewRHS(RHS->getValue());
6798 NewRHS.zext(SrcBits);
6799 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006800 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006801 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006802 }
6803 }
6804 break;
6805
Duncan Sands0091bf22007-04-04 06:42:45 +00006806 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006807 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6808 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6809 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006810 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6811 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006812 Value *CompareVal = LHSI->getOperand(0);
6813
6814 // If the sign bit of the XorCST is not set, there is no change to
6815 // the operation, just stop using the Xor.
6816 if (!XorCST->getValue().isNegative()) {
6817 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006818 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006819 return &ICI;
6820 }
6821
6822 // Was the old condition true if the operand is positive?
6823 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6824
6825 // If so, the new one isn't.
6826 isTrueIfPositive ^= true;
6827
6828 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006829 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006830 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006831 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006832 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006833 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006834 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006835
6836 if (LHSI->hasOneUse()) {
6837 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6838 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6839 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006840 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006841 ? ICI.getUnsignedPredicate()
6842 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006843 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006844 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006845 }
6846
6847 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006848 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006849 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006850 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006851 ? ICI.getUnsignedPredicate()
6852 : ICI.getSignedPredicate();
6853 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006854 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006855 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006856 }
6857 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006858 }
6859 break;
6860 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6861 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6862 LHSI->getOperand(0)->hasOneUse()) {
6863 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6864
6865 // If the LHS is an AND of a truncating cast, we can widen the
6866 // and/compare to be the input width without changing the value
6867 // produced, eliminating a cast.
6868 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6869 // We can do this transformation if either the AND constant does not
6870 // have its sign bit set or if it is an equality comparison.
6871 // Extending a relational comparison when we're checking the sign
6872 // bit would not work.
6873 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006874 (ICI.isEquality() ||
6875 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006876 uint32_t BitWidth =
6877 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6878 APInt NewCST = AndCST->getValue();
6879 NewCST.zext(BitWidth);
6880 APInt NewCI = RHSV;
6881 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006882 Value *NewAnd =
6883 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006884 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006885 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006886 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006887 }
6888 }
6889
6890 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6891 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6892 // happens a LOT in code produced by the C front-end, for bitfield
6893 // access.
6894 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6895 if (Shift && !Shift->isShift())
6896 Shift = 0;
6897
6898 ConstantInt *ShAmt;
6899 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6900 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6901 const Type *AndTy = AndCST->getType(); // Type of the and.
6902
6903 // We can fold this as long as we can't shift unknown bits
6904 // into the mask. This can only happen with signed shift
6905 // rights, as they sign-extend.
6906 if (ShAmt) {
6907 bool CanFold = Shift->isLogicalShift();
6908 if (!CanFold) {
6909 // To test for the bad case of the signed shr, see if any
6910 // of the bits shifted in could be tested after the mask.
6911 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6912 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6913
6914 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6915 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6916 AndCST->getValue()) == 0)
6917 CanFold = true;
6918 }
6919
6920 if (CanFold) {
6921 Constant *NewCst;
6922 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006923 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006924 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006925 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006926
6927 // Check to see if we are shifting out any of the bits being
6928 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006929 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006930 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006931 // If we shifted bits out, the fold is not going to work out.
6932 // As a special case, check to see if this means that the
6933 // result is always true or false now.
6934 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006935 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006936 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006937 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006938 } else {
6939 ICI.setOperand(1, NewCst);
6940 Constant *NewAndCST;
6941 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006942 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006943 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006944 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006945 LHSI->setOperand(1, NewAndCST);
6946 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006947 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006948 return &ICI;
6949 }
6950 }
6951 }
6952
6953 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6954 // preferable because it allows the C<<Y expression to be hoisted out
6955 // of a loop if Y is invariant and X is not.
6956 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006957 ICI.isEquality() && !Shift->isArithmeticShift() &&
6958 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006959 // Compute C << Y.
6960 Value *NS;
6961 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006962 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006963 } else {
6964 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006965 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006966 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006967
6968 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006969 Value *NewAnd =
6970 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006971
6972 ICI.setOperand(0, NewAnd);
6973 return &ICI;
6974 }
6975 }
6976 break;
6977
Chris Lattnera0141b92007-07-15 20:42:37 +00006978 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6979 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6980 if (!ShAmt) break;
6981
6982 uint32_t TypeBits = RHSV.getBitWidth();
6983
6984 // Check that the shift amount is in range. If not, don't perform
6985 // undefined shifts. When the shift is visited it will be
6986 // simplified.
6987 if (ShAmt->uge(TypeBits))
6988 break;
6989
6990 if (ICI.isEquality()) {
6991 // If we are comparing against bits always shifted out, the
6992 // comparison cannot succeed.
6993 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006994 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006995 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006996 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6997 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006998 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006999 return ReplaceInstUsesWith(ICI, Cst);
7000 }
7001
7002 if (LHSI->hasOneUse()) {
7003 // Otherwise strength reduce the shift into an and.
7004 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7005 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00007006 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00007007 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007008
Chris Lattner74381062009-08-30 07:44:24 +00007009 Value *And =
7010 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007011 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00007012 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007013 }
7014 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007015
7016 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7017 bool TrueIfSigned = false;
7018 if (LHSI->hasOneUse() &&
7019 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7020 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00007021 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00007022 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00007023 Value *And =
7024 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007025 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00007026 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00007027 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007028 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007029 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007030
7031 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00007032 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007033 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00007034 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007035 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007036
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007037 // Check that the shift amount is in range. If not, don't perform
7038 // undefined shifts. When the shift is visited it will be
7039 // simplified.
7040 uint32_t TypeBits = RHSV.getBitWidth();
7041 if (ShAmt->uge(TypeBits))
7042 break;
7043
7044 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007045
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007046 // If we are comparing against bits always shifted out, the
7047 // comparison cannot succeed.
7048 APInt Comp = RHSV << ShAmtVal;
7049 if (LHSI->getOpcode() == Instruction::LShr)
7050 Comp = Comp.lshr(ShAmtVal);
7051 else
7052 Comp = Comp.ashr(ShAmtVal);
7053
7054 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7055 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007056 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007057 return ReplaceInstUsesWith(ICI, Cst);
7058 }
7059
7060 // Otherwise, check to see if the bits shifted out are known to be zero.
7061 // If so, we can compare against the unshifted value:
7062 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007063 if (LHSI->hasOneUse() &&
7064 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007065 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007066 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007067 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007068 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007069
Evan Chengf30752c2008-04-23 00:38:06 +00007070 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007071 // Otherwise strength reduce the shift into an and.
7072 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007073 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007074
Chris Lattner74381062009-08-30 07:44:24 +00007075 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7076 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007077 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007078 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007079 }
7080 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007081 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007082
7083 case Instruction::SDiv:
7084 case Instruction::UDiv:
7085 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7086 // Fold this div into the comparison, producing a range check.
7087 // Determine, based on the divide type, what the range is being
7088 // checked. If there is an overflow on the low or high side, remember
7089 // it, otherwise compute the range [low, hi) bounding the new value.
7090 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007091 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7092 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7093 DivRHS))
7094 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007095 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007096
7097 case Instruction::Add:
7098 // Fold: icmp pred (add, X, C1), C2
7099
7100 if (!ICI.isEquality()) {
7101 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7102 if (!LHSC) break;
7103 const APInt &LHSV = LHSC->getValue();
7104
7105 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7106 .subtract(LHSV);
7107
Nick Lewycky4a134af2009-10-25 05:20:17 +00007108 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007109 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007110 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007111 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007112 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007113 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007114 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007115 }
7116 } else {
7117 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007118 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007119 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007120 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007121 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007122 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007123 }
7124 }
7125 }
7126 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007127 }
7128
7129 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7130 if (ICI.isEquality()) {
7131 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7132
7133 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7134 // the second operand is a constant, simplify a bit.
7135 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7136 switch (BO->getOpcode()) {
7137 case Instruction::SRem:
7138 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7139 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7140 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7141 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007142 Value *NewRem =
7143 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7144 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007145 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007146 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007147 }
7148 }
7149 break;
7150 case Instruction::Add:
7151 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7152 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7153 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007154 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007155 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007156 } else if (RHSV == 0) {
7157 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7158 // efficiently invertible, or if the add has just this one use.
7159 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7160
Dan Gohman186a6362009-08-12 16:04:34 +00007161 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007162 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007163 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007164 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007165 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007166 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007167 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007168 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007169 }
7170 }
7171 break;
7172 case Instruction::Xor:
7173 // For the xor case, we can xor two constants together, eliminating
7174 // the explicit xor.
7175 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007176 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007177 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007178
7179 // FALLTHROUGH
7180 case Instruction::Sub:
7181 // Replace (([sub|xor] A, B) != 0) with (A != B)
7182 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007183 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007184 BO->getOperand(1));
7185 break;
7186
7187 case Instruction::Or:
7188 // If bits are being or'd in that are not present in the constant we
7189 // are comparing against, then the comparison could never succeed!
7190 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007191 Constant *NotCI = ConstantExpr::getNot(RHS);
7192 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007193 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007194 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007195 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007196 }
7197 break;
7198
7199 case Instruction::And:
7200 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7201 // If bits are being compared against that are and'd out, then the
7202 // comparison can never succeed!
7203 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007204 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007205 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007206 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007207
7208 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7209 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007210 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007211 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007212 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007213
7214 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007215 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007216 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007217 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007218 ICmpInst::Predicate pred = isICMP_NE ?
7219 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007220 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007221 }
7222
7223 // ((X & ~7) == 0) --> X < 8
7224 if (RHSV == 0 && isHighOnes(BOC)) {
7225 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007226 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007227 ICmpInst::Predicate pred = isICMP_NE ?
7228 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007229 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007230 }
7231 }
7232 default: break;
7233 }
7234 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7235 // Handle icmp {eq|ne} <intrinsic>, intcst.
7236 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007237 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007238 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007239 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007240 return &ICI;
7241 }
7242 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007243 }
7244 return 0;
7245}
7246
7247/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7248/// We only handle extending casts so far.
7249///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007250Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7251 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007252 Value *LHSCIOp = LHSCI->getOperand(0);
7253 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007254 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007255 Value *RHSCIOp;
7256
Chris Lattner8c756c12007-05-05 22:41:33 +00007257 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7258 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007259 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7260 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007261 cast<IntegerType>(DestTy)->getBitWidth()) {
7262 Value *RHSOp = 0;
7263 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007264 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007265 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7266 RHSOp = RHSC->getOperand(0);
7267 // If the pointer types don't match, insert a bitcast.
7268 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007269 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007270 }
7271
7272 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007273 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007274 }
7275
7276 // The code below only handles extension cast instructions, so far.
7277 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007278 if (LHSCI->getOpcode() != Instruction::ZExt &&
7279 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007280 return 0;
7281
Reid Spencere4d87aa2006-12-23 06:05:41 +00007282 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007283 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007284
Reid Spencere4d87aa2006-12-23 06:05:41 +00007285 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007286 // Not an extension from the same type?
7287 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007288 if (RHSCIOp->getType() != LHSCIOp->getType())
7289 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007290
Nick Lewycky4189a532008-01-28 03:48:02 +00007291 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007292 // and the other is a zext), then we can't handle this.
7293 if (CI->getOpcode() != LHSCI->getOpcode())
7294 return 0;
7295
Nick Lewycky4189a532008-01-28 03:48:02 +00007296 // Deal with equality cases early.
7297 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007298 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007299
7300 // A signed comparison of sign extended values simplifies into a
7301 // signed comparison.
7302 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007303 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007304
7305 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007306 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007307 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007308
Reid Spencere4d87aa2006-12-23 06:05:41 +00007309 // If we aren't dealing with a constant on the RHS, exit early
7310 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7311 if (!CI)
7312 return 0;
7313
7314 // Compute the constant that would happen if we truncated to SrcTy then
7315 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007316 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7317 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007318 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007319
7320 // If the re-extended constant didn't change...
7321 if (Res2 == CI) {
7322 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7323 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007324 // %A = sext i16 %X to i32
7325 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007326 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007327 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007328 // because %A may have negative value.
7329 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007330 // However, we allow this when the compare is EQ/NE, because they are
7331 // signless.
7332 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007333 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007334 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007335 }
7336
7337 // The re-extended constant changed so the constant cannot be represented
7338 // in the shorter type. Consequently, we cannot emit a simple comparison.
7339
7340 // First, handle some easy cases. We know the result cannot be equal at this
7341 // point so handle the ICI.isEquality() cases
7342 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007343 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007344 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007345 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007346
7347 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7348 // should have been folded away previously and not enter in here.
7349 Value *Result;
7350 if (isSignedCmp) {
7351 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007352 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007353 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007354 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007355 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007356 } else {
7357 // We're performing an unsigned comparison.
7358 if (isSignedExt) {
7359 // We're performing an unsigned comp with a sign extended value.
7360 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007361 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007362 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007363 } else {
7364 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007365 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007366 }
7367 }
7368
7369 // Finally, return the value computed.
7370 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007371 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007372 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007373
7374 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7375 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7376 "ICmp should be folded!");
7377 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007378 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007379 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007380}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007381
Reid Spencer832254e2007-02-02 02:16:23 +00007382Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7383 return commonShiftTransforms(I);
7384}
7385
7386Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7387 return commonShiftTransforms(I);
7388}
7389
7390Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007391 if (Instruction *R = commonShiftTransforms(I))
7392 return R;
7393
7394 Value *Op0 = I.getOperand(0);
7395
7396 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7397 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7398 if (CSI->isAllOnesValue())
7399 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007400
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007401 // See if we can turn a signed shr into an unsigned shr.
7402 if (MaskedValueIsZero(Op0,
7403 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7404 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7405
7406 // Arithmetic shifting an all-sign-bit value is a no-op.
7407 unsigned NumSignBits = ComputeNumSignBits(Op0);
7408 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7409 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007410
Chris Lattner348f6652007-12-06 01:59:46 +00007411 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007412}
7413
7414Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7415 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007416 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007417
7418 // shl X, 0 == X and shr X, 0 == X
7419 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007420 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7421 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007422 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007423
Reid Spencere4d87aa2006-12-23 06:05:41 +00007424 if (isa<UndefValue>(Op0)) {
7425 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007426 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007427 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007428 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007429 }
7430 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007431 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7432 return ReplaceInstUsesWith(I, Op0);
7433 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007434 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007435 }
7436
Dan Gohman9004c8a2009-05-21 02:28:33 +00007437 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007438 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007439 return &I;
7440
Chris Lattner2eefe512004-04-09 19:05:30 +00007441 // Try to fold constant and into select arguments.
7442 if (isa<Constant>(Op0))
7443 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007444 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007445 return R;
7446
Reid Spencerb83eb642006-10-20 07:07:24 +00007447 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007448 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7449 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007450 return 0;
7451}
7452
Reid Spencerb83eb642006-10-20 07:07:24 +00007453Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007454 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007455 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007456
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007457 // See if we can simplify any instructions used by the instruction whose sole
7458 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007459 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007460
Dan Gohmana119de82009-06-14 23:30:43 +00007461 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7462 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007463 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007464 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007465 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007466 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007467 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007468 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007469 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007470 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007471 }
7472
7473 // ((X*C1) << C2) == (X * (C1 << C2))
7474 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7475 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7476 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007477 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007478 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007479
7480 // Try to fold constant and into select arguments.
7481 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7482 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7483 return R;
7484 if (isa<PHINode>(Op0))
7485 if (Instruction *NV = FoldOpIntoPhi(I))
7486 return NV;
7487
Chris Lattner8999dd32007-12-22 09:07:47 +00007488 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7489 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7490 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7491 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7492 // place. Don't try to do this transformation in this case. Also, we
7493 // require that the input operand is a shift-by-constant so that we have
7494 // confidence that the shifts will get folded together. We could do this
7495 // xform in more cases, but it is unlikely to be profitable.
7496 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7497 isa<ConstantInt>(TrOp->getOperand(1))) {
7498 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007499 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007500 // (shift2 (shift1 & 0x00FF), c2)
7501 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007502
7503 // For logical shifts, the truncation has the effect of making the high
7504 // part of the register be zeros. Emulate this by inserting an AND to
7505 // clear the top bits as needed. This 'and' will usually be zapped by
7506 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007507 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7508 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007509 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7510
7511 // The mask we constructed says what the trunc would do if occurring
7512 // between the shifts. We want to know the effect *after* the second
7513 // shift. We know that it is a logical shift by a constant, so adjust the
7514 // mask as appropriate.
7515 if (I.getOpcode() == Instruction::Shl)
7516 MaskV <<= Op1->getZExtValue();
7517 else {
7518 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7519 MaskV = MaskV.lshr(Op1->getZExtValue());
7520 }
7521
Chris Lattner74381062009-08-30 07:44:24 +00007522 // shift1 & 0x00FF
7523 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7524 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007525
7526 // Return the value truncated to the interesting size.
7527 return new TruncInst(And, I.getType());
7528 }
7529 }
7530
Chris Lattner4d5542c2006-01-06 07:12:35 +00007531 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007532 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7533 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7534 Value *V1, *V2;
7535 ConstantInt *CC;
7536 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007537 default: break;
7538 case Instruction::Add:
7539 case Instruction::And:
7540 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007541 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007542 // These operators commute.
7543 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007544 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007545 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007546 m_Specific(Op1)))) {
7547 Value *YS = // (Y << C)
7548 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7549 // (X + (Y << C))
7550 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7551 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007552 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007553 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007554 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007555 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007556
Chris Lattner150f12a2005-09-18 06:30:59 +00007557 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007558 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007559 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007560 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007561 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007562 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007563 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007564 Value *YS = // (Y << C)
7565 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7566 Op0BO->getName());
7567 // X & (CC << C)
7568 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7569 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007570 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007571 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007572 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007573
Reid Spencera07cb7d2007-02-02 14:41:37 +00007574 // FALL THROUGH.
7575 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007576 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007577 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007578 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007579 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007580 Value *YS = // (Y << C)
7581 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7582 // (X + (Y << C))
7583 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7584 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007585 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007586 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007587 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007588 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007589
Chris Lattner13d4ab42006-05-31 21:14:00 +00007590 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007591 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7592 match(Op0BO->getOperand(0),
7593 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007594 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007595 cast<BinaryOperator>(Op0BO->getOperand(0))
7596 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007597 Value *YS = // (Y << C)
7598 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7599 // X & (CC << C)
7600 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7601 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007602
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007603 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007604 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007605
Chris Lattner11021cb2005-09-18 05:12:10 +00007606 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007607 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007608 }
7609
7610
7611 // If the operand is an bitwise operator with a constant RHS, and the
7612 // shift is the only use, we can pull it out of the shift.
7613 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7614 bool isValid = true; // Valid only for And, Or, Xor
7615 bool highBitSet = false; // Transform if high bit of constant set?
7616
7617 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007618 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007619 case Instruction::Add:
7620 isValid = isLeftShift;
7621 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007622 case Instruction::Or:
7623 case Instruction::Xor:
7624 highBitSet = false;
7625 break;
7626 case Instruction::And:
7627 highBitSet = true;
7628 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007629 }
7630
7631 // If this is a signed shift right, and the high bit is modified
7632 // by the logical operation, do not perform the transformation.
7633 // The highBitSet boolean indicates the value of the high bit of
7634 // the constant which would cause it to be modified for this
7635 // operation.
7636 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007637 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007638 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007639
7640 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007641 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007642
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007643 Value *NewShift =
7644 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007645 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007646
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007647 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007648 NewRHS);
7649 }
7650 }
7651 }
7652 }
7653
Chris Lattnerad0124c2006-01-06 07:52:12 +00007654 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007655 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7656 if (ShiftOp && !ShiftOp->isShift())
7657 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007658
Reid Spencerb83eb642006-10-20 07:07:24 +00007659 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007660 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007661 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7662 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007663 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7664 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7665 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007666
Zhou Sheng4351c642007-04-02 08:20:41 +00007667 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007668
7669 const IntegerType *Ty = cast<IntegerType>(I.getType());
7670
7671 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007672 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007673 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7674 // saturates.
7675 if (AmtSum >= TypeBits) {
7676 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007677 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007678 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7679 }
7680
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007681 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007682 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007683 }
7684
7685 if (ShiftOp->getOpcode() == Instruction::LShr &&
7686 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007687 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007688 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007689
Chris Lattnerb87056f2007-02-05 00:57:54 +00007690 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007691 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007692 }
7693
7694 if (ShiftOp->getOpcode() == Instruction::AShr &&
7695 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007696 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007697 if (AmtSum >= TypeBits)
7698 AmtSum = TypeBits-1;
7699
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007700 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007701
Zhou Shenge9e03f62007-03-28 15:02:20 +00007702 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007703 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007704 }
7705
Chris Lattnerb87056f2007-02-05 00:57:54 +00007706 // Okay, if we get here, one shift must be left, and the other shift must be
7707 // right. See if the amounts are equal.
7708 if (ShiftAmt1 == ShiftAmt2) {
7709 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7710 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007711 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007712 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007713 }
7714 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7715 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007716 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007717 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007718 }
7719 // We can simplify ((X << C) >>s C) into a trunc + sext.
7720 // NOTE: we could do this for any C, but that would make 'unusual' integer
7721 // types. For now, just stick to ones well-supported by the code
7722 // generators.
7723 const Type *SExtType = 0;
7724 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007725 case 1 :
7726 case 8 :
7727 case 16 :
7728 case 32 :
7729 case 64 :
7730 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007731 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007732 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007733 default: break;
7734 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007735 if (SExtType)
7736 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007737 // Otherwise, we can't handle it yet.
7738 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007739 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007740
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007741 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007742 if (I.getOpcode() == Instruction::Shl) {
7743 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7744 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007745 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007746
Reid Spencer55702aa2007-03-25 21:11:44 +00007747 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007748 return BinaryOperator::CreateAnd(Shift,
7749 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007750 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007751
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007752 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007753 if (I.getOpcode() == Instruction::LShr) {
7754 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007755 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007756
Reid Spencerd5e30f02007-03-26 17:18:58 +00007757 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007758 return BinaryOperator::CreateAnd(Shift,
7759 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007760 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007761
7762 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7763 } else {
7764 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007765 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007766
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007767 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007768 if (I.getOpcode() == Instruction::Shl) {
7769 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7770 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007771 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7772 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007773
Reid Spencer55702aa2007-03-25 21:11:44 +00007774 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007775 return BinaryOperator::CreateAnd(Shift,
7776 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007777 }
7778
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007779 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007780 if (I.getOpcode() == Instruction::LShr) {
7781 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007782 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007783
Reid Spencer68d27cf2007-03-26 23:45:51 +00007784 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007785 return BinaryOperator::CreateAnd(Shift,
7786 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007787 }
7788
7789 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007790 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007791 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007792 return 0;
7793}
7794
Chris Lattnera1be5662002-05-02 17:06:02 +00007795
Chris Lattnercfd65102005-10-29 04:36:15 +00007796/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7797/// expression. If so, decompose it, returning some value X, such that Val is
7798/// X*Scale+Offset.
7799///
7800static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007801 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007802 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7803 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007804 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007805 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007806 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007807 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007808 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7809 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7810 if (I->getOpcode() == Instruction::Shl) {
7811 // This is a value scaled by '1 << the shift amt'.
7812 Scale = 1U << RHS->getZExtValue();
7813 Offset = 0;
7814 return I->getOperand(0);
7815 } else if (I->getOpcode() == Instruction::Mul) {
7816 // This value is scaled by 'RHS'.
7817 Scale = RHS->getZExtValue();
7818 Offset = 0;
7819 return I->getOperand(0);
7820 } else if (I->getOpcode() == Instruction::Add) {
7821 // We have X+C. Check to see if we really have (X*C2)+C1,
7822 // where C1 is divisible by C2.
7823 unsigned SubScale;
7824 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007825 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7826 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007827 Offset += RHS->getZExtValue();
7828 Scale = SubScale;
7829 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007830 }
7831 }
7832 }
7833
7834 // Otherwise, we can't look past this.
7835 Scale = 1;
7836 Offset = 0;
7837 return Val;
7838}
7839
7840
Chris Lattnerb3f83972005-10-24 06:03:58 +00007841/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7842/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007843Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00007844 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007845 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007846
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007847 BuilderTy AllocaBuilder(*Builder);
7848 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7849
Chris Lattnerb53c2382005-10-24 06:22:12 +00007850 // Remove any uses of AI that are dead.
7851 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007852
Chris Lattnerb53c2382005-10-24 06:22:12 +00007853 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7854 Instruction *User = cast<Instruction>(*UI++);
7855 if (isInstructionTriviallyDead(User)) {
7856 while (UI != E && *UI == User)
7857 ++UI; // If this instruction uses AI more than once, don't break UI.
7858
Chris Lattnerb53c2382005-10-24 06:22:12 +00007859 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007860 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007861 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007862 }
7863 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007864
7865 // This requires TargetData to get the alloca alignment and size information.
7866 if (!TD) return 0;
7867
Chris Lattnerb3f83972005-10-24 06:03:58 +00007868 // Get the type really allocated and the type casted to.
7869 const Type *AllocElTy = AI.getAllocatedType();
7870 const Type *CastElTy = PTy->getElementType();
7871 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007872
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007873 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7874 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007875 if (CastElTyAlign < AllocElTyAlign) return 0;
7876
Chris Lattner39387a52005-10-24 06:35:18 +00007877 // If the allocation has multiple uses, only promote it if we are strictly
7878 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007879 // same, we open the door to infinite loops of various kinds. (A reference
7880 // from a dbg.declare doesn't count as a use for this purpose.)
7881 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7882 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007883
Duncan Sands777d2302009-05-09 07:06:46 +00007884 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7885 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007886 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007887
Chris Lattner455fcc82005-10-29 03:19:53 +00007888 // See if we can satisfy the modulus by pulling a scale out of the array
7889 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007890 unsigned ArraySizeScale;
7891 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007892 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007893 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7894 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007895
Chris Lattner455fcc82005-10-29 03:19:53 +00007896 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7897 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007898 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7899 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007900
Chris Lattner455fcc82005-10-29 03:19:53 +00007901 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7902 Value *Amt = 0;
7903 if (Scale == 1) {
7904 Amt = NumElements;
7905 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007906 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007907 // Insert before the alloca, not before the cast.
7908 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007909 }
7910
Jeff Cohen86796be2007-04-04 16:58:57 +00007911 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007912 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007913 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007914 }
7915
Victor Hernandez7b929da2009-10-23 21:09:37 +00007916 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007917 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007918 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007919
Dale Johannesena0a66372009-03-05 00:39:02 +00007920 // If the allocation has one real use plus a dbg.declare, just remove the
7921 // declare.
7922 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7923 EraseInstFromFunction(*DI);
7924 }
7925 // If the allocation has multiple real uses, insert a cast and change all
7926 // things that used it to use the new cast. This will also hack on CI, but it
7927 // will die soon.
7928 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007929 // New is the allocation instruction, pointer typed. AI is the original
7930 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007931 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007932 AI.replaceAllUsesWith(NewCast);
7933 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007934 return ReplaceInstUsesWith(CI, New);
7935}
7936
Chris Lattner70074e02006-05-13 02:06:03 +00007937/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007938/// and return it as type Ty without inserting any new casts and without
7939/// changing the computed value. This is used by code that tries to decide
7940/// whether promoting or shrinking integer operations to wider or smaller types
7941/// will allow us to eliminate a truncate or extend.
7942///
7943/// This is a truncation operation if Ty is smaller than V->getType(), or an
7944/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007945///
7946/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7947/// should return true if trunc(V) can be computed by computing V in the smaller
7948/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7949/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7950/// efficiently truncated.
7951///
7952/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7953/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7954/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007955bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007956 unsigned CastOpc,
7957 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007958 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007959 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007960 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007961
7962 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007963 if (!I) return false;
7964
Dan Gohman6de29f82009-06-15 22:12:54 +00007965 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007966
Chris Lattner951626b2007-08-02 06:11:14 +00007967 // If this is an extension or truncate, we can often eliminate it.
7968 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7969 // If this is a cast from the destination type, we can trivially eliminate
7970 // it, and this will remove a cast overall.
7971 if (I->getOperand(0)->getType() == Ty) {
7972 // If the first operand is itself a cast, and is eliminable, do not count
7973 // this as an eliminable cast. We would prefer to eliminate those two
7974 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007975 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007976 ++NumCastsRemoved;
7977 return true;
7978 }
7979 }
7980
7981 // We can't extend or shrink something that has multiple uses: doing so would
7982 // require duplicating the instruction in general, which isn't profitable.
7983 if (!I->hasOneUse()) return false;
7984
Evan Chengf35fd542009-01-15 17:01:23 +00007985 unsigned Opc = I->getOpcode();
7986 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007987 case Instruction::Add:
7988 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007989 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007990 case Instruction::And:
7991 case Instruction::Or:
7992 case Instruction::Xor:
7993 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007994 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007995 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007996 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007997 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007998
Eli Friedman070a9812009-07-13 22:46:01 +00007999 case Instruction::UDiv:
8000 case Instruction::URem: {
8001 // UDiv and URem can be truncated if all the truncated bits are zero.
8002 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8003 uint32_t BitWidth = Ty->getScalarSizeInBits();
8004 if (BitWidth < OrigBitWidth) {
8005 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8006 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8007 MaskedValueIsZero(I->getOperand(1), Mask)) {
8008 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8009 NumCastsRemoved) &&
8010 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8011 NumCastsRemoved);
8012 }
8013 }
8014 break;
8015 }
Chris Lattner46b96052006-11-29 07:18:39 +00008016 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008017 // If we are truncating the result of this SHL, and if it's a shift of a
8018 // constant amount, we can always perform a SHL in a smaller type.
8019 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008020 uint32_t BitWidth = Ty->getScalarSizeInBits();
8021 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008022 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008023 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008024 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008025 }
8026 break;
8027 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008028 // If this is a truncate of a logical shr, we can truncate it to a smaller
8029 // lshr iff we know that the bits we would otherwise be shifting in are
8030 // already zeros.
8031 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008032 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8033 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008034 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008035 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008036 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8037 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008038 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008039 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008040 }
8041 }
Chris Lattner46b96052006-11-29 07:18:39 +00008042 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008043 case Instruction::ZExt:
8044 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008045 case Instruction::Trunc:
8046 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008047 // can safely replace it. Note that replacing it does not reduce the number
8048 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008049 if (Opc == CastOpc)
8050 return true;
8051
8052 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008053 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008054 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008055 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008056 case Instruction::Select: {
8057 SelectInst *SI = cast<SelectInst>(I);
8058 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008059 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008060 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008061 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008062 }
Chris Lattner8114b712008-06-18 04:00:49 +00008063 case Instruction::PHI: {
8064 // We can change a phi if we can change all operands.
8065 PHINode *PN = cast<PHINode>(I);
8066 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8067 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008068 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008069 return false;
8070 return true;
8071 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008072 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008073 // TODO: Can handle more cases here.
8074 break;
8075 }
8076
8077 return false;
8078}
8079
8080/// EvaluateInDifferentType - Given an expression that
8081/// CanEvaluateInDifferentType returns true for, actually insert the code to
8082/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008083Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008084 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008085 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00008086 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00008087 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008088
8089 // Otherwise, it must be an instruction.
8090 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008091 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008092 unsigned Opc = I->getOpcode();
8093 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008094 case Instruction::Add:
8095 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008096 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008097 case Instruction::And:
8098 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008099 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008100 case Instruction::AShr:
8101 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008102 case Instruction::Shl:
8103 case Instruction::UDiv:
8104 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008105 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008106 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008107 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008108 break;
8109 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008110 case Instruction::Trunc:
8111 case Instruction::ZExt:
8112 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008113 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008114 // just return the source. There's no need to insert it because it is not
8115 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008116 if (I->getOperand(0)->getType() == Ty)
8117 return I->getOperand(0);
8118
Chris Lattner8114b712008-06-18 04:00:49 +00008119 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008120 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008121 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008122 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008123 case Instruction::Select: {
8124 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8125 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8126 Res = SelectInst::Create(I->getOperand(0), True, False);
8127 break;
8128 }
Chris Lattner8114b712008-06-18 04:00:49 +00008129 case Instruction::PHI: {
8130 PHINode *OPN = cast<PHINode>(I);
8131 PHINode *NPN = PHINode::Create(Ty);
8132 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8133 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8134 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8135 }
8136 Res = NPN;
8137 break;
8138 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008139 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008140 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008141 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008142 break;
8143 }
8144
Chris Lattner8114b712008-06-18 04:00:49 +00008145 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008146 return InsertNewInstBefore(Res, *I);
8147}
8148
Reid Spencer3da59db2006-11-27 01:05:10 +00008149/// @brief Implement the transforms common to all CastInst visitors.
8150Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008151 Value *Src = CI.getOperand(0);
8152
Dan Gohman23d9d272007-05-11 21:10:54 +00008153 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008154 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008155 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008156 if (Instruction::CastOps opc =
8157 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8158 // The first cast (CSrc) is eliminable so we need to fix up or replace
8159 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008160 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008161 }
8162 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008163
Reid Spencer3da59db2006-11-27 01:05:10 +00008164 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008165 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8166 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8167 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008168
8169 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008170 if (isa<PHINode>(Src))
8171 if (Instruction *NV = FoldOpIntoPhi(CI))
8172 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008173
Reid Spencer3da59db2006-11-27 01:05:10 +00008174 return 0;
8175}
8176
Chris Lattner46cd5a12009-01-09 05:44:56 +00008177/// FindElementAtOffset - Given a type and a constant offset, determine whether
8178/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008179/// the specified offset. If so, fill them into NewIndices and return the
8180/// resultant element type, otherwise return null.
8181static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8182 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008183 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008184 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008185 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008186 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008187
8188 // Start with the index over the outer type. Note that the type size
8189 // might be zero (even if the offset isn't zero) if the indexed type
8190 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008191 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008192 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008193 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008194 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008195 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008196
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008197 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008198 if (Offset < 0) {
8199 --FirstIdx;
8200 Offset += TySize;
8201 assert(Offset >= 0);
8202 }
8203 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8204 }
8205
Owen Andersoneed707b2009-07-24 23:12:02 +00008206 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008207
8208 // Index into the types. If we fail, set OrigBase to null.
8209 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008210 // Indexing into tail padding between struct/array elements.
8211 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008212 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008213
Chris Lattner46cd5a12009-01-09 05:44:56 +00008214 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8215 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008216 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8217 "Offset must stay within the indexed type");
8218
Chris Lattner46cd5a12009-01-09 05:44:56 +00008219 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008220 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008221
8222 Offset -= SL->getElementOffset(Elt);
8223 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008224 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008225 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008226 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008227 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008228 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008229 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008230 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008231 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008232 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008233 }
8234 }
8235
Chris Lattner3914f722009-01-24 01:00:13 +00008236 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008237}
8238
Chris Lattnerd3e28342007-04-27 17:44:50 +00008239/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8240Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8241 Value *Src = CI.getOperand(0);
8242
Chris Lattnerd3e28342007-04-27 17:44:50 +00008243 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008244 // If casting the result of a getelementptr instruction with no offset, turn
8245 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008246 if (GEP->hasAllZeroIndices()) {
8247 // Changing the cast operand is usually not a good idea but it is safe
8248 // here because the pointer operand is being replaced with another
8249 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008250 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008251 CI.setOperand(0, GEP->getOperand(0));
8252 return &CI;
8253 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008254
8255 // If the GEP has a single use, and the base pointer is a bitcast, and the
8256 // GEP computes a constant offset, see if we can convert these three
8257 // instructions into fewer. This typically happens with unions and other
8258 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008259 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008260 if (GEP->hasAllConstantIndices()) {
8261 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00008262 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008263 int64_t Offset = OffsetV->getSExtValue();
8264
8265 // Get the base pointer input of the bitcast, and the type it points to.
8266 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8267 const Type *GEPIdxTy =
8268 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008269 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008270 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008271 // If we were able to index down into an element, create the GEP
8272 // and bitcast the result. This eliminates one bitcast, potentially
8273 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008274 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8275 Builder->CreateInBoundsGEP(OrigBase,
8276 NewIndices.begin(), NewIndices.end()) :
8277 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008278 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008279
Chris Lattner46cd5a12009-01-09 05:44:56 +00008280 if (isa<BitCastInst>(CI))
8281 return new BitCastInst(NGEP, CI.getType());
8282 assert(isa<PtrToIntInst>(CI));
8283 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008284 }
8285 }
8286 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008287 }
8288
8289 return commonCastTransforms(CI);
8290}
8291
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008292/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8293/// type like i42. We don't want to introduce operations on random non-legal
8294/// integer types where they don't already exist in the code. In the future,
8295/// we should consider making this based off target-data, so that 32-bit targets
8296/// won't get i64 operations etc.
8297static bool isSafeIntegerType(const Type *Ty) {
8298 switch (Ty->getPrimitiveSizeInBits()) {
8299 case 8:
8300 case 16:
8301 case 32:
8302 case 64:
8303 return true;
8304 default:
8305 return false;
8306 }
8307}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008308
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008309/// commonIntCastTransforms - This function implements the common transforms
8310/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008311Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8312 if (Instruction *Result = commonCastTransforms(CI))
8313 return Result;
8314
8315 Value *Src = CI.getOperand(0);
8316 const Type *SrcTy = Src->getType();
8317 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008318 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8319 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008320
Reid Spencer3da59db2006-11-27 01:05:10 +00008321 // See if we can simplify any instructions used by the LHS whose sole
8322 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008323 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008324 return &CI;
8325
8326 // If the source isn't an instruction or has more than one use then we
8327 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008328 Instruction *SrcI = dyn_cast<Instruction>(Src);
8329 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008330 return 0;
8331
Chris Lattnerc739cd62007-03-03 05:27:34 +00008332 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008333 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008334 // Only do this if the dest type is a simple type, don't convert the
8335 // expression tree to something weird like i93 unless the source is also
8336 // strange.
8337 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008338 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8339 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008340 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008341 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008342 // eliminates the cast, so it is always a win. If this is a zero-extension,
8343 // we need to do an AND to maintain the clear top-part of the computation,
8344 // so we require that the input have eliminated at least one cast. If this
8345 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008346 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008347 bool DoXForm = false;
8348 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008349 switch (CI.getOpcode()) {
8350 default:
8351 // All the others use floating point so we shouldn't actually
8352 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008353 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008354 case Instruction::Trunc:
8355 DoXForm = true;
8356 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008357 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008358 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008359 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008360 // If it's unnecessary to issue an AND to clear the high bits, it's
8361 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008362 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008363 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8364 if (MaskedValueIsZero(TryRes, Mask))
8365 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008366
8367 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008368 if (TryI->use_empty())
8369 EraseInstFromFunction(*TryI);
8370 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008371 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008372 }
Evan Chengf35fd542009-01-15 17:01:23 +00008373 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008374 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008375 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008376 // If we do not have to emit the truncate + sext pair, then it's always
8377 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008378 //
8379 // It's not safe to eliminate the trunc + sext pair if one of the
8380 // eliminated cast is a truncate. e.g.
8381 // t2 = trunc i32 t1 to i16
8382 // t3 = sext i16 t2 to i32
8383 // !=
8384 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008385 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008386 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8387 if (NumSignBits > (DestBitSize - SrcBitSize))
8388 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008389
8390 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008391 if (TryI->use_empty())
8392 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008393 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008394 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008395 }
Evan Chengf35fd542009-01-15 17:01:23 +00008396 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008397
8398 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008399 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8400 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008401 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8402 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008403 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008404 // Just replace this cast with the result.
8405 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008406
Reid Spencer3da59db2006-11-27 01:05:10 +00008407 assert(Res->getType() == DestTy);
8408 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008409 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008410 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008411 // Just replace this cast with the result.
8412 return ReplaceInstUsesWith(CI, Res);
8413 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008414 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008415
8416 // If the high bits are already zero, just replace this cast with the
8417 // result.
8418 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8419 if (MaskedValueIsZero(Res, Mask))
8420 return ReplaceInstUsesWith(CI, Res);
8421
8422 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008423 Constant *C = ConstantInt::get(*Context,
8424 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008425 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008426 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008427 case Instruction::SExt: {
8428 // If the high bits are already filled with sign bit, just replace this
8429 // cast with the result.
8430 unsigned NumSignBits = ComputeNumSignBits(Res);
8431 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008432 return ReplaceInstUsesWith(CI, Res);
8433
Reid Spencer3da59db2006-11-27 01:05:10 +00008434 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008435 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008436 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008437 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008438 }
8439 }
8440
8441 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8442 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8443
8444 switch (SrcI->getOpcode()) {
8445 case Instruction::Add:
8446 case Instruction::Mul:
8447 case Instruction::And:
8448 case Instruction::Or:
8449 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008450 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008451 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8452 // Don't insert two casts unless at least one can be eliminated.
8453 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008454 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008455 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8456 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008457 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008458 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008459 }
8460 }
8461
8462 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8463 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8464 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008465 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008466 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008467 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008468 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008469 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008470 }
8471 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008472
Eli Friedman65445c52009-07-13 21:45:57 +00008473 case Instruction::Shl: {
8474 // Canonicalize trunc inside shl, if we can.
8475 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8476 if (CI && DestBitSize < SrcBitSize &&
8477 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008478 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8479 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008480 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008481 }
8482 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008483 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008484 }
8485 return 0;
8486}
8487
Chris Lattner8a9f5712007-04-11 06:57:46 +00008488Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008489 if (Instruction *Result = commonIntCastTransforms(CI))
8490 return Result;
8491
8492 Value *Src = CI.getOperand(0);
8493 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008494 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8495 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008496
8497 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008498 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008499 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008500 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008501 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008502 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008503 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008504
Chris Lattner4f9797d2009-03-24 18:15:30 +00008505 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8506 ConstantInt *ShAmtV = 0;
8507 Value *ShiftOp = 0;
8508 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008509 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008510 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8511
8512 // Get a mask for the bits shifting in.
8513 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8514 if (MaskedValueIsZero(ShiftOp, Mask)) {
8515 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008516 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008517
8518 // Okay, we can shrink this. Truncate the input, then return a new
8519 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008520 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008521 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008522 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008523 }
8524 }
8525
8526 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008527}
8528
Evan Chengb98a10e2008-03-24 00:21:34 +00008529/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8530/// in order to eliminate the icmp.
8531Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8532 bool DoXform) {
8533 // If we are just checking for a icmp eq of a single bit and zext'ing it
8534 // to an integer, then shift the bit to the appropriate place and then
8535 // cast to integer to avoid the comparison.
8536 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8537 const APInt &Op1CV = Op1C->getValue();
8538
8539 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8540 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8541 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8542 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8543 if (!DoXform) return ICI;
8544
8545 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008546 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008547 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008548 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008549 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008550 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008551
8552 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008553 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008554 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008555 }
8556
8557 return ReplaceInstUsesWith(CI, In);
8558 }
8559
8560
8561
8562 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8563 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8564 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8565 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8566 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8567 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8568 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8569 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8570 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8571 // This only works for EQ and NE
8572 ICI->isEquality()) {
8573 // If Op1C some other power of two, convert:
8574 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8575 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8576 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8577 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8578
8579 APInt KnownZeroMask(~KnownZero);
8580 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8581 if (!DoXform) return ICI;
8582
8583 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8584 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8585 // (X&4) == 2 --> false
8586 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008587 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008588 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008589 return ReplaceInstUsesWith(CI, Res);
8590 }
8591
8592 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8593 Value *In = ICI->getOperand(0);
8594 if (ShiftAmt) {
8595 // Perform a logical shr by shiftamt.
8596 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008597 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8598 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008599 }
8600
8601 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008602 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008603 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008604 }
8605
8606 if (CI.getType() == In->getType())
8607 return ReplaceInstUsesWith(CI, In);
8608 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008609 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008610 }
8611 }
8612 }
8613
8614 return 0;
8615}
8616
Chris Lattner8a9f5712007-04-11 06:57:46 +00008617Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008618 // If one of the common conversion will work ..
8619 if (Instruction *Result = commonIntCastTransforms(CI))
8620 return Result;
8621
8622 Value *Src = CI.getOperand(0);
8623
Chris Lattnera84f47c2009-02-17 20:47:23 +00008624 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8625 // types and if the sizes are just right we can convert this into a logical
8626 // 'and' which will be much cheaper than the pair of casts.
8627 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8628 // Get the sizes of the types involved. We know that the intermediate type
8629 // will be smaller than A or C, but don't know the relation between A and C.
8630 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008631 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8632 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8633 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008634 // If we're actually extending zero bits, then if
8635 // SrcSize < DstSize: zext(a & mask)
8636 // SrcSize == DstSize: a & mask
8637 // SrcSize > DstSize: trunc(a) & mask
8638 if (SrcSize < DstSize) {
8639 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008640 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008641 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008642 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008643 }
8644
8645 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008646 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008647 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008648 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008649 }
8650 if (SrcSize > DstSize) {
8651 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008652 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008653 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008654 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008655 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008656 }
8657 }
8658
Evan Chengb98a10e2008-03-24 00:21:34 +00008659 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8660 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008661
Evan Chengb98a10e2008-03-24 00:21:34 +00008662 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8663 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8664 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8665 // of the (zext icmp) will be transformed.
8666 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8667 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8668 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8669 (transformZExtICmp(LHS, CI, false) ||
8670 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008671 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8672 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008673 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008674 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008675 }
8676
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008677 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008678 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8679 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8680 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8681 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008682 if (TI0->getType() == CI.getType())
8683 return
8684 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008685 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008686 }
8687
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008688 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8689 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8690 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8691 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8692 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8693 And->getOperand(1) == C)
8694 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8695 Value *TI0 = TI->getOperand(0);
8696 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008697 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008698 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008699 return BinaryOperator::CreateXor(NewAnd, ZC);
8700 }
8701 }
8702
Reid Spencer3da59db2006-11-27 01:05:10 +00008703 return 0;
8704}
8705
Chris Lattner8a9f5712007-04-11 06:57:46 +00008706Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008707 if (Instruction *I = commonIntCastTransforms(CI))
8708 return I;
8709
Chris Lattner8a9f5712007-04-11 06:57:46 +00008710 Value *Src = CI.getOperand(0);
8711
Dan Gohman1975d032008-10-30 20:40:10 +00008712 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008713 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008714 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008715 Constant::getAllOnesValue(CI.getType()),
8716 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008717
8718 // See if the value being truncated is already sign extended. If so, just
8719 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008720 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008721 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008722 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8723 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8724 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008725 unsigned NumSignBits = ComputeNumSignBits(Op);
8726
8727 if (OpBits == DestBits) {
8728 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8729 // bits, it is already ready.
8730 if (NumSignBits > DestBits-MidBits)
8731 return ReplaceInstUsesWith(CI, Op);
8732 } else if (OpBits < DestBits) {
8733 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8734 // bits, just sext from i32.
8735 if (NumSignBits > OpBits-MidBits)
8736 return new SExtInst(Op, CI.getType(), "tmp");
8737 } else {
8738 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8739 // bits, just truncate to i32.
8740 if (NumSignBits > OpBits-MidBits)
8741 return new TruncInst(Op, CI.getType(), "tmp");
8742 }
8743 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008744
8745 // If the input is a shl/ashr pair of a same constant, then this is a sign
8746 // extension from a smaller value. If we could trust arbitrary bitwidth
8747 // integers, we could turn this into a truncate to the smaller bit and then
8748 // use a sext for the whole extension. Since we don't, look deeper and check
8749 // for a truncate. If the source and dest are the same type, eliminate the
8750 // trunc and extend and just do shifts. For example, turn:
8751 // %a = trunc i32 %i to i8
8752 // %b = shl i8 %a, 6
8753 // %c = ashr i8 %b, 6
8754 // %d = sext i8 %c to i32
8755 // into:
8756 // %a = shl i32 %i, 30
8757 // %d = ashr i32 %a, 30
8758 Value *A = 0;
8759 ConstantInt *BA = 0, *CA = 0;
8760 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008761 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008762 BA == CA && isa<TruncInst>(A)) {
8763 Value *I = cast<TruncInst>(A)->getOperand(0);
8764 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008765 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8766 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008767 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008768 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008769 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008770 return BinaryOperator::CreateAShr(I, ShAmtV);
8771 }
8772 }
8773
Chris Lattnerba417832007-04-11 06:12:58 +00008774 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008775}
8776
Chris Lattnerb7530652008-01-27 05:29:54 +00008777/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8778/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008779static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008780 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008781 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008782 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008783 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8784 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008785 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008786 return 0;
8787}
8788
8789/// LookThroughFPExtensions - If this is an fp extension instruction, look
8790/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008791static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008792 if (Instruction *I = dyn_cast<Instruction>(V))
8793 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008794 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008795
8796 // If this value is a constant, return the constant in the smallest FP type
8797 // that can accurately represent it. This allows us to turn
8798 // (float)((double)X+2.0) into x+2.0f.
8799 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008800 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008801 return V; // No constant folding of this.
8802 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008803 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008804 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008805 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008806 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008807 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008808 return V;
8809 // Don't try to shrink to various long double types.
8810 }
8811
8812 return V;
8813}
8814
8815Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8816 if (Instruction *I = commonCastTransforms(CI))
8817 return I;
8818
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008819 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008820 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008821 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008822 // many builtins (sqrt, etc).
8823 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8824 if (OpI && OpI->hasOneUse()) {
8825 switch (OpI->getOpcode()) {
8826 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008827 case Instruction::FAdd:
8828 case Instruction::FSub:
8829 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008830 case Instruction::FDiv:
8831 case Instruction::FRem:
8832 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008833 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8834 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008835 if (LHSTrunc->getType() != SrcTy &&
8836 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008837 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008838 // If the source types were both smaller than the destination type of
8839 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008840 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8841 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008842 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8843 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008844 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008845 }
8846 }
8847 break;
8848 }
8849 }
8850 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008851}
8852
8853Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8854 return commonCastTransforms(CI);
8855}
8856
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008857Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008858 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8859 if (OpI == 0)
8860 return commonCastTransforms(FI);
8861
8862 // fptoui(uitofp(X)) --> X
8863 // fptoui(sitofp(X)) --> X
8864 // This is safe if the intermediate type has enough bits in its mantissa to
8865 // accurately represent all values of X. For example, do not do this with
8866 // i64->float->i64. This is also safe for sitofp case, because any negative
8867 // 'X' value would cause an undefined result for the fptoui.
8868 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8869 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008870 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008871 OpI->getType()->getFPMantissaWidth())
8872 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008873
8874 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008875}
8876
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008877Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008878 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8879 if (OpI == 0)
8880 return commonCastTransforms(FI);
8881
8882 // fptosi(sitofp(X)) --> X
8883 // fptosi(uitofp(X)) --> X
8884 // This is safe if the intermediate type has enough bits in its mantissa to
8885 // accurately represent all values of X. For example, do not do this with
8886 // i64->float->i64. This is also safe for sitofp case, because any negative
8887 // 'X' value would cause an undefined result for the fptoui.
8888 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8889 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008890 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008891 OpI->getType()->getFPMantissaWidth())
8892 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008893
8894 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008895}
8896
8897Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8898 return commonCastTransforms(CI);
8899}
8900
8901Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8902 return commonCastTransforms(CI);
8903}
8904
Chris Lattnera0e69692009-03-24 18:35:40 +00008905Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8906 // If the destination integer type is smaller than the intptr_t type for
8907 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8908 // trunc to be exposed to other transforms. Don't do this for extending
8909 // ptrtoint's, because we don't know if the target sign or zero extends its
8910 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008911 if (TD &&
8912 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008913 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8914 TD->getIntPtrType(CI.getContext()),
8915 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008916 return new TruncInst(P, CI.getType());
8917 }
8918
Chris Lattnerd3e28342007-04-27 17:44:50 +00008919 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008920}
8921
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008922Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008923 // If the source integer type is larger than the intptr_t type for
8924 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8925 // allows the trunc to be exposed to other transforms. Don't do this for
8926 // extending inttoptr's, because we don't know if the target sign or zero
8927 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008928 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008929 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008930 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8931 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008932 return new IntToPtrInst(P, CI.getType());
8933 }
8934
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008935 if (Instruction *I = commonCastTransforms(CI))
8936 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008937
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008938 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008939}
8940
Chris Lattnerd3e28342007-04-27 17:44:50 +00008941Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008942 // If the operands are integer typed then apply the integer transforms,
8943 // otherwise just apply the common ones.
8944 Value *Src = CI.getOperand(0);
8945 const Type *SrcTy = Src->getType();
8946 const Type *DestTy = CI.getType();
8947
Eli Friedman7e25d452009-07-13 20:53:00 +00008948 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008949 if (Instruction *I = commonPointerCastTransforms(CI))
8950 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008951 } else {
8952 if (Instruction *Result = commonCastTransforms(CI))
8953 return Result;
8954 }
8955
8956
8957 // Get rid of casts from one type to the same type. These are useless and can
8958 // be replaced by the operand.
8959 if (DestTy == Src->getType())
8960 return ReplaceInstUsesWith(CI, Src);
8961
Reid Spencer3da59db2006-11-27 01:05:10 +00008962 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008963 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8964 const Type *DstElTy = DstPTy->getElementType();
8965 const Type *SrcElTy = SrcPTy->getElementType();
8966
Nate Begeman83ad90a2008-03-31 00:22:16 +00008967 // If the address spaces don't match, don't eliminate the bitcast, which is
8968 // required for changing types.
8969 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8970 return 0;
8971
Victor Hernandez83d63912009-09-18 22:35:49 +00008972 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008973 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008974 // There is no need to modify malloc calls because it is their bitcast that
8975 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00008976 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00008977 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8978 return V;
8979
Chris Lattnerd717c182007-05-05 22:32:24 +00008980 // If the source and destination are pointers, and this cast is equivalent
8981 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008982 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008983 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008984 unsigned NumZeros = 0;
8985 while (SrcElTy != DstElTy &&
8986 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8987 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8988 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8989 ++NumZeros;
8990 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008991
Chris Lattnerd3e28342007-04-27 17:44:50 +00008992 // If we found a path from the src to dest, create the getelementptr now.
8993 if (SrcElTy == DstElTy) {
8994 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008995 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8996 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008997 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008998 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008999
Eli Friedman2451a642009-07-18 23:06:53 +00009000 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9001 if (DestVTy->getNumElements() == 1) {
9002 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009003 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009004 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00009005 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009006 }
9007 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9008 }
9009 }
9010
9011 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9012 if (SrcVTy->getNumElements() == 1) {
9013 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009014 Value *Elem =
9015 Builder->CreateExtractElement(Src,
9016 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009017 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9018 }
9019 }
9020 }
9021
Reid Spencer3da59db2006-11-27 01:05:10 +00009022 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9023 if (SVI->hasOneUse()) {
9024 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9025 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009026 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009027 cast<VectorType>(DestTy)->getNumElements() ==
9028 SVI->getType()->getNumElements() &&
9029 SVI->getType()->getNumElements() ==
9030 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009031 CastInst *Tmp;
9032 // If either of the operands is a cast from CI.getType(), then
9033 // evaluating the shuffle in the casted destination's type will allow
9034 // us to eliminate at least one cast.
9035 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9036 Tmp->getOperand(0)->getType() == DestTy) ||
9037 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9038 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009039 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9040 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00009041 // Return a new shuffle vector. Use the same element ID's, as we
9042 // know the vector types match #elts.
9043 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009044 }
9045 }
9046 }
9047 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009048 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009049}
9050
Chris Lattnere576b912004-04-09 23:46:01 +00009051/// GetSelectFoldableOperands - We want to turn code that looks like this:
9052/// %C = or %A, %B
9053/// %D = select %cond, %C, %A
9054/// into:
9055/// %C = select %cond, %B, 0
9056/// %D = or %A, %C
9057///
9058/// Assuming that the specified instruction is an operand to the select, return
9059/// a bitmask indicating which operands of this instruction are foldable if they
9060/// equal the other incoming value of the select.
9061///
9062static unsigned GetSelectFoldableOperands(Instruction *I) {
9063 switch (I->getOpcode()) {
9064 case Instruction::Add:
9065 case Instruction::Mul:
9066 case Instruction::And:
9067 case Instruction::Or:
9068 case Instruction::Xor:
9069 return 3; // Can fold through either operand.
9070 case Instruction::Sub: // Can only fold on the amount subtracted.
9071 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009072 case Instruction::LShr:
9073 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009074 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009075 default:
9076 return 0; // Cannot fold
9077 }
9078}
9079
9080/// GetSelectFoldableConstant - For the same transformation as the previous
9081/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009082static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009083 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009084 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009085 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009086 case Instruction::Add:
9087 case Instruction::Sub:
9088 case Instruction::Or:
9089 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009090 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009091 case Instruction::LShr:
9092 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009093 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009094 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009095 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009096 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009097 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009098 }
9099}
9100
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009101/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9102/// have the same opcode and only one use each. Try to simplify this.
9103Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9104 Instruction *FI) {
9105 if (TI->getNumOperands() == 1) {
9106 // If this is a non-volatile load or a cast from the same type,
9107 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009108 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009109 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9110 return 0;
9111 } else {
9112 return 0; // unknown unary op.
9113 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009114
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009115 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009116 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009117 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009118 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009119 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009120 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009121 }
9122
Reid Spencer832254e2007-02-02 02:16:23 +00009123 // Only handle binary operators here.
9124 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009125 return 0;
9126
9127 // Figure out if the operations have any operands in common.
9128 Value *MatchOp, *OtherOpT, *OtherOpF;
9129 bool MatchIsOpZero;
9130 if (TI->getOperand(0) == FI->getOperand(0)) {
9131 MatchOp = TI->getOperand(0);
9132 OtherOpT = TI->getOperand(1);
9133 OtherOpF = FI->getOperand(1);
9134 MatchIsOpZero = true;
9135 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9136 MatchOp = TI->getOperand(1);
9137 OtherOpT = TI->getOperand(0);
9138 OtherOpF = FI->getOperand(0);
9139 MatchIsOpZero = false;
9140 } else if (!TI->isCommutative()) {
9141 return 0;
9142 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9143 MatchOp = TI->getOperand(0);
9144 OtherOpT = TI->getOperand(1);
9145 OtherOpF = FI->getOperand(0);
9146 MatchIsOpZero = true;
9147 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9148 MatchOp = TI->getOperand(1);
9149 OtherOpT = TI->getOperand(0);
9150 OtherOpF = FI->getOperand(1);
9151 MatchIsOpZero = true;
9152 } else {
9153 return 0;
9154 }
9155
9156 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009157 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9158 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009159 InsertNewInstBefore(NewSI, SI);
9160
9161 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9162 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009163 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009164 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009165 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009166 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009167 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009168 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009169}
9170
Evan Chengde621922009-03-31 20:42:45 +00009171static bool isSelect01(Constant *C1, Constant *C2) {
9172 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9173 if (!C1I)
9174 return false;
9175 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9176 if (!C2I)
9177 return false;
9178 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9179}
9180
9181/// FoldSelectIntoOp - Try fold the select into one of the operands to
9182/// facilitate further optimization.
9183Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9184 Value *FalseVal) {
9185 // See the comment above GetSelectFoldableOperands for a description of the
9186 // transformation we are doing here.
9187 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9188 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9189 !isa<Constant>(FalseVal)) {
9190 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9191 unsigned OpToFold = 0;
9192 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9193 OpToFold = 1;
9194 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9195 OpToFold = 2;
9196 }
9197
9198 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009199 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009200 Value *OOp = TVI->getOperand(2-OpToFold);
9201 // Avoid creating select between 2 constants unless it's selecting
9202 // between 0 and 1.
9203 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9204 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9205 InsertNewInstBefore(NewSel, SI);
9206 NewSel->takeName(TVI);
9207 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9208 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009209 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009210 }
9211 }
9212 }
9213 }
9214 }
9215
9216 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9217 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9218 !isa<Constant>(TrueVal)) {
9219 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9220 unsigned OpToFold = 0;
9221 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9222 OpToFold = 1;
9223 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9224 OpToFold = 2;
9225 }
9226
9227 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009228 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009229 Value *OOp = FVI->getOperand(2-OpToFold);
9230 // Avoid creating select between 2 constants unless it's selecting
9231 // between 0 and 1.
9232 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9233 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9234 InsertNewInstBefore(NewSel, SI);
9235 NewSel->takeName(FVI);
9236 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9237 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009238 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009239 }
9240 }
9241 }
9242 }
9243 }
9244
9245 return 0;
9246}
9247
Dan Gohman81b28ce2008-09-16 18:46:06 +00009248/// visitSelectInstWithICmp - Visit a SelectInst that has an
9249/// ICmpInst as its first operand.
9250///
9251Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9252 ICmpInst *ICI) {
9253 bool Changed = false;
9254 ICmpInst::Predicate Pred = ICI->getPredicate();
9255 Value *CmpLHS = ICI->getOperand(0);
9256 Value *CmpRHS = ICI->getOperand(1);
9257 Value *TrueVal = SI.getTrueValue();
9258 Value *FalseVal = SI.getFalseValue();
9259
9260 // Check cases where the comparison is with a constant that
9261 // can be adjusted to fit the min/max idiom. We may edit ICI in
9262 // place here, so make sure the select is the only user.
9263 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009264 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009265 switch (Pred) {
9266 default: break;
9267 case ICmpInst::ICMP_ULT:
9268 case ICmpInst::ICMP_SLT: {
9269 // X < MIN ? T : F --> F
9270 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9271 return ReplaceInstUsesWith(SI, FalseVal);
9272 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009273 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009274 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9275 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9276 Pred = ICmpInst::getSwappedPredicate(Pred);
9277 CmpRHS = AdjustedRHS;
9278 std::swap(FalseVal, TrueVal);
9279 ICI->setPredicate(Pred);
9280 ICI->setOperand(1, CmpRHS);
9281 SI.setOperand(1, TrueVal);
9282 SI.setOperand(2, FalseVal);
9283 Changed = true;
9284 }
9285 break;
9286 }
9287 case ICmpInst::ICMP_UGT:
9288 case ICmpInst::ICMP_SGT: {
9289 // X > MAX ? T : F --> F
9290 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9291 return ReplaceInstUsesWith(SI, FalseVal);
9292 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009293 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009294 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9295 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9296 Pred = ICmpInst::getSwappedPredicate(Pred);
9297 CmpRHS = AdjustedRHS;
9298 std::swap(FalseVal, TrueVal);
9299 ICI->setPredicate(Pred);
9300 ICI->setOperand(1, CmpRHS);
9301 SI.setOperand(1, TrueVal);
9302 SI.setOperand(2, FalseVal);
9303 Changed = true;
9304 }
9305 break;
9306 }
9307 }
9308
Dan Gohman1975d032008-10-30 20:40:10 +00009309 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9310 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009311 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009312 if (match(TrueVal, m_ConstantInt<-1>()) &&
9313 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009314 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009315 else if (match(TrueVal, m_ConstantInt<0>()) &&
9316 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009317 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9318
Dan Gohman1975d032008-10-30 20:40:10 +00009319 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9320 // If we are just checking for a icmp eq of a single bit and zext'ing it
9321 // to an integer, then shift the bit to the appropriate place and then
9322 // cast to integer to avoid the comparison.
9323 const APInt &Op1CV = CI->getValue();
9324
9325 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9326 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9327 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009328 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009329 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009330 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009331 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009332 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009333 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009334 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009335 if (In->getType() != SI.getType())
9336 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009337 true/*SExt*/, "tmp", ICI);
9338
9339 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009340 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009341 In->getName()+".not"), *ICI);
9342
9343 return ReplaceInstUsesWith(SI, In);
9344 }
9345 }
9346 }
9347
Dan Gohman81b28ce2008-09-16 18:46:06 +00009348 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9349 // Transform (X == Y) ? X : Y -> Y
9350 if (Pred == ICmpInst::ICMP_EQ)
9351 return ReplaceInstUsesWith(SI, FalseVal);
9352 // Transform (X != Y) ? X : Y -> X
9353 if (Pred == ICmpInst::ICMP_NE)
9354 return ReplaceInstUsesWith(SI, TrueVal);
9355 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9356
9357 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9358 // Transform (X == Y) ? Y : X -> X
9359 if (Pred == ICmpInst::ICMP_EQ)
9360 return ReplaceInstUsesWith(SI, FalseVal);
9361 // Transform (X != Y) ? Y : X -> Y
9362 if (Pred == ICmpInst::ICMP_NE)
9363 return ReplaceInstUsesWith(SI, TrueVal);
9364 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9365 }
9366
9367 /// NOTE: if we wanted to, this is where to detect integer ABS
9368
9369 return Changed ? &SI : 0;
9370}
9371
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009372
Chris Lattner7f239582009-10-22 00:17:26 +00009373/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9374/// PHI node (but the two may be in different blocks). See if the true/false
9375/// values (V) are live in all of the predecessor blocks of the PHI. For
9376/// example, cases like this cannot be mapped:
9377///
9378/// X = phi [ C1, BB1], [C2, BB2]
9379/// Y = add
9380/// Z = select X, Y, 0
9381///
9382/// because Y is not live in BB1/BB2.
9383///
9384static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9385 const SelectInst &SI) {
9386 // If the value is a non-instruction value like a constant or argument, it
9387 // can always be mapped.
9388 const Instruction *I = dyn_cast<Instruction>(V);
9389 if (I == 0) return true;
9390
9391 // If V is a PHI node defined in the same block as the condition PHI, we can
9392 // map the arguments.
9393 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9394
9395 if (const PHINode *VP = dyn_cast<PHINode>(I))
9396 if (VP->getParent() == CondPHI->getParent())
9397 return true;
9398
9399 // Otherwise, if the PHI and select are defined in the same block and if V is
9400 // defined in a different block, then we can transform it.
9401 if (SI.getParent() == CondPHI->getParent() &&
9402 I->getParent() != CondPHI->getParent())
9403 return true;
9404
9405 // Otherwise we have a 'hard' case and we can't tell without doing more
9406 // detailed dominator based analysis, punt.
9407 return false;
9408}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009409
Chris Lattner3d69f462004-03-12 05:52:32 +00009410Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009411 Value *CondVal = SI.getCondition();
9412 Value *TrueVal = SI.getTrueValue();
9413 Value *FalseVal = SI.getFalseValue();
9414
9415 // select true, X, Y -> X
9416 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009417 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009418 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009419
9420 // select C, X, X -> X
9421 if (TrueVal == FalseVal)
9422 return ReplaceInstUsesWith(SI, TrueVal);
9423
Chris Lattnere87597f2004-10-16 18:11:37 +00009424 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9425 return ReplaceInstUsesWith(SI, FalseVal);
9426 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9427 return ReplaceInstUsesWith(SI, TrueVal);
9428 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9429 if (isa<Constant>(TrueVal))
9430 return ReplaceInstUsesWith(SI, TrueVal);
9431 else
9432 return ReplaceInstUsesWith(SI, FalseVal);
9433 }
9434
Owen Anderson1d0be152009-08-13 21:58:54 +00009435 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009436 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009437 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009438 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009439 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009440 } else {
9441 // Change: A = select B, false, C --> A = and !B, C
9442 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009443 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009444 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009445 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009446 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009447 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009448 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009449 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009450 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009451 } else {
9452 // Change: A = select B, C, true --> A = or !B, C
9453 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009454 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009455 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009456 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009457 }
9458 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009459
9460 // select a, b, a -> a&b
9461 // select a, a, b -> a|b
9462 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009463 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009464 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009465 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009466 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009467
Chris Lattner2eefe512004-04-09 19:05:30 +00009468 // Selecting between two integer constants?
9469 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9470 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009471 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009472 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009473 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009474 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009475 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009476 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009477 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009478 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009479 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009480 }
Chris Lattner457dd822004-06-09 07:59:58 +00009481
Reid Spencere4d87aa2006-12-23 06:05:41 +00009482 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009483 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009484 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009485 // non-constant value, eliminate this whole mess. This corresponds to
9486 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009487 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009488 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009489 cast<Constant>(IC->getOperand(1))->isNullValue())
9490 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9491 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009492 isa<ConstantInt>(ICA->getOperand(1)) &&
9493 (ICA->getOperand(1) == TrueValC ||
9494 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009495 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9496 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009497 // know whether we have a icmp_ne or icmp_eq and whether the
9498 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009499 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009500 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009501 Value *V = ICA;
9502 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009503 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009504 Instruction::Xor, V, ICA->getOperand(1)), SI);
9505 return ReplaceInstUsesWith(SI, V);
9506 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009507 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009508 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009509
9510 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009511 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9512 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009513 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009514 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9515 // This is not safe in general for floating point:
9516 // consider X== -0, Y== +0.
9517 // It becomes safe if either operand is a nonzero constant.
9518 ConstantFP *CFPt, *CFPf;
9519 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9520 !CFPt->getValueAPF().isZero()) ||
9521 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9522 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009523 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009524 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009525 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009526 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009527 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009528 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009529
Reid Spencere4d87aa2006-12-23 06:05:41 +00009530 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009531 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009532 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9533 // This is not safe in general for floating point:
9534 // consider X== -0, Y== +0.
9535 // It becomes safe if either operand is a nonzero constant.
9536 ConstantFP *CFPt, *CFPf;
9537 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9538 !CFPt->getValueAPF().isZero()) ||
9539 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9540 !CFPf->getValueAPF().isZero()))
9541 return ReplaceInstUsesWith(SI, FalseVal);
9542 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009543 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009544 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9545 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009546 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009547 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009548 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009549 }
9550
9551 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009552 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9553 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9554 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009555
Chris Lattner87875da2005-01-13 22:52:24 +00009556 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9557 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9558 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009559 Instruction *AddOp = 0, *SubOp = 0;
9560
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009561 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9562 if (TI->getOpcode() == FI->getOpcode())
9563 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9564 return IV;
9565
9566 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9567 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009568 if ((TI->getOpcode() == Instruction::Sub &&
9569 FI->getOpcode() == Instruction::Add) ||
9570 (TI->getOpcode() == Instruction::FSub &&
9571 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009572 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009573 } else if ((FI->getOpcode() == Instruction::Sub &&
9574 TI->getOpcode() == Instruction::Add) ||
9575 (FI->getOpcode() == Instruction::FSub &&
9576 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009577 AddOp = TI; SubOp = FI;
9578 }
9579
9580 if (AddOp) {
9581 Value *OtherAddOp = 0;
9582 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9583 OtherAddOp = AddOp->getOperand(1);
9584 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9585 OtherAddOp = AddOp->getOperand(0);
9586 }
9587
9588 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009589 // So at this point we know we have (Y -> OtherAddOp):
9590 // select C, (add X, Y), (sub X, Z)
9591 Value *NegVal; // Compute -Z
9592 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009593 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009594 } else {
9595 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009596 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009597 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009598 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009599
9600 Value *NewTrueOp = OtherAddOp;
9601 Value *NewFalseOp = NegVal;
9602 if (AddOp != TI)
9603 std::swap(NewTrueOp, NewFalseOp);
9604 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009605 SelectInst::Create(CondVal, NewTrueOp,
9606 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009607
9608 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009609 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009610 }
9611 }
9612 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009613
Chris Lattnere576b912004-04-09 23:46:01 +00009614 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009615 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009616 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9617 if (FoldI)
9618 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009619 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009620
Chris Lattner7f239582009-10-22 00:17:26 +00009621 // See if we can fold the select into a phi node if the condition is a select.
9622 if (isa<PHINode>(SI.getCondition()))
9623 // The true/false values have to be live in the PHI predecessor's blocks.
9624 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9625 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9626 if (Instruction *NV = FoldOpIntoPhi(SI))
9627 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00009628
Chris Lattnera1df33c2005-04-24 07:30:14 +00009629 if (BinaryOperator::isNot(CondVal)) {
9630 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9631 SI.setOperand(1, FalseVal);
9632 SI.setOperand(2, TrueVal);
9633 return &SI;
9634 }
9635
Chris Lattner3d69f462004-03-12 05:52:32 +00009636 return 0;
9637}
9638
Dan Gohmaneee962e2008-04-10 18:43:06 +00009639/// EnforceKnownAlignment - If the specified pointer points to an object that
9640/// we control, modify the object's alignment to PrefAlign. This isn't
9641/// often possible though. If alignment is important, a more reliable approach
9642/// is to simply align all global variables and allocation instructions to
9643/// their preferred alignment from the beginning.
9644///
9645static unsigned EnforceKnownAlignment(Value *V,
9646 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009647
Dan Gohmaneee962e2008-04-10 18:43:06 +00009648 User *U = dyn_cast<User>(V);
9649 if (!U) return Align;
9650
Dan Gohmanca178902009-07-17 20:47:02 +00009651 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009652 default: break;
9653 case Instruction::BitCast:
9654 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9655 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009656 // If all indexes are zero, it is just the alignment of the base pointer.
9657 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009658 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009659 if (!isa<Constant>(*i) ||
9660 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009661 AllZeroOperands = false;
9662 break;
9663 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009664
9665 if (AllZeroOperands) {
9666 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009667 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009668 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009669 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009670 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009671 }
9672
9673 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9674 // If there is a large requested alignment and we can, bump up the alignment
9675 // of the global.
9676 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009677 if (GV->getAlignment() >= PrefAlign)
9678 Align = GV->getAlignment();
9679 else {
9680 GV->setAlignment(PrefAlign);
9681 Align = PrefAlign;
9682 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009683 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009684 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9685 // If there is a requested alignment and if this is an alloca, round up.
9686 if (AI->getAlignment() >= PrefAlign)
9687 Align = AI->getAlignment();
9688 else {
9689 AI->setAlignment(PrefAlign);
9690 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009691 }
9692 }
9693
9694 return Align;
9695}
9696
9697/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9698/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9699/// and it is more than the alignment of the ultimate object, see if we can
9700/// increase the alignment of the ultimate object, making this check succeed.
9701unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9702 unsigned PrefAlign) {
9703 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9704 sizeof(PrefAlign) * CHAR_BIT;
9705 APInt Mask = APInt::getAllOnesValue(BitWidth);
9706 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9707 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9708 unsigned TrailZ = KnownZero.countTrailingOnes();
9709 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9710
9711 if (PrefAlign > Align)
9712 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9713
9714 // We don't need to make any adjustment.
9715 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009716}
9717
Chris Lattnerf497b022008-01-13 23:50:23 +00009718Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009719 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009720 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009721 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009722 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009723
9724 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009725 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009726 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009727 return MI;
9728 }
9729
9730 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9731 // load/store.
9732 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9733 if (MemOpLength == 0) return 0;
9734
Chris Lattner37ac6082008-01-14 00:28:35 +00009735 // Source and destination pointer types are always "i8*" for intrinsic. See
9736 // if the size is something we can handle with a single primitive load/store.
9737 // A single load+store correctly handles overlapping memory in the memmove
9738 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009739 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009740 if (Size == 0) return MI; // Delete this mem transfer.
9741
9742 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009743 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009744
Chris Lattner37ac6082008-01-14 00:28:35 +00009745 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009746 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009747 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009748
9749 // Memcpy forces the use of i8* for the source and destination. That means
9750 // that if you're using memcpy to move one double around, you'll get a cast
9751 // from double* to i8*. We'd much rather use a double load+store rather than
9752 // an i64 load+store, here because this improves the odds that the source or
9753 // dest address will be promotable. See if we can find a better type than the
9754 // integer datatype.
9755 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9756 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009757 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009758 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9759 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009760 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009761 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9762 if (STy->getNumElements() == 1)
9763 SrcETy = STy->getElementType(0);
9764 else
9765 break;
9766 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9767 if (ATy->getNumElements() == 1)
9768 SrcETy = ATy->getElementType();
9769 else
9770 break;
9771 } else
9772 break;
9773 }
9774
Dan Gohman8f8e2692008-05-23 01:52:21 +00009775 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009776 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009777 }
9778 }
9779
9780
Chris Lattnerf497b022008-01-13 23:50:23 +00009781 // If the memcpy/memmove provides better alignment info than we can
9782 // infer, use it.
9783 SrcAlign = std::max(SrcAlign, CopyAlign);
9784 DstAlign = std::max(DstAlign, CopyAlign);
9785
Chris Lattner08142f22009-08-30 19:47:22 +00009786 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9787 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009788 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9789 InsertNewInstBefore(L, *MI);
9790 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9791
9792 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009793 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009794 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009795}
Chris Lattner3d69f462004-03-12 05:52:32 +00009796
Chris Lattner69ea9d22008-04-30 06:39:11 +00009797Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9798 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009799 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009800 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009801 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009802 return MI;
9803 }
9804
9805 // Extract the length and alignment and fill if they are constant.
9806 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9807 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009808 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009809 return 0;
9810 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009811 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009812
9813 // If the length is zero, this is a no-op
9814 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9815
9816 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9817 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009818 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009819
9820 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009821 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009822
9823 // Alignment 0 is identity for alignment 1 for memset, but not store.
9824 if (Alignment == 0) Alignment = 1;
9825
9826 // Extract the fill value and store.
9827 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009828 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009829 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009830
9831 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009832 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009833 return MI;
9834 }
9835
9836 return 0;
9837}
9838
9839
Chris Lattner8b0ea312006-01-13 20:11:04 +00009840/// visitCallInst - CallInst simplification. This mostly only handles folding
9841/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9842/// the heavy lifting.
9843///
Chris Lattner9fe38862003-06-19 17:00:31 +00009844Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00009845 if (isFreeCall(&CI))
9846 return visitFree(CI);
9847
Chris Lattneraab6ec42009-05-13 17:39:14 +00009848 // If the caller function is nounwind, mark the call as nounwind, even if the
9849 // callee isn't.
9850 if (CI.getParent()->getParent()->doesNotThrow() &&
9851 !CI.doesNotThrow()) {
9852 CI.setDoesNotThrow();
9853 return &CI;
9854 }
9855
Chris Lattner8b0ea312006-01-13 20:11:04 +00009856 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9857 if (!II) return visitCallSite(&CI);
9858
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009859 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9860 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009861 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009862 bool Changed = false;
9863
9864 // memmove/cpy/set of zero bytes is a noop.
9865 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9866 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9867
Chris Lattner35b9e482004-10-12 04:52:52 +00009868 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009869 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009870 // Replace the instruction with just byte operations. We would
9871 // transform other cases to loads/stores, but we don't know if
9872 // alignment is sufficient.
9873 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009874 }
9875
Chris Lattner35b9e482004-10-12 04:52:52 +00009876 // If we have a memmove and the source operation is a constant global,
9877 // then the source and dest pointers can't alias, so we can change this
9878 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009879 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009880 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9881 if (GVSrc->isConstant()) {
9882 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009883 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9884 const Type *Tys[1];
9885 Tys[0] = CI.getOperand(3)->getType();
9886 CI.setOperand(0,
9887 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009888 Changed = true;
9889 }
Chris Lattnera935db82008-05-28 05:30:41 +00009890
9891 // memmove(x,x,size) -> noop.
9892 if (MMI->getSource() == MMI->getDest())
9893 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009894 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009895
Chris Lattner95a959d2006-03-06 20:18:44 +00009896 // If we can determine a pointer alignment that is bigger than currently
9897 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009898 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009899 if (Instruction *I = SimplifyMemTransfer(MI))
9900 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009901 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9902 if (Instruction *I = SimplifyMemSet(MSI))
9903 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009904 }
9905
Chris Lattner8b0ea312006-01-13 20:11:04 +00009906 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009907 }
9908
9909 switch (II->getIntrinsicID()) {
9910 default: break;
9911 case Intrinsic::bswap:
9912 // bswap(bswap(x)) -> x
9913 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9914 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9915 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9916 break;
9917 case Intrinsic::ppc_altivec_lvx:
9918 case Intrinsic::ppc_altivec_lvxl:
9919 case Intrinsic::x86_sse_loadu_ps:
9920 case Intrinsic::x86_sse2_loadu_pd:
9921 case Intrinsic::x86_sse2_loadu_dq:
9922 // Turn PPC lvx -> load if the pointer is known aligned.
9923 // Turn X86 loadups -> load if the pointer is known aligned.
9924 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009925 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9926 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009927 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009928 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009929 break;
9930 case Intrinsic::ppc_altivec_stvx:
9931 case Intrinsic::ppc_altivec_stvxl:
9932 // Turn stvx -> store if the pointer is known aligned.
9933 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9934 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009935 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009936 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009937 return new StoreInst(II->getOperand(1), Ptr);
9938 }
9939 break;
9940 case Intrinsic::x86_sse_storeu_ps:
9941 case Intrinsic::x86_sse2_storeu_pd:
9942 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009943 // Turn X86 storeu -> store if the pointer is known aligned.
9944 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9945 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009946 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009947 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009948 return new StoreInst(II->getOperand(2), Ptr);
9949 }
9950 break;
9951
9952 case Intrinsic::x86_sse_cvttss2si: {
9953 // These intrinsics only demands the 0th element of its input vector. If
9954 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009955 unsigned VWidth =
9956 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9957 APInt DemandedElts(VWidth, 1);
9958 APInt UndefElts(VWidth, 0);
9959 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009960 UndefElts)) {
9961 II->setOperand(1, V);
9962 return II;
9963 }
9964 break;
9965 }
9966
9967 case Intrinsic::ppc_altivec_vperm:
9968 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9969 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9970 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009971
Chris Lattner0521e3c2008-06-18 04:33:20 +00009972 // Check that all of the elements are integer constants or undefs.
9973 bool AllEltsOk = true;
9974 for (unsigned i = 0; i != 16; ++i) {
9975 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9976 !isa<UndefValue>(Mask->getOperand(i))) {
9977 AllEltsOk = false;
9978 break;
9979 }
9980 }
9981
9982 if (AllEltsOk) {
9983 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009984 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9985 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009986 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009987
Chris Lattner0521e3c2008-06-18 04:33:20 +00009988 // Only extract each element once.
9989 Value *ExtractedElts[32];
9990 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9991
Chris Lattnere2ed0572006-04-06 19:19:17 +00009992 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009993 if (isa<UndefValue>(Mask->getOperand(i)))
9994 continue;
9995 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9996 Idx &= 31; // Match the hardware behavior.
9997
9998 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009999 ExtractedElts[Idx] =
10000 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
10001 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10002 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010003 }
Chris Lattnere2ed0572006-04-06 19:19:17 +000010004
Chris Lattner0521e3c2008-06-18 04:33:20 +000010005 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010006 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10007 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10008 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010009 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010010 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010011 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010012 }
10013 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010014
Chris Lattner0521e3c2008-06-18 04:33:20 +000010015 case Intrinsic::stackrestore: {
10016 // If the save is right next to the restore, remove the restore. This can
10017 // happen when variable allocas are DCE'd.
10018 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10019 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10020 BasicBlock::iterator BI = SS;
10021 if (&*++BI == II)
10022 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010023 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010024 }
10025
10026 // Scan down this block to see if there is another stack restore in the
10027 // same block without an intervening call/alloca.
10028 BasicBlock::iterator BI = II;
10029 TerminatorInst *TI = II->getParent()->getTerminator();
10030 bool CannotRemove = false;
10031 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +000010032 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010033 CannotRemove = true;
10034 break;
10035 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010036 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10037 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10038 // If there is a stackrestore below this one, remove this one.
10039 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10040 return EraseInstFromFunction(CI);
10041 // Otherwise, ignore the intrinsic.
10042 } else {
10043 // If we found a non-intrinsic call, we can't remove the stack
10044 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010045 CannotRemove = true;
10046 break;
10047 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010048 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010049 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010050
10051 // If the stack restore is in a return/unwind block and if there are no
10052 // allocas or calls between the restore and the return, nuke the restore.
10053 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10054 return EraseInstFromFunction(CI);
10055 break;
10056 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010057 }
10058
Chris Lattner8b0ea312006-01-13 20:11:04 +000010059 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010060}
10061
10062// InvokeInst simplification
10063//
10064Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010065 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010066}
10067
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010068/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10069/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010070static bool isSafeToEliminateVarargsCast(const CallSite CS,
10071 const CastInst * const CI,
10072 const TargetData * const TD,
10073 const int ix) {
10074 if (!CI->isLosslessCast())
10075 return false;
10076
10077 // The size of ByVal arguments is derived from the type, so we
10078 // can't change to a type with a different size. If the size were
10079 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010080 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010081 return true;
10082
10083 const Type* SrcTy =
10084 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10085 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10086 if (!SrcTy->isSized() || !DstTy->isSized())
10087 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010088 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010089 return false;
10090 return true;
10091}
10092
Chris Lattnera44d8a22003-10-07 22:32:43 +000010093// visitCallSite - Improvements for call and invoke instructions.
10094//
10095Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010096 bool Changed = false;
10097
10098 // If the callee is a constexpr cast of a function, attempt to move the cast
10099 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010100 if (transformConstExprCastCall(CS)) return 0;
10101
Chris Lattner6c266db2003-10-07 22:54:13 +000010102 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010103
Chris Lattner08b22ec2005-05-13 07:09:09 +000010104 if (Function *CalleeF = dyn_cast<Function>(Callee))
10105 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10106 Instruction *OldCall = CS.getInstruction();
10107 // If the call and callee calling conventions don't match, this call must
10108 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010109 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010110 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010111 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010112 // If OldCall dues not return void then replaceAllUsesWith undef.
10113 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010114 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010115 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010116 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10117 return EraseInstFromFunction(*OldCall);
10118 return 0;
10119 }
10120
Chris Lattner17be6352004-10-18 02:59:09 +000010121 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10122 // This instruction is not reachable, just remove it. We insert a store to
10123 // undef so that we know that this code is not reachable, despite the fact
10124 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010125 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010126 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010127 CS.getInstruction());
10128
Devang Patel228ebd02009-10-13 22:56:32 +000010129 // If CS dues not return void then replaceAllUsesWith undef.
10130 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010131 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010132 CS.getInstruction()->
10133 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010134
10135 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10136 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010137 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010138 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010139 }
Chris Lattner17be6352004-10-18 02:59:09 +000010140 return EraseInstFromFunction(*CS.getInstruction());
10141 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010142
Duncan Sandscdb6d922007-09-17 10:26:40 +000010143 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10144 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10145 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10146 return transformCallThroughTrampoline(CS);
10147
Chris Lattner6c266db2003-10-07 22:54:13 +000010148 const PointerType *PTy = cast<PointerType>(Callee->getType());
10149 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10150 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010151 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010152 // See if we can optimize any arguments passed through the varargs area of
10153 // the call.
10154 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010155 E = CS.arg_end(); I != E; ++I, ++ix) {
10156 CastInst *CI = dyn_cast<CastInst>(*I);
10157 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10158 *I = CI->getOperand(0);
10159 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010160 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010161 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010162 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010163
Duncan Sandsf0c33542007-12-19 21:13:37 +000010164 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010165 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010166 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010167 Changed = true;
10168 }
10169
Chris Lattner6c266db2003-10-07 22:54:13 +000010170 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010171}
10172
Chris Lattner9fe38862003-06-19 17:00:31 +000010173// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10174// attempt to move the cast to the arguments of the call/invoke.
10175//
10176bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10177 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10178 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010179 if (CE->getOpcode() != Instruction::BitCast ||
10180 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010181 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010182 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010183 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010184 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010185
10186 // Okay, this is a cast from a function to a different type. Unless doing so
10187 // would cause a type conversion of one of our arguments, change this call to
10188 // be a direct call with arguments casted to the appropriate types.
10189 //
10190 const FunctionType *FT = Callee->getFunctionType();
10191 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010192 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010193
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010194 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010195 return false; // TODO: Handle multiple return values.
10196
Chris Lattnerf78616b2004-01-14 06:06:08 +000010197 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010198 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010199 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010200 // Conversion is ok if changing from one pointer type to another or from
10201 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010202 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010203 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010204 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010205 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010206 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010207
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010208 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010209 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010210 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010211 return false; // Cannot transform this return value.
10212
Chris Lattner58d74912008-03-12 17:45:29 +000010213 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010214 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010215 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010216 return false; // Attribute not compatible with transformed value.
10217 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010218
Chris Lattnerf78616b2004-01-14 06:06:08 +000010219 // If the callsite is an invoke instruction, and the return value is used by
10220 // a PHI node in a successor, we cannot change the return type of the call
10221 // because there is no place to put the cast instruction (without breaking
10222 // the critical edge). Bail out in this case.
10223 if (!Caller->use_empty())
10224 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10225 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10226 UI != E; ++UI)
10227 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10228 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010229 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010230 return false;
10231 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010232
10233 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10234 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010235
Chris Lattner9fe38862003-06-19 17:00:31 +000010236 CallSite::arg_iterator AI = CS.arg_begin();
10237 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10238 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010239 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010240
10241 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010242 return false; // Cannot transform this parameter value.
10243
Devang Patel19c87462008-09-26 22:53:05 +000010244 if (CallerPAL.getParamAttributes(i + 1)
10245 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010246 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010247
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010248 // Converting from one pointer type to another or between a pointer and an
10249 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010250 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010251 (TD && ((isa<PointerType>(ParamTy) ||
10252 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10253 (isa<PointerType>(ActTy) ||
10254 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010255 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010256 }
10257
10258 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010259 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010260 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010261
Chris Lattner58d74912008-03-12 17:45:29 +000010262 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10263 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010264 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010265 // won't be dropping them. Check that these extra arguments have attributes
10266 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010267 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10268 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010269 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010270 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010271 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010272 return false;
10273 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010274
Chris Lattner9fe38862003-06-19 17:00:31 +000010275 // Okay, we decided that this is a safe thing to do: go ahead and start
10276 // inserting cast instructions as necessary...
10277 std::vector<Value*> Args;
10278 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010279 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010280 attrVec.reserve(NumCommonArgs);
10281
10282 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010283 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010284
10285 // If the return value is not being used, the type may not be compatible
10286 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010287 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010288
10289 // Add the new return attributes.
10290 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010291 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010292
10293 AI = CS.arg_begin();
10294 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10295 const Type *ParamTy = FT->getParamType(i);
10296 if ((*AI)->getType() == ParamTy) {
10297 Args.push_back(*AI);
10298 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010299 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010300 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010301 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010302 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010303
10304 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010305 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010306 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010307 }
10308
10309 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010310 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010311 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010312 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010313
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010314 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010315 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010316 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010317 errs() << "WARNING: While resolving call to function '"
10318 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010319 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010320 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010321 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10322 const Type *PTy = getPromotedType((*AI)->getType());
10323 if (PTy != (*AI)->getType()) {
10324 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010325 Instruction::CastOps opcode =
10326 CastInst::getCastOpcode(*AI, false, PTy, false);
10327 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010328 } else {
10329 Args.push_back(*AI);
10330 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010331
Duncan Sandse1e520f2008-01-13 08:02:44 +000010332 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010333 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010334 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010335 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010336 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010337 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010338
Devang Patel19c87462008-09-26 22:53:05 +000010339 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10340 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10341
Devang Patel9674d152009-10-14 17:29:00 +000010342 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010343 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010344
Eric Christophera66297a2009-07-25 02:45:27 +000010345 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10346 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010347
Chris Lattner9fe38862003-06-19 17:00:31 +000010348 Instruction *NC;
10349 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010350 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010351 Args.begin(), Args.end(),
10352 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010353 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010354 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010355 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010356 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10357 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010358 CallInst *CI = cast<CallInst>(Caller);
10359 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010360 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010361 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010362 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010363 }
10364
Chris Lattner6934a042007-02-11 01:23:03 +000010365 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010366 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010367 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010368 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010369 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010370 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010371 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010372
10373 // If this is an invoke instruction, we should insert it after the first
10374 // non-phi, instruction in the normal successor block.
10375 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010376 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010377 InsertNewInstBefore(NC, *I);
10378 } else {
10379 // Otherwise, it's a call, just insert cast right after the call instr
10380 InsertNewInstBefore(NC, *Caller);
10381 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010382 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010383 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010384 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010385 }
10386 }
10387
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010388
Chris Lattner931f8f32009-08-31 05:17:58 +000010389 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010390 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010391
10392 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010393 return true;
10394}
10395
Duncan Sandscdb6d922007-09-17 10:26:40 +000010396// transformCallThroughTrampoline - Turn a call to a function created by the
10397// init_trampoline intrinsic into a direct call to the underlying function.
10398//
10399Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10400 Value *Callee = CS.getCalledValue();
10401 const PointerType *PTy = cast<PointerType>(Callee->getType());
10402 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010403 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010404
10405 // If the call already has the 'nest' attribute somewhere then give up -
10406 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010407 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010408 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010409
10410 IntrinsicInst *Tramp =
10411 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10412
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010413 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010414 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10415 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10416
Devang Patel05988662008-09-25 21:00:45 +000010417 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010418 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010419 unsigned NestIdx = 1;
10420 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010421 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010422
10423 // Look for a parameter marked with the 'nest' attribute.
10424 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10425 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010426 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010427 // Record the parameter type and any other attributes.
10428 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010429 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010430 break;
10431 }
10432
10433 if (NestTy) {
10434 Instruction *Caller = CS.getInstruction();
10435 std::vector<Value*> NewArgs;
10436 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10437
Devang Patel05988662008-09-25 21:00:45 +000010438 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010439 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010440
Duncan Sandscdb6d922007-09-17 10:26:40 +000010441 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010442 // mean appending it. Likewise for attributes.
10443
Devang Patel19c87462008-09-26 22:53:05 +000010444 // Add any result attributes.
10445 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010446 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010447
Duncan Sandscdb6d922007-09-17 10:26:40 +000010448 {
10449 unsigned Idx = 1;
10450 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10451 do {
10452 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010453 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010454 Value *NestVal = Tramp->getOperand(3);
10455 if (NestVal->getType() != NestTy)
10456 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10457 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010458 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010459 }
10460
10461 if (I == E)
10462 break;
10463
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010464 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010465 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010466 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010467 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010468 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010469
10470 ++Idx, ++I;
10471 } while (1);
10472 }
10473
Devang Patel19c87462008-09-26 22:53:05 +000010474 // Add any function attributes.
10475 if (Attributes Attr = Attrs.getFnAttributes())
10476 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10477
Duncan Sandscdb6d922007-09-17 10:26:40 +000010478 // The trampoline may have been bitcast to a bogus type (FTy).
10479 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010480 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010481
Duncan Sandscdb6d922007-09-17 10:26:40 +000010482 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010483 NewTypes.reserve(FTy->getNumParams()+1);
10484
Duncan Sandscdb6d922007-09-17 10:26:40 +000010485 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010486 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010487 {
10488 unsigned Idx = 1;
10489 FunctionType::param_iterator I = FTy->param_begin(),
10490 E = FTy->param_end();
10491
10492 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010493 if (Idx == NestIdx)
10494 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010495 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010496
10497 if (I == E)
10498 break;
10499
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010500 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010501 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010502
10503 ++Idx, ++I;
10504 } while (1);
10505 }
10506
10507 // Replace the trampoline call with a direct call. Let the generic
10508 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010509 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010510 FTy->isVarArg());
10511 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010512 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010513 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010514 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010515 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10516 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010517
10518 Instruction *NewCaller;
10519 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010520 NewCaller = InvokeInst::Create(NewCallee,
10521 II->getNormalDest(), II->getUnwindDest(),
10522 NewArgs.begin(), NewArgs.end(),
10523 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010524 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010525 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010526 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010527 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10528 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010529 if (cast<CallInst>(Caller)->isTailCall())
10530 cast<CallInst>(NewCaller)->setTailCall();
10531 cast<CallInst>(NewCaller)->
10532 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010533 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010534 }
Devang Patel9674d152009-10-14 17:29:00 +000010535 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010536 Caller->replaceAllUsesWith(NewCaller);
10537 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010538 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010539 return 0;
10540 }
10541 }
10542
10543 // Replace the trampoline call with a direct call. Since there is no 'nest'
10544 // parameter, there is no need to adjust the argument list. Let the generic
10545 // code sort out any function type mismatches.
10546 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010547 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010548 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010549 CS.setCalledFunction(NewCallee);
10550 return CS.getInstruction();
10551}
10552
Dan Gohman9ad29202009-09-16 16:50:24 +000010553/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10554/// and if a/b/c and the add's all have a single use, turn this into a phi
Chris Lattner7da52b22006-11-01 04:51:18 +000010555/// and a single binop.
10556Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10557 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010558 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010559 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010560 Value *LHSVal = FirstInst->getOperand(0);
10561 Value *RHSVal = FirstInst->getOperand(1);
10562
10563 const Type *LHSType = LHSVal->getType();
10564 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010565
Dan Gohman9ad29202009-09-16 16:50:24 +000010566 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010567 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010568 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010569 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010570 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010571 // types or GEP's with different index types.
10572 I->getOperand(0)->getType() != LHSType ||
10573 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010574 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010575
10576 // If they are CmpInst instructions, check their predicates
10577 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10578 if (cast<CmpInst>(I)->getPredicate() !=
10579 cast<CmpInst>(FirstInst)->getPredicate())
10580 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010581
10582 // Keep track of which operand needs a phi node.
10583 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10584 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010585 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010586
10587 // If both LHS and RHS would need a PHI, don't do this transformation,
10588 // because it would increase the number of PHIs entering the block,
10589 // which leads to higher register pressure. This is especially
10590 // bad when the PHIs are in the header of a loop.
10591 if (!LHSVal && !RHSVal)
10592 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010593
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010594 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010595
Chris Lattner7da52b22006-11-01 04:51:18 +000010596 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010597 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010598 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010599 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010600 NewLHS = PHINode::Create(LHSType,
10601 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010602 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10603 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010604 InsertNewInstBefore(NewLHS, PN);
10605 LHSVal = NewLHS;
10606 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010607
10608 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010609 NewRHS = PHINode::Create(RHSType,
10610 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010611 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10612 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010613 InsertNewInstBefore(NewRHS, PN);
10614 RHSVal = NewRHS;
10615 }
10616
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010617 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010618 if (NewLHS || NewRHS) {
10619 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10620 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10621 if (NewLHS) {
10622 Value *NewInLHS = InInst->getOperand(0);
10623 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10624 }
10625 if (NewRHS) {
10626 Value *NewInRHS = InInst->getOperand(1);
10627 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10628 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010629 }
10630 }
10631
Chris Lattner7da52b22006-11-01 04:51:18 +000010632 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010633 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010634 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010635 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010636 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010637}
10638
Chris Lattner05f18922008-12-01 02:34:36 +000010639Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10640 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10641
10642 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10643 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010644 // This is true if all GEP bases are allocas and if all indices into them are
10645 // constants.
10646 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010647
10648 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010649 // more than one phi, which leads to higher register pressure. This is
10650 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010651 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010652
Dan Gohman9ad29202009-09-16 16:50:24 +000010653 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010654 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10655 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10656 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10657 GEP->getNumOperands() != FirstInst->getNumOperands())
10658 return 0;
10659
Chris Lattner36d3e322009-02-21 00:46:50 +000010660 // Keep track of whether or not all GEPs are of alloca pointers.
10661 if (AllBasePointersAreAllocas &&
10662 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10663 !GEP->hasAllConstantIndices()))
10664 AllBasePointersAreAllocas = false;
10665
Chris Lattner05f18922008-12-01 02:34:36 +000010666 // Compare the operand lists.
10667 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10668 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10669 continue;
10670
10671 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10672 // if one of the PHIs has a constant for the index. The index may be
10673 // substantially cheaper to compute for the constants, so making it a
10674 // variable index could pessimize the path. This also handles the case
10675 // for struct indices, which must always be constant.
10676 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10677 isa<ConstantInt>(GEP->getOperand(op)))
10678 return 0;
10679
10680 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10681 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010682
10683 // If we already needed a PHI for an earlier operand, and another operand
10684 // also requires a PHI, we'd be introducing more PHIs than we're
10685 // eliminating, which increases register pressure on entry to the PHI's
10686 // block.
10687 if (NeededPhi)
10688 return 0;
10689
Chris Lattner05f18922008-12-01 02:34:36 +000010690 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010691 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010692 }
10693 }
10694
Chris Lattner36d3e322009-02-21 00:46:50 +000010695 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010696 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010697 // offset calculation, but all the predecessors will have to materialize the
10698 // stack address into a register anyway. We'd actually rather *clone* the
10699 // load up into the predecessors so that we have a load of a gep of an alloca,
10700 // which can usually all be folded into the load.
10701 if (AllBasePointersAreAllocas)
10702 return 0;
10703
Chris Lattner05f18922008-12-01 02:34:36 +000010704 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10705 // that is variable.
10706 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10707
10708 bool HasAnyPHIs = false;
10709 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10710 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10711 Value *FirstOp = FirstInst->getOperand(i);
10712 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10713 FirstOp->getName()+".pn");
10714 InsertNewInstBefore(NewPN, PN);
10715
10716 NewPN->reserveOperandSpace(e);
10717 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10718 OperandPhis[i] = NewPN;
10719 FixedOperands[i] = NewPN;
10720 HasAnyPHIs = true;
10721 }
10722
10723
10724 // Add all operands to the new PHIs.
10725 if (HasAnyPHIs) {
10726 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10727 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10728 BasicBlock *InBB = PN.getIncomingBlock(i);
10729
10730 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10731 if (PHINode *OpPhi = OperandPhis[op])
10732 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10733 }
10734 }
10735
10736 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010737 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10738 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10739 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010740 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10741 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010742}
10743
10744
Chris Lattner21550882009-02-23 05:56:17 +000010745/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10746/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010747/// obvious the value of the load is not changed from the point of the load to
10748/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010749///
10750/// Finally, it is safe, but not profitable, to sink a load targetting a
10751/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10752/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010753static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010754 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10755
10756 for (++BBI; BBI != E; ++BBI)
10757 if (BBI->mayWriteToMemory())
10758 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010759
10760 // Check for non-address taken alloca. If not address-taken already, it isn't
10761 // profitable to do this xform.
10762 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10763 bool isAddressTaken = false;
10764 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10765 UI != E; ++UI) {
10766 if (isa<LoadInst>(UI)) continue;
10767 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10768 // If storing TO the alloca, then the address isn't taken.
10769 if (SI->getOperand(1) == AI) continue;
10770 }
10771 isAddressTaken = true;
10772 break;
10773 }
10774
Chris Lattner36d3e322009-02-21 00:46:50 +000010775 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010776 return false;
10777 }
10778
Chris Lattner36d3e322009-02-21 00:46:50 +000010779 // If this load is a load from a GEP with a constant offset from an alloca,
10780 // then we don't want to sink it. In its present form, it will be
10781 // load [constant stack offset]. Sinking it will cause us to have to
10782 // materialize the stack addresses in each predecessor in a register only to
10783 // do a shared load from register in the successor.
10784 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10785 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10786 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10787 return false;
10788
Chris Lattner76c73142006-11-01 07:13:54 +000010789 return true;
10790}
10791
Chris Lattner751a3622009-11-01 20:04:24 +000010792Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10793 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10794
10795 // When processing loads, we need to propagate two bits of information to the
10796 // sunk load: whether it is volatile, and what its alignment is. We currently
10797 // don't sink loads when some have their alignment specified and some don't.
10798 // visitLoadInst will propagate an alignment onto the load when TD is around,
10799 // and if TD isn't around, we can't handle the mixed case.
10800 bool isVolatile = FirstLI->isVolatile();
10801 unsigned LoadAlignment = FirstLI->getAlignment();
10802
10803 // We can't sink the load if the loaded value could be modified between the
10804 // load and the PHI.
10805 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10806 !isSafeAndProfitableToSinkLoad(FirstLI))
10807 return 0;
10808
10809 // If the PHI is of volatile loads and the load block has multiple
10810 // successors, sinking it would remove a load of the volatile value from
10811 // the path through the other successor.
10812 if (isVolatile &&
10813 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10814 return 0;
10815
10816 // Check to see if all arguments are the same operation.
10817 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10818 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10819 if (!LI || !LI->hasOneUse())
10820 return 0;
10821
10822 // We can't sink the load if the loaded value could be modified between
10823 // the load and the PHI.
10824 if (LI->isVolatile() != isVolatile ||
10825 LI->getParent() != PN.getIncomingBlock(i) ||
10826 !isSafeAndProfitableToSinkLoad(LI))
10827 return 0;
10828
10829 // If some of the loads have an alignment specified but not all of them,
10830 // we can't do the transformation.
10831 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10832 return 0;
10833
Chris Lattnera664bb72009-11-01 20:07:07 +000010834 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000010835
10836 // If the PHI is of volatile loads and the load block has multiple
10837 // successors, sinking it would remove a load of the volatile value from
10838 // the path through the other successor.
10839 if (isVolatile &&
10840 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10841 return 0;
10842 }
10843
10844 // Okay, they are all the same operation. Create a new PHI node of the
10845 // correct type, and PHI together all of the LHS's of the instructions.
10846 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10847 PN.getName()+".in");
10848 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10849
10850 Value *InVal = FirstLI->getOperand(0);
10851 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10852
10853 // Add all operands to the new PHI.
10854 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10855 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10856 if (NewInVal != InVal)
10857 InVal = 0;
10858 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10859 }
10860
10861 Value *PhiVal;
10862 if (InVal) {
10863 // The new PHI unions all of the same values together. This is really
10864 // common, so we handle it intelligently here for compile-time speed.
10865 PhiVal = InVal;
10866 delete NewPN;
10867 } else {
10868 InsertNewInstBefore(NewPN, PN);
10869 PhiVal = NewPN;
10870 }
10871
10872 // If this was a volatile load that we are merging, make sure to loop through
10873 // and mark all the input loads as non-volatile. If we don't do this, we will
10874 // insert a new volatile load and the old ones will not be deletable.
10875 if (isVolatile)
10876 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10877 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10878
10879 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
10880}
10881
Chris Lattner9fe38862003-06-19 17:00:31 +000010882
Chris Lattnerbac32862004-11-14 19:13:23 +000010883// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10884// operator and they all are only used by the PHI, PHI together their
10885// inputs, and do the operation once, to the result of the PHI.
10886Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10887 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10888
Chris Lattner751a3622009-11-01 20:04:24 +000010889 if (isa<GetElementPtrInst>(FirstInst))
10890 return FoldPHIArgGEPIntoPHI(PN);
10891 if (isa<LoadInst>(FirstInst))
10892 return FoldPHIArgLoadIntoPHI(PN);
10893
Chris Lattnerbac32862004-11-14 19:13:23 +000010894 // Scan the instruction, looking for input operations that can be folded away.
10895 // If all input operands to the phi are the same instruction (e.g. a cast from
10896 // the same type or "+42") we can pull the operation through the PHI, reducing
10897 // code size and simplifying code.
10898 Constant *ConstantOp = 0;
10899 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000010900
Chris Lattnerbac32862004-11-14 19:13:23 +000010901 if (isa<CastInst>(FirstInst)) {
10902 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010903 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010904 // Can fold binop, compare or shift here if the RHS is a constant,
10905 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010906 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010907 if (ConstantOp == 0)
10908 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010909 } else {
10910 return 0; // Cannot fold this operation.
10911 }
10912
10913 // Check to see if all arguments are the same operation.
10914 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000010915 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10916 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010917 return 0;
10918 if (CastSrcTy) {
10919 if (I->getOperand(0)->getType() != CastSrcTy)
10920 return 0; // Cast operation must match.
10921 } else if (I->getOperand(1) != ConstantOp) {
10922 return 0;
10923 }
10924 }
10925
10926 // Okay, they are all the same operation. Create a new PHI node of the
10927 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010928 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10929 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010930 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010931
10932 Value *InVal = FirstInst->getOperand(0);
10933 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010934
10935 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010936 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10937 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10938 if (NewInVal != InVal)
10939 InVal = 0;
10940 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10941 }
10942
10943 Value *PhiVal;
10944 if (InVal) {
10945 // The new PHI unions all of the same values together. This is really
10946 // common, so we handle it intelligently here for compile-time speed.
10947 PhiVal = InVal;
10948 delete NewPN;
10949 } else {
10950 InsertNewInstBefore(NewPN, PN);
10951 PhiVal = NewPN;
10952 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010953
Chris Lattnerbac32862004-11-14 19:13:23 +000010954 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000010955 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010956 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000010957
Chris Lattner54545ac2008-04-29 17:13:43 +000010958 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010959 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000010960
Chris Lattner751a3622009-11-01 20:04:24 +000010961 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10962 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10963 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000010964}
Chris Lattnera1be5662002-05-02 17:06:02 +000010965
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010966/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10967/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010968static bool DeadPHICycle(PHINode *PN,
10969 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010970 if (PN->use_empty()) return true;
10971 if (!PN->hasOneUse()) return false;
10972
10973 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010974 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010975 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010976
10977 // Don't scan crazily complex things.
10978 if (PotentiallyDeadPHIs.size() == 16)
10979 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010980
10981 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10982 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010983
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010984 return false;
10985}
10986
Chris Lattnercf5008a2007-11-06 21:52:06 +000010987/// PHIsEqualValue - Return true if this phi node is always equal to
10988/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10989/// z = some value; x = phi (y, z); y = phi (x, z)
10990static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10991 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10992 // See if we already saw this PHI node.
10993 if (!ValueEqualPHIs.insert(PN))
10994 return true;
10995
10996 // Don't scan crazily complex things.
10997 if (ValueEqualPHIs.size() == 16)
10998 return false;
10999
11000 // Scan the operands to see if they are either phi nodes or are equal to
11001 // the value.
11002 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11003 Value *Op = PN->getIncomingValue(i);
11004 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11005 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11006 return false;
11007 } else if (Op != NonPhiInVal)
11008 return false;
11009 }
11010
11011 return true;
11012}
11013
11014
Chris Lattner473945d2002-05-06 18:06:38 +000011015// PHINode simplification
11016//
Chris Lattner7e708292002-06-25 16:13:24 +000011017Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000011018 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000011019 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000011020
Owen Anderson7e057142006-07-10 22:03:18 +000011021 if (Value *V = PN.hasConstantValue())
11022 return ReplaceInstUsesWith(PN, V);
11023
Owen Anderson7e057142006-07-10 22:03:18 +000011024 // If all PHI operands are the same operation, pull them through the PHI,
11025 // reducing code size.
11026 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000011027 isa<Instruction>(PN.getIncomingValue(1)) &&
11028 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11029 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11030 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11031 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000011032 PN.getIncomingValue(0)->hasOneUse())
11033 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11034 return Result;
11035
11036 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11037 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11038 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011039 if (PN.hasOneUse()) {
11040 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11041 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000011042 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000011043 PotentiallyDeadPHIs.insert(&PN);
11044 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011045 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000011046 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011047
11048 // If this phi has a single use, and if that use just computes a value for
11049 // the next iteration of a loop, delete the phi. This occurs with unused
11050 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11051 // common case here is good because the only other things that catch this
11052 // are induction variable analysis (sometimes) and ADCE, which is only run
11053 // late.
11054 if (PHIUser->hasOneUse() &&
11055 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11056 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011057 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011058 }
11059 }
Owen Anderson7e057142006-07-10 22:03:18 +000011060
Chris Lattnercf5008a2007-11-06 21:52:06 +000011061 // We sometimes end up with phi cycles that non-obviously end up being the
11062 // same value, for example:
11063 // z = some value; x = phi (y, z); y = phi (x, z)
11064 // where the phi nodes don't necessarily need to be in the same block. Do a
11065 // quick check to see if the PHI node only contains a single non-phi value, if
11066 // so, scan to see if the phi cycle is actually equal to that value.
11067 {
11068 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11069 // Scan for the first non-phi operand.
11070 while (InValNo != NumOperandVals &&
11071 isa<PHINode>(PN.getIncomingValue(InValNo)))
11072 ++InValNo;
11073
11074 if (InValNo != NumOperandVals) {
11075 Value *NonPhiInVal = PN.getOperand(InValNo);
11076
11077 // Scan the rest of the operands to see if there are any conflicts, if so
11078 // there is no need to recursively scan other phis.
11079 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11080 Value *OpVal = PN.getIncomingValue(InValNo);
11081 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11082 break;
11083 }
11084
11085 // If we scanned over all operands, then we have one unique value plus
11086 // phi values. Scan PHI nodes to see if they all merge in each other or
11087 // the value.
11088 if (InValNo == NumOperandVals) {
11089 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11090 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11091 return ReplaceInstUsesWith(PN, NonPhiInVal);
11092 }
11093 }
11094 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011095
Dan Gohman5b097012009-10-31 14:22:52 +000011096 // If there are multiple PHIs, sort their operands so that they all list
11097 // the blocks in the same order. This will help identical PHIs be eliminated
11098 // by other passes. Other passes shouldn't depend on this for correctness
11099 // however.
11100 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11101 if (&PN != FirstPN)
11102 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011103 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000011104 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11105 if (BBA != BBB) {
11106 Value *VA = PN.getIncomingValue(i);
11107 unsigned j = PN.getBasicBlockIndex(BBB);
11108 Value *VB = PN.getIncomingValue(j);
11109 PN.setIncomingBlock(i, BBB);
11110 PN.setIncomingValue(i, VB);
11111 PN.setIncomingBlock(j, BBA);
11112 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000011113 // NOTE: Instcombine normally would want us to "return &PN" if we
11114 // modified any of the operands of an instruction. However, since we
11115 // aren't adding or removing uses (just rearranging them) we don't do
11116 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000011117 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011118 }
11119
Chris Lattner60921c92003-12-19 05:58:40 +000011120 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011121}
11122
Chris Lattner7e708292002-06-25 16:13:24 +000011123Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000011124 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000011125 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011126 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011127 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011128
Chris Lattnere87597f2004-10-16 18:11:37 +000011129 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011130 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011131
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011132 bool HasZeroPointerIndex = false;
11133 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11134 HasZeroPointerIndex = C->isNullValue();
11135
11136 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011137 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011138
Chris Lattner28977af2004-04-05 01:30:19 +000011139 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011140 if (TD) {
11141 bool MadeChange = false;
11142 unsigned PtrSize = TD->getPointerSizeInBits();
11143
11144 gep_type_iterator GTI = gep_type_begin(GEP);
11145 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11146 I != E; ++I, ++GTI) {
11147 if (!isa<SequentialType>(*GTI)) continue;
11148
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011149 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011150 // to what we need. If narrower, sign-extend it to what we need. This
11151 // explicit cast can make subsequent optimizations more obvious.
11152 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000011153 if (OpBits == PtrSize)
11154 continue;
11155
Chris Lattner2345d1d2009-08-30 20:01:10 +000011156 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011157 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011158 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011159 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011160 }
Chris Lattner28977af2004-04-05 01:30:19 +000011161
Chris Lattner90ac28c2002-08-02 19:29:35 +000011162 // Combine Indices - If the source pointer to this getelementptr instruction
11163 // is a getelementptr instruction, combine the indices of the two
11164 // getelementptr instructions into a single instruction.
11165 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011166 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011167 // Note that if our source is a gep chain itself that we wait for that
11168 // chain to be resolved before we perform this transformation. This
11169 // avoids us creating a TON of code in some cases.
11170 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011171 if (GetElementPtrInst *SrcGEP =
11172 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11173 if (SrcGEP->getNumOperands() == 2)
11174 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011175
Chris Lattner72588fc2007-02-15 22:48:32 +000011176 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011177
11178 // Find out whether the last index in the source GEP is a sequential idx.
11179 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011180 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11181 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011182 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011183
Chris Lattner90ac28c2002-08-02 19:29:35 +000011184 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011185 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011186 // Replace: gep (gep %P, long B), long A, ...
11187 // With: T = long A+B; gep %P, T, ...
11188 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011189 Value *Sum;
11190 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11191 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011192 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011193 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011194 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011195 Sum = SO1;
11196 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011197 // If they aren't the same type, then the input hasn't been processed
11198 // by the loop above yet (which canonicalizes sequential index types to
11199 // intptr_t). Just avoid transforming this until the input has been
11200 // normalized.
11201 if (SO1->getType() != GO1->getType())
11202 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011203 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000011204 }
Chris Lattner620ce142004-05-07 22:09:22 +000011205
Chris Lattnerab984842009-08-30 05:30:55 +000011206 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011207 if (Src->getNumOperands() == 2) {
11208 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011209 GEP.setOperand(1, Sum);
11210 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011211 }
Chris Lattnerab984842009-08-30 05:30:55 +000011212 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011213 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011214 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011215 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011216 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011217 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011218 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011219 Indices.append(Src->op_begin()+1, Src->op_end());
11220 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011221 }
11222
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011223 if (!Indices.empty())
11224 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11225 Src->isInBounds()) ?
11226 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11227 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011228 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011229 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011230 }
11231
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011232 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11233 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011234 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011235
Chris Lattner2de23192009-08-30 20:38:21 +000011236 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11237 // want to change the gep until the bitcasts are eliminated.
11238 if (getBitCastOperand(X)) {
11239 Worklist.AddValue(PtrOp);
11240 return 0;
11241 }
11242
Chris Lattner963f4ba2009-08-30 20:36:46 +000011243 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11244 // into : GEP [10 x i8]* X, i32 0, ...
11245 //
11246 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11247 // into : GEP i8* X, ...
11248 //
11249 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011250 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011251 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11252 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011253 if (const ArrayType *CATy =
11254 dyn_cast<ArrayType>(CPTy->getElementType())) {
11255 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11256 if (CATy->getElementType() == XTy->getElementType()) {
11257 // -> GEP i8* X, ...
11258 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011259 return cast<GEPOperator>(&GEP)->isInBounds() ?
11260 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11261 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011262 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11263 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011264 }
11265
11266 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011267 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011268 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011269 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011270 // At this point, we know that the cast source type is a pointer
11271 // to an array of the same type as the destination pointer
11272 // array. Because the array type is never stepped over (there
11273 // is a leading zero) we can fold the cast into this GEP.
11274 GEP.setOperand(0, X);
11275 return &GEP;
11276 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011277 }
11278 }
Chris Lattnereed48272005-09-13 00:40:14 +000011279 } else if (GEP.getNumOperands() == 2) {
11280 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011281 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11282 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011283 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11284 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011285 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011286 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11287 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011288 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011289 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011290 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011291 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11292 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011293 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011294 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011295 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011296 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011297
11298 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011299 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011300 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011301 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011302
Owen Anderson1d0be152009-08-13 21:58:54 +000011303 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011304 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011305 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011306
11307 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11308 // allow either a mul, shift, or constant here.
11309 Value *NewIdx = 0;
11310 ConstantInt *Scale = 0;
11311 if (ArrayEltSize == 1) {
11312 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011313 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011314 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011315 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011316 Scale = CI;
11317 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11318 if (Inst->getOpcode() == Instruction::Shl &&
11319 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011320 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11321 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011322 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011323 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011324 NewIdx = Inst->getOperand(0);
11325 } else if (Inst->getOpcode() == Instruction::Mul &&
11326 isa<ConstantInt>(Inst->getOperand(1))) {
11327 Scale = cast<ConstantInt>(Inst->getOperand(1));
11328 NewIdx = Inst->getOperand(0);
11329 }
11330 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011331
Chris Lattner7835cdd2005-09-13 18:36:04 +000011332 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011333 // out, perform the transformation. Note, we don't know whether Scale is
11334 // signed or not. We'll use unsigned version of division/modulo
11335 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011336 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011337 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011338 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011339 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011340 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011341 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11342 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011343 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011344 }
11345
11346 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011347 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011348 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011349 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011350 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11351 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11352 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011353 // The NewGEP must be pointer typed, so must the old one -> BitCast
11354 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011355 }
11356 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011357 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011358 }
Chris Lattner58407792009-01-09 04:53:57 +000011359
Chris Lattner46cd5a12009-01-09 05:44:56 +000011360 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011361 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011362 /// Y = gep X, <...constant indices...>
11363 /// into a gep of the original struct. This is important for SROA and alias
11364 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011365 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011366 if (TD &&
11367 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011368 // Determine how much the GEP moves the pointer. We are guaranteed to get
11369 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000011370 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011371 int64_t Offset = OffsetV->getSExtValue();
11372
11373 // If this GEP instruction doesn't move the pointer, just replace the GEP
11374 // with a bitcast of the real input to the dest type.
11375 if (Offset == 0) {
11376 // If the bitcast is of an allocation, and the allocation will be
11377 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000011378 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000011379 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011380 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11381 if (Instruction *I = visitBitCast(*BCI)) {
11382 if (I != BCI) {
11383 I->takeName(BCI);
11384 BCI->getParent()->getInstList().insert(BCI, I);
11385 ReplaceInstUsesWith(*BCI, I);
11386 }
11387 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011388 }
Chris Lattner58407792009-01-09 04:53:57 +000011389 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011390 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011391 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011392
11393 // Otherwise, if the offset is non-zero, we need to find out if there is a
11394 // field at Offset in 'A's type. If so, we can pull the cast through the
11395 // GEP.
11396 SmallVector<Value*, 8> NewIndices;
11397 const Type *InTy =
11398 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011399 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011400 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11401 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11402 NewIndices.end()) :
11403 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11404 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011405
11406 if (NGEP->getType() == GEP.getType())
11407 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011408 NGEP->takeName(&GEP);
11409 return new BitCastInst(NGEP, GEP.getType());
11410 }
Chris Lattner58407792009-01-09 04:53:57 +000011411 }
11412 }
11413
Chris Lattner8a2a3112001-12-14 16:52:21 +000011414 return 0;
11415}
11416
Victor Hernandez7b929da2009-10-23 21:09:37 +000011417Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000011418 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011419 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011420 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11421 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011422 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000011423 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000011424 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011425 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011426
Chris Lattner0864acf2002-11-04 16:18:53 +000011427 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011428 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011429 //
11430 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000011431 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011432
11433 // Now that I is pointing to the first non-allocation-inst in the block,
11434 // insert our getelementptr instruction...
11435 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011436 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011437 Value *Idx[2];
11438 Idx[0] = NullIdx;
11439 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011440 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11441 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011442
11443 // Now make everything use the getelementptr instead of the original
11444 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011445 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011446 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011447 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011448 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011449 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011450
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011451 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011452 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011453 // Note that we only do this for alloca's, because malloc should allocate
11454 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011455 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011456 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011457
11458 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11459 if (AI.getAlignment() == 0)
11460 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11461 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011462
Chris Lattner0864acf2002-11-04 16:18:53 +000011463 return 0;
11464}
11465
Victor Hernandez66284e02009-10-24 04:23:03 +000011466Instruction *InstCombiner::visitFree(Instruction &FI) {
11467 Value *Op = FI.getOperand(1);
11468
11469 // free undef -> unreachable.
11470 if (isa<UndefValue>(Op)) {
11471 // Insert a new store to null because we cannot modify the CFG here.
11472 new StoreInst(ConstantInt::getTrue(*Context),
11473 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11474 return EraseInstFromFunction(FI);
11475 }
11476
11477 // If we have 'free null' delete the instruction. This can happen in stl code
11478 // when lots of inlining happens.
11479 if (isa<ConstantPointerNull>(Op))
11480 return EraseInstFromFunction(FI);
11481
Victor Hernandez046e78c2009-10-26 23:43:48 +000011482 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000011483 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000011484 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11485 if (Op->hasOneUse() && CI->hasOneUse()) {
11486 EraseInstFromFunction(FI);
11487 EraseInstFromFunction(*CI);
11488 return EraseInstFromFunction(*cast<Instruction>(Op));
11489 }
11490 } else {
11491 // Op is a call to malloc
11492 if (Op->hasOneUse()) {
11493 EraseInstFromFunction(FI);
11494 return EraseInstFromFunction(*cast<Instruction>(Op));
11495 }
11496 }
Dan Gohman7f712a12009-10-27 00:11:02 +000011497 }
Victor Hernandez66284e02009-10-24 04:23:03 +000011498
11499 return 0;
11500}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011501
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011502/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011503static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011504 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011505 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011506 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011507 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011508
Mon P Wang6753f952009-02-07 22:19:29 +000011509 const PointerType *DestTy = cast<PointerType>(CI->getType());
11510 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011511 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011512
11513 // If the address spaces don't match, don't eliminate the cast.
11514 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11515 return 0;
11516
Chris Lattnerb89e0712004-07-13 01:49:43 +000011517 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011518
Reid Spencer42230162007-01-22 05:51:25 +000011519 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011520 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011521 // If the source is an array, the code below will not succeed. Check to
11522 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11523 // constants.
11524 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11525 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11526 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011527 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000011528 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11529 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000011530 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011531 SrcTy = cast<PointerType>(CastOp->getType());
11532 SrcPTy = SrcTy->getElementType();
11533 }
11534
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011535 if (IC.getTargetData() &&
11536 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011537 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011538 // Do not allow turning this into a load of an integer, which is then
11539 // casted to a pointer, this pessimizes pointer analysis a lot.
11540 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011541 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11542 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011543
Chris Lattnerf9527852005-01-31 04:50:46 +000011544 // Okay, we are casting from one integer or pointer type to another of
11545 // the same size. Instead of casting the pointer before the load, cast
11546 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011547 Value *NewLoad =
11548 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011549 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011550 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011551 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011552 }
11553 }
11554 return 0;
11555}
11556
Chris Lattner833b8a42003-06-26 05:06:25 +000011557Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11558 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011559
Dan Gohman9941f742007-07-20 16:34:21 +000011560 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011561 if (TD) {
11562 unsigned KnownAlign =
11563 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11564 if (KnownAlign >
11565 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11566 LI.getAlignment()))
11567 LI.setAlignment(KnownAlign);
11568 }
Dan Gohman9941f742007-07-20 16:34:21 +000011569
Chris Lattner963f4ba2009-08-30 20:36:46 +000011570 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011571 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011572 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011573 return Res;
11574
11575 // None of the following transforms are legal for volatile loads.
11576 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011577
Dan Gohman2276a7b2008-10-15 23:19:35 +000011578 // Do really simple store-to-load forwarding and load CSE, to catch cases
11579 // where there are several consequtive memory accesses to the same location,
11580 // separated by a few arithmetic operations.
11581 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011582 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11583 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011584
Chris Lattner878e4942009-10-22 06:25:11 +000011585 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000011586 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11587 const Value *GEPI0 = GEPI->getOperand(0);
11588 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011589 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011590 // Insert a new store to null instruction before the load to indicate
11591 // that this code is not reachable. We do this instead of inserting
11592 // an unreachable instruction directly because we cannot modify the
11593 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011594 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011595 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011596 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011597 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011598 }
Chris Lattner37366c12005-05-01 04:24:53 +000011599
Chris Lattner878e4942009-10-22 06:25:11 +000011600 // load null/undef -> unreachable
11601 // TODO: Consider a target hook for valid address spaces for this xform.
11602 if (isa<UndefValue>(Op) ||
11603 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11604 // Insert a new store to null instruction before the load to indicate that
11605 // this code is not reachable. We do this instead of inserting an
11606 // unreachable instruction directly because we cannot modify the CFG.
11607 new StoreInst(UndefValue::get(LI.getType()),
11608 Constant::getNullValue(Op->getType()), &LI);
11609 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011610 }
Chris Lattner878e4942009-10-22 06:25:11 +000011611
11612 // Instcombine load (constantexpr_cast global) -> cast (load global)
11613 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11614 if (CE->isCast())
11615 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11616 return Res;
11617
Chris Lattner37366c12005-05-01 04:24:53 +000011618 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011619 // Change select and PHI nodes to select values instead of addresses: this
11620 // helps alias analysis out a lot, allows many others simplifications, and
11621 // exposes redundancy in the code.
11622 //
11623 // Note that we cannot do the transformation unless we know that the
11624 // introduced loads cannot trap! Something like this is valid as long as
11625 // the condition is always false: load (select bool %C, int* null, int* %G),
11626 // but it would not be valid if we transformed it to load from null
11627 // unconditionally.
11628 //
11629 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11630 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011631 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11632 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011633 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11634 SI->getOperand(1)->getName()+".val");
11635 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11636 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011637 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011638 }
11639
Chris Lattner684fe212004-09-23 15:46:00 +000011640 // load (select (cond, null, P)) -> load P
11641 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11642 if (C->isNullValue()) {
11643 LI.setOperand(0, SI->getOperand(2));
11644 return &LI;
11645 }
11646
11647 // load (select (cond, P, null)) -> load P
11648 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11649 if (C->isNullValue()) {
11650 LI.setOperand(0, SI->getOperand(1));
11651 return &LI;
11652 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011653 }
11654 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011655 return 0;
11656}
11657
Reid Spencer55af2b52007-01-19 21:20:31 +000011658/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011659/// when possible. This makes it generally easy to do alias analysis and/or
11660/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011661static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11662 User *CI = cast<User>(SI.getOperand(1));
11663 Value *CastOp = CI->getOperand(0);
11664
11665 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011666 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11667 if (SrcTy == 0) return 0;
11668
11669 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011670
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011671 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11672 return 0;
11673
Chris Lattner3914f722009-01-24 01:00:13 +000011674 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11675 /// to its first element. This allows us to handle things like:
11676 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11677 /// on 32-bit hosts.
11678 SmallVector<Value*, 4> NewGEPIndices;
11679
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011680 // If the source is an array, the code below will not succeed. Check to
11681 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11682 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011683 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11684 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011685 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011686 NewGEPIndices.push_back(Zero);
11687
11688 while (1) {
11689 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011690 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011691 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011692 NewGEPIndices.push_back(Zero);
11693 SrcPTy = STy->getElementType(0);
11694 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11695 NewGEPIndices.push_back(Zero);
11696 SrcPTy = ATy->getElementType();
11697 } else {
11698 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011699 }
Chris Lattner3914f722009-01-24 01:00:13 +000011700 }
11701
Owen Andersondebcb012009-07-29 22:17:13 +000011702 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011703 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011704
11705 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11706 return 0;
11707
Chris Lattner71759c42009-01-16 20:12:52 +000011708 // If the pointers point into different address spaces or if they point to
11709 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011710 if (!IC.getTargetData() ||
11711 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011712 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011713 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11714 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011715 return 0;
11716
11717 // Okay, we are casting from one integer or pointer type to another of
11718 // the same size. Instead of casting the pointer before
11719 // the store, cast the value to be stored.
11720 Value *NewCast;
11721 Value *SIOp0 = SI.getOperand(0);
11722 Instruction::CastOps opcode = Instruction::BitCast;
11723 const Type* CastSrcTy = SIOp0->getType();
11724 const Type* CastDstTy = SrcPTy;
11725 if (isa<PointerType>(CastDstTy)) {
11726 if (CastSrcTy->isInteger())
11727 opcode = Instruction::IntToPtr;
11728 } else if (isa<IntegerType>(CastDstTy)) {
11729 if (isa<PointerType>(SIOp0->getType()))
11730 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011731 }
Chris Lattner3914f722009-01-24 01:00:13 +000011732
11733 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11734 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011735 if (!NewGEPIndices.empty())
11736 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11737 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011738
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011739 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11740 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011741 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011742}
11743
Chris Lattner4aebaee2008-11-27 08:56:30 +000011744/// equivalentAddressValues - Test if A and B will obviously have the same
11745/// value. This includes recognizing that %t0 and %t1 will have the same
11746/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011747/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011748/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011749/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011750/// %t2 = load i32* %t1
11751///
11752static bool equivalentAddressValues(Value *A, Value *B) {
11753 // Test if the values are trivially equivalent.
11754 if (A == B) return true;
11755
11756 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011757 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11758 // its only used to compare two uses within the same basic block, which
11759 // means that they'll always either have the same value or one of them
11760 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011761 if (isa<BinaryOperator>(A) ||
11762 isa<CastInst>(A) ||
11763 isa<PHINode>(A) ||
11764 isa<GetElementPtrInst>(A))
11765 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011766 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011767 return true;
11768
11769 // Otherwise they may not be equivalent.
11770 return false;
11771}
11772
Dale Johannesen4945c652009-03-03 21:26:39 +000011773// If this instruction has two uses, one of which is a llvm.dbg.declare,
11774// return the llvm.dbg.declare.
11775DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11776 if (!V->hasNUses(2))
11777 return 0;
11778 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11779 UI != E; ++UI) {
11780 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11781 return DI;
11782 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11783 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11784 return DI;
11785 }
11786 }
11787 return 0;
11788}
11789
Chris Lattner2f503e62005-01-31 05:36:43 +000011790Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11791 Value *Val = SI.getOperand(0);
11792 Value *Ptr = SI.getOperand(1);
11793
11794 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011795 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011796 ++NumCombined;
11797 return 0;
11798 }
Chris Lattner836692d2007-01-15 06:51:56 +000011799
11800 // If the RHS is an alloca with a single use, zapify the store, making the
11801 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011802 // If the RHS is an alloca with a two uses, the other one being a
11803 // llvm.dbg.declare, zapify the store and the declare, making the
11804 // alloca dead. We must do this to prevent declare's from affecting
11805 // codegen.
11806 if (!SI.isVolatile()) {
11807 if (Ptr->hasOneUse()) {
11808 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011809 EraseInstFromFunction(SI);
11810 ++NumCombined;
11811 return 0;
11812 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011813 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11814 if (isa<AllocaInst>(GEP->getOperand(0))) {
11815 if (GEP->getOperand(0)->hasOneUse()) {
11816 EraseInstFromFunction(SI);
11817 ++NumCombined;
11818 return 0;
11819 }
11820 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11821 EraseInstFromFunction(*DI);
11822 EraseInstFromFunction(SI);
11823 ++NumCombined;
11824 return 0;
11825 }
11826 }
11827 }
11828 }
11829 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11830 EraseInstFromFunction(*DI);
11831 EraseInstFromFunction(SI);
11832 ++NumCombined;
11833 return 0;
11834 }
Chris Lattner836692d2007-01-15 06:51:56 +000011835 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011836
Dan Gohman9941f742007-07-20 16:34:21 +000011837 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011838 if (TD) {
11839 unsigned KnownAlign =
11840 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11841 if (KnownAlign >
11842 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11843 SI.getAlignment()))
11844 SI.setAlignment(KnownAlign);
11845 }
Dan Gohman9941f742007-07-20 16:34:21 +000011846
Dale Johannesenacb51a32009-03-03 01:43:03 +000011847 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011848 // stores to the same location, separated by a few arithmetic operations. This
11849 // situation often occurs with bitfield accesses.
11850 BasicBlock::iterator BBI = &SI;
11851 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11852 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011853 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011854 // Don't count debug info directives, lest they affect codegen,
11855 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11856 // It is necessary for correctness to skip those that feed into a
11857 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011858 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011859 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011860 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011861 continue;
11862 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011863
11864 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11865 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011866 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11867 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011868 ++NumDeadStore;
11869 ++BBI;
11870 EraseInstFromFunction(*PrevSI);
11871 continue;
11872 }
11873 break;
11874 }
11875
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011876 // If this is a load, we have to stop. However, if the loaded value is from
11877 // the pointer we're loading and is producing the pointer we're storing,
11878 // then *this* store is dead (X = load P; store X -> P).
11879 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011880 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11881 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011882 EraseInstFromFunction(SI);
11883 ++NumCombined;
11884 return 0;
11885 }
11886 // Otherwise, this is a load from some other location. Stores before it
11887 // may not be dead.
11888 break;
11889 }
11890
Chris Lattner9ca96412006-02-08 03:25:32 +000011891 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011892 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011893 break;
11894 }
11895
11896
11897 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011898
11899 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011900 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011901 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011902 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011903 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011904 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011905 ++NumCombined;
11906 }
11907 return 0; // Do not modify these!
11908 }
11909
11910 // store undef, Ptr -> noop
11911 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011912 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011913 ++NumCombined;
11914 return 0;
11915 }
11916
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011917 // If the pointer destination is a cast, see if we can fold the cast into the
11918 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011919 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011920 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11921 return Res;
11922 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011923 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011924 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11925 return Res;
11926
Chris Lattner408902b2005-09-12 23:23:25 +000011927
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011928 // If this store is the last instruction in the basic block (possibly
11929 // excepting debug info instructions and the pointer bitcasts that feed
11930 // into them), and if the block ends with an unconditional branch, try
11931 // to move it to the successor block.
11932 BBI = &SI;
11933 do {
11934 ++BBI;
11935 } while (isa<DbgInfoIntrinsic>(BBI) ||
11936 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011937 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011938 if (BI->isUnconditional())
11939 if (SimplifyStoreAtEndOfBlock(SI))
11940 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011941
Chris Lattner2f503e62005-01-31 05:36:43 +000011942 return 0;
11943}
11944
Chris Lattner3284d1f2007-04-15 00:07:55 +000011945/// SimplifyStoreAtEndOfBlock - Turn things like:
11946/// if () { *P = v1; } else { *P = v2 }
11947/// into a phi node with a store in the successor.
11948///
Chris Lattner31755a02007-04-15 01:02:18 +000011949/// Simplify things like:
11950/// *P = v1; if () { *P = v2; }
11951/// into a phi node with a store in the successor.
11952///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011953bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11954 BasicBlock *StoreBB = SI.getParent();
11955
11956 // Check to see if the successor block has exactly two incoming edges. If
11957 // so, see if the other predecessor contains a store to the same location.
11958 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011959 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011960
11961 // Determine whether Dest has exactly two predecessors and, if so, compute
11962 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011963 pred_iterator PI = pred_begin(DestBB);
11964 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011965 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011966 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011967 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011968 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011969 return false;
11970
11971 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011972 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011973 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011974 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011975 }
Chris Lattner31755a02007-04-15 01:02:18 +000011976 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011977 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011978
11979 // Bail out if all the relevant blocks aren't distinct (this can happen,
11980 // for example, if SI is in an infinite loop)
11981 if (StoreBB == DestBB || OtherBB == DestBB)
11982 return false;
11983
Chris Lattner31755a02007-04-15 01:02:18 +000011984 // Verify that the other block ends in a branch and is not otherwise empty.
11985 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011986 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011987 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011988 return false;
11989
Chris Lattner31755a02007-04-15 01:02:18 +000011990 // If the other block ends in an unconditional branch, check for the 'if then
11991 // else' case. there is an instruction before the branch.
11992 StoreInst *OtherStore = 0;
11993 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011994 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011995 // Skip over debugging info.
11996 while (isa<DbgInfoIntrinsic>(BBI) ||
11997 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11998 if (BBI==OtherBB->begin())
11999 return false;
12000 --BBI;
12001 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012002 // If this isn't a store, isn't a store to the same location, or if the
12003 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012004 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012005 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12006 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012007 return false;
12008 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012009 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012010 // destinations is StoreBB, then we have the if/then case.
12011 if (OtherBr->getSuccessor(0) != StoreBB &&
12012 OtherBr->getSuccessor(1) != StoreBB)
12013 return false;
12014
12015 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012016 // if/then triangle. See if there is a store to the same ptr as SI that
12017 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012018 for (;; --BBI) {
12019 // Check to see if we find the matching store.
12020 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012021 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12022 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012023 return false;
12024 break;
12025 }
Eli Friedman6903a242008-06-13 22:02:12 +000012026 // If we find something that may be using or overwriting the stored
12027 // value, or if we run out of instructions, we can't do the xform.
12028 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012029 BBI == OtherBB->begin())
12030 return false;
12031 }
12032
12033 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012034 // make sure nothing reads or overwrites the stored value in
12035 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012036 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12037 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012038 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012039 return false;
12040 }
12041 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012042
Chris Lattner31755a02007-04-15 01:02:18 +000012043 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012044 Value *MergedVal = OtherStore->getOperand(0);
12045 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012046 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012047 PN->reserveOperandSpace(2);
12048 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012049 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12050 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012051 }
12052
12053 // Advance to a place where it is safe to insert the new store and
12054 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012055 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012056 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012057 OtherStore->isVolatile(),
12058 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012059
12060 // Nuke the old stores.
12061 EraseInstFromFunction(SI);
12062 EraseInstFromFunction(*OtherStore);
12063 ++NumCombined;
12064 return true;
12065}
12066
Chris Lattner2f503e62005-01-31 05:36:43 +000012067
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012068Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12069 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012070 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012071 BasicBlock *TrueDest;
12072 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012073 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012074 !isa<Constant>(X)) {
12075 // Swap Destinations and condition...
12076 BI.setCondition(X);
12077 BI.setSuccessor(0, FalseDest);
12078 BI.setSuccessor(1, TrueDest);
12079 return &BI;
12080 }
12081
Reid Spencere4d87aa2006-12-23 06:05:41 +000012082 // Cannonicalize fcmp_one -> fcmp_oeq
12083 FCmpInst::Predicate FPred; Value *Y;
12084 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012085 TrueDest, FalseDest)) &&
12086 BI.getCondition()->hasOneUse())
12087 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12088 FPred == FCmpInst::FCMP_OGE) {
12089 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12090 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12091
12092 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012093 BI.setSuccessor(0, FalseDest);
12094 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012095 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012096 return &BI;
12097 }
12098
12099 // Cannonicalize icmp_ne -> icmp_eq
12100 ICmpInst::Predicate IPred;
12101 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012102 TrueDest, FalseDest)) &&
12103 BI.getCondition()->hasOneUse())
12104 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12105 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12106 IPred == ICmpInst::ICMP_SGE) {
12107 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12108 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12109 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012110 BI.setSuccessor(0, FalseDest);
12111 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012112 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012113 return &BI;
12114 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012115
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012116 return 0;
12117}
Chris Lattner0864acf2002-11-04 16:18:53 +000012118
Chris Lattner46238a62004-07-03 00:26:11 +000012119Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12120 Value *Cond = SI.getCondition();
12121 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12122 if (I->getOpcode() == Instruction::Add)
12123 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12124 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12125 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012126 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012127 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012128 AddRHS));
12129 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012130 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012131 return &SI;
12132 }
12133 }
12134 return 0;
12135}
12136
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012137Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012138 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012139
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012140 if (!EV.hasIndices())
12141 return ReplaceInstUsesWith(EV, Agg);
12142
12143 if (Constant *C = dyn_cast<Constant>(Agg)) {
12144 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012145 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012146
12147 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012148 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012149
12150 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12151 // Extract the element indexed by the first index out of the constant
12152 Value *V = C->getOperand(*EV.idx_begin());
12153 if (EV.getNumIndices() > 1)
12154 // Extract the remaining indices out of the constant indexed by the
12155 // first index
12156 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12157 else
12158 return ReplaceInstUsesWith(EV, V);
12159 }
12160 return 0; // Can't handle other constants
12161 }
12162 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12163 // We're extracting from an insertvalue instruction, compare the indices
12164 const unsigned *exti, *exte, *insi, *inse;
12165 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12166 exte = EV.idx_end(), inse = IV->idx_end();
12167 exti != exte && insi != inse;
12168 ++exti, ++insi) {
12169 if (*insi != *exti)
12170 // The insert and extract both reference distinctly different elements.
12171 // This means the extract is not influenced by the insert, and we can
12172 // replace the aggregate operand of the extract with the aggregate
12173 // operand of the insert. i.e., replace
12174 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12175 // %E = extractvalue { i32, { i32 } } %I, 0
12176 // with
12177 // %E = extractvalue { i32, { i32 } } %A, 0
12178 return ExtractValueInst::Create(IV->getAggregateOperand(),
12179 EV.idx_begin(), EV.idx_end());
12180 }
12181 if (exti == exte && insi == inse)
12182 // Both iterators are at the end: Index lists are identical. Replace
12183 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12184 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12185 // with "i32 42"
12186 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12187 if (exti == exte) {
12188 // The extract list is a prefix of the insert list. i.e. replace
12189 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12190 // %E = extractvalue { i32, { i32 } } %I, 1
12191 // with
12192 // %X = extractvalue { i32, { i32 } } %A, 1
12193 // %E = insertvalue { i32 } %X, i32 42, 0
12194 // by switching the order of the insert and extract (though the
12195 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012196 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12197 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012198 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12199 insi, inse);
12200 }
12201 if (insi == inse)
12202 // The insert list is a prefix of the extract list
12203 // We can simply remove the common indices from the extract and make it
12204 // operate on the inserted value instead of the insertvalue result.
12205 // i.e., replace
12206 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12207 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12208 // with
12209 // %E extractvalue { i32 } { i32 42 }, 0
12210 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12211 exti, exte);
12212 }
12213 // Can't simplify extracts from other values. Note that nested extracts are
12214 // already simplified implicitely by the above (extract ( extract (insert) )
12215 // will be translated into extract ( insert ( extract ) ) first and then just
12216 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012217 return 0;
12218}
12219
Chris Lattner220b0cf2006-03-05 00:22:33 +000012220/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12221/// is to leave as a vector operation.
12222static bool CheapToScalarize(Value *V, bool isConstant) {
12223 if (isa<ConstantAggregateZero>(V))
12224 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012225 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012226 if (isConstant) return true;
12227 // If all elts are the same, we can extract.
12228 Constant *Op0 = C->getOperand(0);
12229 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12230 if (C->getOperand(i) != Op0)
12231 return false;
12232 return true;
12233 }
12234 Instruction *I = dyn_cast<Instruction>(V);
12235 if (!I) return false;
12236
12237 // Insert element gets simplified to the inserted element or is deleted if
12238 // this is constant idx extract element and its a constant idx insertelt.
12239 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12240 isa<ConstantInt>(I->getOperand(2)))
12241 return true;
12242 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12243 return true;
12244 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12245 if (BO->hasOneUse() &&
12246 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12247 CheapToScalarize(BO->getOperand(1), isConstant)))
12248 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012249 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12250 if (CI->hasOneUse() &&
12251 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12252 CheapToScalarize(CI->getOperand(1), isConstant)))
12253 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012254
12255 return false;
12256}
12257
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012258/// Read and decode a shufflevector mask.
12259///
12260/// It turns undef elements into values that are larger than the number of
12261/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012262static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12263 unsigned NElts = SVI->getType()->getNumElements();
12264 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12265 return std::vector<unsigned>(NElts, 0);
12266 if (isa<UndefValue>(SVI->getOperand(2)))
12267 return std::vector<unsigned>(NElts, 2*NElts);
12268
12269 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012270 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012271 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12272 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012273 Result.push_back(NElts*2); // undef -> 8
12274 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012275 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012276 return Result;
12277}
12278
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012279/// FindScalarElement - Given a vector and an element number, see if the scalar
12280/// value is already around as a register, for example if it were inserted then
12281/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012282static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012283 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012284 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12285 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012286 unsigned Width = PTy->getNumElements();
12287 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012288 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012289
12290 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012291 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012292 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012293 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012294 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012295 return CP->getOperand(EltNo);
12296 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12297 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012298 if (!isa<ConstantInt>(III->getOperand(2)))
12299 return 0;
12300 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012301
12302 // If this is an insert to the element we are looking for, return the
12303 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012304 if (EltNo == IIElt)
12305 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012306
12307 // Otherwise, the insertelement doesn't modify the value, recurse on its
12308 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012309 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012310 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012311 unsigned LHSWidth =
12312 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012313 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012314 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012315 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012316 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012317 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012318 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012319 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012320 }
12321
12322 // Otherwise, we don't know.
12323 return 0;
12324}
12325
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012326Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012327 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012328 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012329 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012330
Dan Gohman07a96762007-07-16 14:29:03 +000012331 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012332 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012333 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012334
Reid Spencer9d6565a2007-02-15 02:26:10 +000012335 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012336 // If vector val is constant with all elements the same, replace EI with
12337 // that element. When the elements are not identical, we cannot replace yet
12338 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012339 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012340 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012341 if (C->getOperand(i) != op0) {
12342 op0 = 0;
12343 break;
12344 }
12345 if (op0)
12346 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012347 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012348
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012349 // If extracting a specified index from the vector, see if we can recursively
12350 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012351 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012352 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012353 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012354
12355 // If this is extracting an invalid index, turn this into undef, to avoid
12356 // crashing the code below.
12357 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012358 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012359
Chris Lattner867b99f2006-10-05 06:55:50 +000012360 // This instruction only demands the single element from the input vector.
12361 // If the input vector has a single use, simplify it based on this use
12362 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012363 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012364 APInt UndefElts(VectorWidth, 0);
12365 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012366 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012367 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012368 EI.setOperand(0, V);
12369 return &EI;
12370 }
12371 }
12372
Owen Andersond672ecb2009-07-03 00:17:18 +000012373 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012374 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012375
12376 // If the this extractelement is directly using a bitcast from a vector of
12377 // the same number of elements, see if we can find the source element from
12378 // it. In this case, we will end up needing to bitcast the scalars.
12379 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12380 if (const VectorType *VT =
12381 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12382 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012383 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12384 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012385 return new BitCastInst(Elt, EI.getType());
12386 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012387 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012388
Chris Lattner73fa49d2006-05-25 22:53:38 +000012389 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012390 // Push extractelement into predecessor operation if legal and
12391 // profitable to do so
12392 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12393 if (I->hasOneUse() &&
12394 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12395 Value *newEI0 =
12396 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12397 EI.getName()+".lhs");
12398 Value *newEI1 =
12399 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12400 EI.getName()+".rhs");
12401 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012402 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012403 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012404 // Extracting the inserted element?
12405 if (IE->getOperand(2) == EI.getOperand(1))
12406 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12407 // If the inserted and extracted elements are constants, they must not
12408 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012409 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012410 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012411 EI.setOperand(0, IE->getOperand(0));
12412 return &EI;
12413 }
12414 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12415 // If this is extracting an element from a shufflevector, figure out where
12416 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012417 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12418 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012419 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012420 unsigned LHSWidth =
12421 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12422
12423 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012424 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012425 else if (SrcIdx < LHSWidth*2) {
12426 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012427 Src = SVI->getOperand(1);
12428 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012429 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012430 }
Eric Christophera3500da2009-07-25 02:28:41 +000012431 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012432 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12433 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012434 }
12435 }
Eli Friedman2451a642009-07-18 23:06:53 +000012436 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012437 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012438 return 0;
12439}
12440
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012441/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12442/// elements from either LHS or RHS, return the shuffle mask and true.
12443/// Otherwise, return false.
12444static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012445 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012446 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012447 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12448 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012449 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012450
12451 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012452 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012453 return true;
12454 } else if (V == LHS) {
12455 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012456 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012457 return true;
12458 } else if (V == RHS) {
12459 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012460 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012461 return true;
12462 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12463 // If this is an insert of an extract from some other vector, include it.
12464 Value *VecOp = IEI->getOperand(0);
12465 Value *ScalarOp = IEI->getOperand(1);
12466 Value *IdxOp = IEI->getOperand(2);
12467
Chris Lattnerd929f062006-04-27 21:14:21 +000012468 if (!isa<ConstantInt>(IdxOp))
12469 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012470 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012471
12472 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12473 // Okay, we can handle this if the vector we are insertinting into is
12474 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012475 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012476 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012477 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012478 return true;
12479 }
12480 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12481 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012482 EI->getOperand(0)->getType() == V->getType()) {
12483 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012484 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012485
12486 // This must be extracting from either LHS or RHS.
12487 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12488 // Okay, we can handle this if the vector we are insertinting into is
12489 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012490 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012491 // If so, update the mask to reflect the inserted value.
12492 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012493 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012494 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012495 } else {
12496 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012497 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012498 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012499
12500 }
12501 return true;
12502 }
12503 }
12504 }
12505 }
12506 }
12507 // TODO: Handle shufflevector here!
12508
12509 return false;
12510}
12511
12512/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12513/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12514/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012515static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012516 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012517 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012518 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012519 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012520 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012521
12522 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012523 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012524 return V;
12525 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012526 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012527 return V;
12528 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12529 // If this is an insert of an extract from some other vector, include it.
12530 Value *VecOp = IEI->getOperand(0);
12531 Value *ScalarOp = IEI->getOperand(1);
12532 Value *IdxOp = IEI->getOperand(2);
12533
12534 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12535 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12536 EI->getOperand(0)->getType() == V->getType()) {
12537 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012538 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12539 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012540
12541 // Either the extracted from or inserted into vector must be RHSVec,
12542 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012543 if (EI->getOperand(0) == RHS || RHS == 0) {
12544 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012545 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012546 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012547 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012548 return V;
12549 }
12550
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012551 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012552 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12553 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012554 // Everything but the extracted element is replaced with the RHS.
12555 for (unsigned i = 0; i != NumElts; ++i) {
12556 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012557 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012558 }
12559 return V;
12560 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012561
12562 // If this insertelement is a chain that comes from exactly these two
12563 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012564 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12565 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012566 return EI->getOperand(0);
12567
Chris Lattnerefb47352006-04-15 01:39:45 +000012568 }
12569 }
12570 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012571 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012572
12573 // Otherwise, can't do anything fancy. Return an identity vector.
12574 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012575 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012576 return V;
12577}
12578
12579Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12580 Value *VecOp = IE.getOperand(0);
12581 Value *ScalarOp = IE.getOperand(1);
12582 Value *IdxOp = IE.getOperand(2);
12583
Chris Lattner599ded12007-04-09 01:11:16 +000012584 // Inserting an undef or into an undefined place, remove this.
12585 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12586 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012587
Chris Lattnerefb47352006-04-15 01:39:45 +000012588 // If the inserted element was extracted from some other vector, and if the
12589 // indexes are constant, try to turn this into a shufflevector operation.
12590 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12591 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12592 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012593 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012594 unsigned ExtractedIdx =
12595 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012596 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012597
12598 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12599 return ReplaceInstUsesWith(IE, VecOp);
12600
12601 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012602 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012603
12604 // If we are extracting a value from a vector, then inserting it right
12605 // back into the same place, just use the input vector.
12606 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12607 return ReplaceInstUsesWith(IE, VecOp);
12608
Chris Lattnerefb47352006-04-15 01:39:45 +000012609 // If this insertelement isn't used by some other insertelement, turn it
12610 // (and any insertelements it points to), into one big shuffle.
12611 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12612 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012613 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012614 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012615 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012616 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012617 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012618 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012619 }
12620 }
12621 }
12622
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012623 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12624 APInt UndefElts(VWidth, 0);
12625 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12626 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12627 return &IE;
12628
Chris Lattnerefb47352006-04-15 01:39:45 +000012629 return 0;
12630}
12631
12632
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012633Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12634 Value *LHS = SVI.getOperand(0);
12635 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012636 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012637
12638 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012639
Chris Lattner867b99f2006-10-05 06:55:50 +000012640 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012641 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012642 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012643
Dan Gohman488fbfc2008-09-09 18:11:14 +000012644 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012645
12646 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12647 return 0;
12648
Evan Cheng388df622009-02-03 10:05:09 +000012649 APInt UndefElts(VWidth, 0);
12650 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12651 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012652 LHS = SVI.getOperand(0);
12653 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012654 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012655 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012656
Chris Lattner863bcff2006-05-25 23:48:38 +000012657 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12658 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12659 if (LHS == RHS || isa<UndefValue>(LHS)) {
12660 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012661 // shuffle(undef,undef,mask) -> undef.
12662 return ReplaceInstUsesWith(SVI, LHS);
12663 }
12664
Chris Lattner863bcff2006-05-25 23:48:38 +000012665 // Remap any references to RHS to use LHS.
12666 std::vector<Constant*> Elts;
12667 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012668 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012669 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012670 else {
12671 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012672 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012673 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012674 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012675 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012676 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012677 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012678 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012679 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012680 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012681 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012682 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012683 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012684 LHS = SVI.getOperand(0);
12685 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012686 MadeChange = true;
12687 }
12688
Chris Lattner7b2e27922006-05-26 00:29:06 +000012689 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012690 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012691
Chris Lattner863bcff2006-05-25 23:48:38 +000012692 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12693 if (Mask[i] >= e*2) continue; // Ignore undef values.
12694 // Is this an identity shuffle of the LHS value?
12695 isLHSID &= (Mask[i] == i);
12696
12697 // Is this an identity shuffle of the RHS value?
12698 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012699 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012700
Chris Lattner863bcff2006-05-25 23:48:38 +000012701 // Eliminate identity shuffles.
12702 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12703 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012704
Chris Lattner7b2e27922006-05-26 00:29:06 +000012705 // If the LHS is a shufflevector itself, see if we can combine it with this
12706 // one without producing an unusual shuffle. Here we are really conservative:
12707 // we are absolutely afraid of producing a shuffle mask not in the input
12708 // program, because the code gen may not be smart enough to turn a merged
12709 // shuffle into two specific shuffles: it may produce worse code. As such,
12710 // we only merge two shuffles if the result is one of the two input shuffle
12711 // masks. In this case, merging the shuffles just removes one instruction,
12712 // which we know is safe. This is good for things like turning:
12713 // (splat(splat)) -> splat.
12714 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12715 if (isa<UndefValue>(RHS)) {
12716 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12717
12718 std::vector<unsigned> NewMask;
12719 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12720 if (Mask[i] >= 2*e)
12721 NewMask.push_back(2*e);
12722 else
12723 NewMask.push_back(LHSMask[Mask[i]]);
12724
12725 // If the result mask is equal to the src shuffle or this shuffle mask, do
12726 // the replacement.
12727 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012728 unsigned LHSInNElts =
12729 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012730 std::vector<Constant*> Elts;
12731 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012732 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012733 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012734 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012735 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012736 }
12737 }
12738 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12739 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012740 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012741 }
12742 }
12743 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012744
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012745 return MadeChange ? &SVI : 0;
12746}
12747
12748
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012749
Chris Lattnerea1c4542004-12-08 23:43:58 +000012750
12751/// TryToSinkInstruction - Try to move the specified instruction from its
12752/// current block into the beginning of DestBlock, which can only happen if it's
12753/// safe to move the instruction past all of the instructions between it and the
12754/// end of its block.
12755static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12756 assert(I->hasOneUse() && "Invariants didn't hold!");
12757
Chris Lattner108e9022005-10-27 17:13:11 +000012758 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012759 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012760 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012761
Chris Lattnerea1c4542004-12-08 23:43:58 +000012762 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012763 if (isa<AllocaInst>(I) && I->getParent() ==
12764 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012765 return false;
12766
Chris Lattner96a52a62004-12-09 07:14:34 +000012767 // We can only sink load instructions if there is nothing between the load and
12768 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012769 if (I->mayReadFromMemory()) {
12770 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012771 Scan != E; ++Scan)
12772 if (Scan->mayWriteToMemory())
12773 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012774 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012775
Dan Gohman02dea8b2008-05-23 21:05:58 +000012776 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012777
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012778 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012779 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012780 ++NumSunkInst;
12781 return true;
12782}
12783
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012784
12785/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12786/// all reachable code to the worklist.
12787///
12788/// This has a couple of tricks to make the code faster and more powerful. In
12789/// particular, we constant fold and DCE instructions as we go, to avoid adding
12790/// them to the worklist (this significantly speeds up instcombine on code where
12791/// many instructions are dead or constant). Additionally, if we find a branch
12792/// whose condition is a known constant, we only visit the reachable successors.
12793///
Chris Lattner2ee743b2009-10-15 04:59:28 +000012794static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012795 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012796 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012797 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000012798 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000012799 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012800 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000012801
12802 std::vector<Instruction*> InstrsForInstCombineWorklist;
12803 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012804
Chris Lattner2ee743b2009-10-15 04:59:28 +000012805 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12806
Chris Lattner2c7718a2007-03-23 19:17:18 +000012807 while (!Worklist.empty()) {
12808 BB = Worklist.back();
12809 Worklist.pop_back();
12810
12811 // We have now visited this block! If we've already been here, ignore it.
12812 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012813
Chris Lattner2c7718a2007-03-23 19:17:18 +000012814 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12815 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012816
Chris Lattner2c7718a2007-03-23 19:17:18 +000012817 // DCE instruction if trivially dead.
12818 if (isInstructionTriviallyDead(Inst)) {
12819 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012820 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012821 Inst->eraseFromParent();
12822 continue;
12823 }
12824
12825 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012826 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000012827 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012828 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12829 << *Inst << '\n');
12830 Inst->replaceAllUsesWith(C);
12831 ++NumConstProp;
12832 Inst->eraseFromParent();
12833 continue;
12834 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000012835
12836
12837
12838 if (TD) {
12839 // See if we can constant fold its operands.
12840 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12841 i != e; ++i) {
12842 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12843 if (CE == 0) continue;
12844
12845 // If we already folded this constant, don't try again.
12846 if (!FoldedConstants.insert(CE))
12847 continue;
12848
Chris Lattner7b550cc2009-11-06 04:27:31 +000012849 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000012850 if (NewC && NewC != CE) {
12851 *i = NewC;
12852 MadeIRChange = true;
12853 }
12854 }
12855 }
12856
Devang Patel7fe1dec2008-11-19 18:56:50 +000012857
Chris Lattner67f7d542009-10-12 03:58:40 +000012858 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012859 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012860
12861 // Recursively visit successors. If this is a branch or switch on a
12862 // constant, only visit the reachable successor.
12863 TerminatorInst *TI = BB->getTerminator();
12864 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12865 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12866 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012867 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012868 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012869 continue;
12870 }
12871 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12872 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12873 // See if this is an explicit destination.
12874 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12875 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012876 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012877 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012878 continue;
12879 }
12880
12881 // Otherwise it is the default destination.
12882 Worklist.push_back(SI->getSuccessor(0));
12883 continue;
12884 }
12885 }
12886
12887 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12888 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012889 }
Chris Lattner67f7d542009-10-12 03:58:40 +000012890
12891 // Once we've found all of the instructions to add to instcombine's worklist,
12892 // add them in reverse order. This way instcombine will visit from the top
12893 // of the function down. This jives well with the way that it adds all uses
12894 // of instructions to the worklist after doing a transformation, thus avoiding
12895 // some N^2 behavior in pathological cases.
12896 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12897 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000012898
12899 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012900}
12901
Chris Lattnerec9c3582007-03-03 02:04:50 +000012902bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012903 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012904
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012905 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12906 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012907
Chris Lattnerb3d59702005-07-07 20:40:38 +000012908 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012909 // Do a depth-first traversal of the function, populate the worklist with
12910 // the reachable instructions. Ignore blocks that are not reachable. Keep
12911 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012912 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000012913 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012914
Chris Lattnerb3d59702005-07-07 20:40:38 +000012915 // Do a quick scan over the function. If we find any blocks that are
12916 // unreachable, remove any instructions inside of them. This prevents
12917 // the instcombine code from having to deal with some bad special cases.
12918 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12919 if (!Visited.count(BB)) {
12920 Instruction *Term = BB->getTerminator();
12921 while (Term != BB->begin()) { // Remove instrs bottom-up
12922 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012923
Chris Lattnerbdff5482009-08-23 04:37:46 +000012924 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012925 // A debug intrinsic shouldn't force another iteration if we weren't
12926 // going to do one without it.
12927 if (!isa<DbgInfoIntrinsic>(I)) {
12928 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012929 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000012930 }
Devang Patel228ebd02009-10-13 22:56:32 +000012931
Devang Patel228ebd02009-10-13 22:56:32 +000012932 // If I is not void type then replaceAllUsesWith undef.
12933 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000012934 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000012935 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012936 I->eraseFromParent();
12937 }
12938 }
12939 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012940
Chris Lattner873ff012009-08-30 05:55:36 +000012941 while (!Worklist.isEmpty()) {
12942 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012943 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012944
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012945 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012946 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012947 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012948 EraseInstFromFunction(*I);
12949 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012950 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012951 continue;
12952 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012953
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012954 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012955 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000012956 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012957 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012958
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012959 // Add operands to the worklist.
12960 ReplaceInstUsesWith(*I, C);
12961 ++NumConstProp;
12962 EraseInstFromFunction(*I);
12963 MadeIRChange = true;
12964 continue;
12965 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012966
Chris Lattnerea1c4542004-12-08 23:43:58 +000012967 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012968 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012969 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000012970 Instruction *UserInst = cast<Instruction>(I->use_back());
12971 BasicBlock *UserParent;
12972
12973 // Get the block the use occurs in.
12974 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12975 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12976 else
12977 UserParent = UserInst->getParent();
12978
Chris Lattnerea1c4542004-12-08 23:43:58 +000012979 if (UserParent != BB) {
12980 bool UserIsSuccessor = false;
12981 // See if the user is one of our successors.
12982 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12983 if (*SI == UserParent) {
12984 UserIsSuccessor = true;
12985 break;
12986 }
12987
12988 // If the user is one of our immediate successors, and if that successor
12989 // only has us as a predecessors (we'd have to split the critical edge
12990 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000012991 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012992 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012993 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012994 }
12995 }
12996
Chris Lattner74381062009-08-30 07:44:24 +000012997 // Now that we have an instruction, try combining it to simplify it.
12998 Builder->SetInsertPoint(I->getParent(), I);
12999
Reid Spencera9b81012007-03-26 17:44:01 +000013000#ifndef NDEBUG
13001 std::string OrigI;
13002#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013003 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000013004 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13005
Chris Lattner90ac28c2002-08-02 19:29:35 +000013006 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013007 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013008 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013009 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013010 DEBUG(errs() << "IC: Old = " << *I << '\n'
13011 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013012
Chris Lattnerf523d062004-06-09 05:08:07 +000013013 // Everything uses the new instruction now.
13014 I->replaceAllUsesWith(Result);
13015
13016 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013017 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013018 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013019
Chris Lattner6934a042007-02-11 01:23:03 +000013020 // Move the name to the new instruction first.
13021 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013022
13023 // Insert the new instruction into the basic block...
13024 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013025 BasicBlock::iterator InsertPos = I;
13026
13027 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13028 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13029 ++InsertPos;
13030
13031 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013032
Chris Lattner7a1e9242009-08-30 06:13:40 +000013033 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000013034 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013035#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013036 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13037 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013038#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013039
Chris Lattner90ac28c2002-08-02 19:29:35 +000013040 // If the instruction was modified, it's possible that it is now dead.
13041 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013042 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013043 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000013044 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013045 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013046 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013047 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013048 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013049 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013050 }
13051 }
13052
Chris Lattner873ff012009-08-30 05:55:36 +000013053 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013054 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013055}
13056
Chris Lattnerec9c3582007-03-03 02:04:50 +000013057
13058bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013059 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013060 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013061 TD = getAnalysisIfAvailable<TargetData>();
13062
Chris Lattner74381062009-08-30 07:44:24 +000013063
13064 /// Builder - This is an IRBuilder that automatically inserts new
13065 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013066 IRBuilder<true, TargetFolder, InstCombineIRInserter>
13067 TheBuilder(F.getContext(), TargetFolder(TD, F.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +000013068 InstCombineIRInserter(Worklist));
13069 Builder = &TheBuilder;
13070
Chris Lattnerec9c3582007-03-03 02:04:50 +000013071 bool EverMadeChange = false;
13072
13073 // Iterate while there is work to do.
13074 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013075 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013076 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000013077
13078 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013079 return EverMadeChange;
13080}
13081
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013082FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013083 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013084}