blob: 4af6c1c41f646a120c6d7822768ca2710b8d49a2 [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 Hernandezf2becca2009-10-26 23:58:56 +000045#include "llvm/Analysis/MallocFreeHelper.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 Lattner7e708292002-06-25 16:13:24 +0000220 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000221 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000222 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000223 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000224 Instruction *visitURem(BinaryOperator &I);
225 Instruction *visitSRem(BinaryOperator &I);
226 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000227 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000228 Instruction *commonRemTransforms(BinaryOperator &I);
229 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000230 Instruction *commonDivTransforms(BinaryOperator &I);
231 Instruction *commonIDivTransforms(BinaryOperator &I);
232 Instruction *visitUDiv(BinaryOperator &I);
233 Instruction *visitSDiv(BinaryOperator &I);
234 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000235 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000236 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000237 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000238 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000239 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000240 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000241 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000242 Instruction *visitOr (BinaryOperator &I);
243 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000244 Instruction *visitShl(BinaryOperator &I);
245 Instruction *visitAShr(BinaryOperator &I);
246 Instruction *visitLShr(BinaryOperator &I);
247 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000248 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
249 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000250 Instruction *visitFCmpInst(FCmpInst &I);
251 Instruction *visitICmpInst(ICmpInst &I);
252 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000253 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
254 Instruction *LHS,
255 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000256 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
257 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000258
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000259 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000260 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000261 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000262 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000263 Instruction *commonCastTransforms(CastInst &CI);
264 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000265 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000266 Instruction *visitTrunc(TruncInst &CI);
267 Instruction *visitZExt(ZExtInst &CI);
268 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000269 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000270 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000271 Instruction *visitFPToUI(FPToUIInst &FI);
272 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000273 Instruction *visitUIToFP(CastInst &CI);
274 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000275 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000276 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000277 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000278 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
279 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000280 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000281 Instruction *visitSelectInst(SelectInst &SI);
282 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000283 Instruction *visitCallInst(CallInst &CI);
284 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000285 Instruction *visitPHINode(PHINode &PN);
286 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000287 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000288 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000289 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000290 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000291 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000292 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000293 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000294 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000295 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000296 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000297
298 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000299 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000300
Chris Lattner9fe38862003-06-19 17:00:31 +0000301 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000302 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000303 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000304 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000305 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
306 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000307 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000308 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
309
Chris Lattner9fe38862003-06-19 17:00:31 +0000310
Chris Lattner28977af2004-04-05 01:30:19 +0000311 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000312 // InsertNewInstBefore - insert an instruction New before instruction Old
313 // in the program. Add the new instruction to the worklist.
314 //
Chris Lattner955f3312004-09-28 21:48:02 +0000315 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000316 assert(New && New->getParent() == 0 &&
317 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000318 BasicBlock *BB = Old.getParent();
319 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000320 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000321 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000322 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000323
Chris Lattner8b170942002-08-09 23:47:40 +0000324 // ReplaceInstUsesWith - This method is to be used when an instruction is
325 // found to be dead, replacable with another preexisting expression. Here
326 // we add all uses of I to the worklist, replace all uses of I with the new
327 // value, then return I, so that the inst combiner will know that I was
328 // modified.
329 //
330 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000331 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000332
333 // If we are replacing the instruction with itself, this must be in a
334 // segment of unreachable code, so just clobber the instruction.
335 if (&I == V)
336 V = UndefValue::get(I.getType());
337
338 I.replaceAllUsesWith(V);
339 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000340 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000341
342 // EraseInstFromFunction - When dealing with an instruction that has side
343 // effects or produces a void value, we can't rely on DCE to delete the
344 // instruction. Instead, visit methods should return the value returned by
345 // this function.
346 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000347 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000348
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000349 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000350 // Make sure that we reprocess all operands now that we reduced their
351 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000352 if (I.getNumOperands() < 8) {
353 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
354 if (Instruction *Op = dyn_cast<Instruction>(*i))
355 Worklist.Add(Op);
356 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000357 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000358 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000359 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000360 return 0; // Don't do anything with FI
361 }
Chris Lattner173234a2008-06-02 01:18:21 +0000362
363 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
364 APInt &KnownOne, unsigned Depth = 0) const {
365 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
366 }
367
368 bool MaskedValueIsZero(Value *V, const APInt &Mask,
369 unsigned Depth = 0) const {
370 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
371 }
372 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
373 return llvm::ComputeNumSignBits(Op, TD, Depth);
374 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000375
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000376 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000377
Reid Spencere4d87aa2006-12-23 06:05:41 +0000378 /// SimplifyCommutative - This performs a few simplifications for
379 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000380 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000381
Reid Spencere4d87aa2006-12-23 06:05:41 +0000382 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
383 /// most-complex to least-complex order.
384 bool SimplifyCompare(CmpInst &I);
385
Chris Lattner886ab6c2009-01-31 08:15:18 +0000386 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
387 /// based on the demanded bits.
388 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
389 APInt& KnownZero, APInt& KnownOne,
390 unsigned Depth);
391 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000392 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000393 unsigned Depth=0);
394
395 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
396 /// SimplifyDemandedBits knows about. See if the instruction has any
397 /// properties that allow us to simplify its operands.
398 bool SimplifyDemandedInstructionBits(Instruction &Inst);
399
Evan Cheng388df622009-02-03 10:05:09 +0000400 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
401 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000402
Chris Lattner5d1704d2009-09-27 19:57:57 +0000403 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
404 // which has a PHI node as operand #0, see if we can fold the instruction
405 // into the PHI (which is only possible if all operands to the PHI are
406 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000407 //
408 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
409 // that would normally be unprofitable because they strongly encourage jump
410 // threading.
411 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000412
Chris Lattnerbac32862004-11-14 19:13:23 +0000413 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
414 // operator and they all are only used by the PHI, PHI together their
415 // inputs, and do the operation once, to the result of the PHI.
416 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000417 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000418 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
419
Chris Lattner7da52b22006-11-01 04:51:18 +0000420
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000421 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
422 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000423
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000424 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000425 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000426 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000427 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000428 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000429 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000430 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000431 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000432 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000433
Chris Lattnerafe91a52006-06-15 19:07:26 +0000434
Reid Spencerc55b2432006-12-13 18:21:21 +0000435 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000436
Dan Gohman6de29f82009-06-15 22:12:54 +0000437 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000438 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000439 unsigned GetOrEnforceKnownAlignment(Value *V,
440 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000441
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000442 };
Chris Lattner873ff012009-08-30 05:55:36 +0000443} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000444
Dan Gohman844731a2008-05-13 00:00:25 +0000445char InstCombiner::ID = 0;
446static RegisterPass<InstCombiner>
447X("instcombine", "Combine redundant instructions");
448
Chris Lattner4f98c562003-03-10 21:43:22 +0000449// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000450// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000451static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000452 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000453 if (BinaryOperator::isNeg(V) ||
454 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000455 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000456 return 3;
457 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000458 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000459 if (isa<Argument>(V)) return 3;
460 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000461}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000462
Chris Lattnerc8802d22003-03-11 00:12:48 +0000463// isOnlyUse - Return true if this instruction will be deleted if we stop using
464// it.
465static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000466 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000467}
468
Chris Lattner4cb170c2004-02-23 06:38:22 +0000469// getPromotedType - Return the specified type promoted as it would be to pass
470// though a va_arg area...
471static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000472 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
473 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000474 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000475 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000476 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000477}
478
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000479/// getBitCastOperand - If the specified operand is a CastInst, a constant
480/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
481/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000482static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000483 if (Operator *O = dyn_cast<Operator>(V)) {
484 if (O->getOpcode() == Instruction::BitCast)
485 return O->getOperand(0);
486 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
487 if (GEP->hasAllZeroIndices())
488 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000489 }
Chris Lattnereed48272005-09-13 00:40:14 +0000490 return 0;
491}
492
Reid Spencer3da59db2006-11-27 01:05:10 +0000493/// This function is a wrapper around CastInst::isEliminableCastPair. It
494/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000495static Instruction::CastOps
496isEliminableCastPair(
497 const CastInst *CI, ///< The first cast instruction
498 unsigned opcode, ///< The opcode of the second cast instruction
499 const Type *DstTy, ///< The target type for the second cast instruction
500 TargetData *TD ///< The target data for pointer size
501) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000502
Reid Spencer3da59db2006-11-27 01:05:10 +0000503 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
504 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000505
Reid Spencer3da59db2006-11-27 01:05:10 +0000506 // Get the opcodes of the two Cast instructions
507 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
508 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000509
Chris Lattnera0e69692009-03-24 18:35:40 +0000510 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000511 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000512 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000513
514 // We don't want to form an inttoptr or ptrtoint that converts to an integer
515 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000516 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000517 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000518 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000519 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000520 Res = 0;
521
522 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000523}
524
525/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
526/// in any code being generated. It does not require codegen if V is simple
527/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000528static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
529 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000530 if (V->getType() == Ty || isa<Constant>(V)) return false;
531
Chris Lattner01575b72006-05-25 23:24:33 +0000532 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000533 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000534 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000535 return false;
536 return true;
537}
538
Chris Lattner4f98c562003-03-10 21:43:22 +0000539// SimplifyCommutative - This performs a few simplifications for commutative
540// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000541//
Chris Lattner4f98c562003-03-10 21:43:22 +0000542// 1. Order operands such that they are listed from right (least complex) to
543// left (most complex). This puts constants before unary operators before
544// binary operators.
545//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000546// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
547// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000548//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000549bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000550 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000551 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000552 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000553
Chris Lattner4f98c562003-03-10 21:43:22 +0000554 if (!I.isAssociative()) return Changed;
555 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000556 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
557 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
558 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000559 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000560 cast<Constant>(I.getOperand(1)),
561 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000562 I.setOperand(0, Op->getOperand(0));
563 I.setOperand(1, Folded);
564 return true;
565 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
566 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
567 isOnlyUse(Op) && isOnlyUse(Op1)) {
568 Constant *C1 = cast<Constant>(Op->getOperand(1));
569 Constant *C2 = cast<Constant>(Op1->getOperand(1));
570
571 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000572 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000573 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000574 Op1->getOperand(0),
575 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000576 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000577 I.setOperand(0, New);
578 I.setOperand(1, Folded);
579 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000580 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000581 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000582 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000583}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000584
Reid Spencere4d87aa2006-12-23 06:05:41 +0000585/// SimplifyCompare - For a CmpInst this function just orders the operands
586/// so that theyare listed from right (least complex) to left (most complex).
587/// This puts constants before unary operators before binary operators.
588bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000589 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000590 return false;
591 I.swapOperands();
592 // Compare instructions are not associative so there's nothing else we can do.
593 return true;
594}
595
Chris Lattner8d969642003-03-10 23:06:50 +0000596// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
597// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000598//
Dan Gohman186a6362009-08-12 16:04:34 +0000599static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000600 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000601 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000602
Chris Lattner0ce85802004-12-14 20:08:06 +0000603 // Constants can be considered to be negated values if they can be folded.
604 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000605 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000606
607 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
608 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000609 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000610
Chris Lattner8d969642003-03-10 23:06:50 +0000611 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000612}
613
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000614// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
615// instruction if the LHS is a constant negative zero (which is the 'negate'
616// form).
617//
Dan Gohman186a6362009-08-12 16:04:34 +0000618static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000619 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000620 return BinaryOperator::getFNegArgument(V);
621
622 // Constants can be considered to be negated values if they can be folded.
623 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000624 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000625
626 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
627 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000628 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000629
630 return 0;
631}
632
Chris Lattner48b59ec2009-10-26 15:40:07 +0000633/// isFreeToInvert - Return true if the specified value is free to invert (apply
634/// ~ to). This happens in cases where the ~ can be eliminated.
635static inline bool isFreeToInvert(Value *V) {
636 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000637 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000638 return true;
639
640 // Constants can be considered to be not'ed values.
641 if (isa<ConstantInt>(V))
642 return true;
643
644 // Compares can be inverted if they have a single use.
645 if (CmpInst *CI = dyn_cast<CmpInst>(V))
646 return CI->hasOneUse();
647
648 return false;
649}
650
651static inline Value *dyn_castNotVal(Value *V) {
652 // If this is not(not(x)) don't return that this is a not: we want the two
653 // not's to be folded first.
654 if (BinaryOperator::isNot(V)) {
655 Value *Operand = BinaryOperator::getNotArgument(V);
656 if (!isFreeToInvert(Operand))
657 return Operand;
658 }
Chris Lattner8d969642003-03-10 23:06:50 +0000659
660 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000661 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000662 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000663 return 0;
664}
665
Chris Lattner48b59ec2009-10-26 15:40:07 +0000666
667
Chris Lattnerc8802d22003-03-11 00:12:48 +0000668// dyn_castFoldableMul - If this value is a multiply that can be folded into
669// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000670// non-constant operand of the multiply, and set CST to point to the multiplier.
671// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000672//
Dan Gohman186a6362009-08-12 16:04:34 +0000673static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000674 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000675 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000676 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000677 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000678 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000679 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000680 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000681 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000682 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000683 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000684 CST = ConstantInt::get(V->getType()->getContext(),
685 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000686 return I->getOperand(0);
687 }
688 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000689 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000690}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000691
Reid Spencer7177c3a2007-03-25 05:33:51 +0000692/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000693static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000694 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000695 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000696}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000697/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000698static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000699 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000700 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000701}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000702/// MultiplyOverflows - True if the multiply can not be expressed in an int
703/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000704static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000705 uint32_t W = C1->getBitWidth();
706 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
707 if (sign) {
708 LHSExt.sext(W * 2);
709 RHSExt.sext(W * 2);
710 } else {
711 LHSExt.zext(W * 2);
712 RHSExt.zext(W * 2);
713 }
714
715 APInt MulExt = LHSExt * RHSExt;
716
717 if (sign) {
718 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
719 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
720 return MulExt.slt(Min) || MulExt.sgt(Max);
721 } else
722 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
723}
Chris Lattner955f3312004-09-28 21:48:02 +0000724
Reid Spencere7816b52007-03-08 01:52:58 +0000725
Chris Lattner255d8912006-02-11 09:31:47 +0000726/// ShrinkDemandedConstant - Check to see if the specified operand of the
727/// specified instruction is a constant integer. If so, check to see if there
728/// are any bits set in the constant that are not demanded. If so, shrink the
729/// constant and return true.
730static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000731 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000732 assert(I && "No instruction?");
733 assert(OpNo < I->getNumOperands() && "Operand index too large");
734
735 // If the operand is not a constant integer, nothing to do.
736 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
737 if (!OpC) return false;
738
739 // If there are no bits set that aren't demanded, nothing to do.
740 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
741 if ((~Demanded & OpC->getValue()) == 0)
742 return false;
743
744 // This instruction is producing bits that are not demanded. Shrink the RHS.
745 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000746 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000747 return true;
748}
749
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000750// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
751// set of known zero and one bits, compute the maximum and minimum values that
752// could have the specified known zero and known one bits, returning them in
753// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000754static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000755 const APInt& KnownOne,
756 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000757 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
758 KnownZero.getBitWidth() == Min.getBitWidth() &&
759 KnownZero.getBitWidth() == Max.getBitWidth() &&
760 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000761 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000762
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000763 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
764 // bit if it is unknown.
765 Min = KnownOne;
766 Max = KnownOne|UnknownBits;
767
Dan Gohman1c8491e2009-04-25 17:12:48 +0000768 if (UnknownBits.isNegative()) { // Sign bit is unknown
769 Min.set(Min.getBitWidth()-1);
770 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000771 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000772}
773
774// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
775// a set of known zero and one bits, compute the maximum and minimum values that
776// could have the specified known zero and known one bits, returning them in
777// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000778static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000779 const APInt &KnownOne,
780 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000781 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
782 KnownZero.getBitWidth() == Min.getBitWidth() &&
783 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000784 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000785 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000786
787 // The minimum value is when the unknown bits are all zeros.
788 Min = KnownOne;
789 // The maximum value is when the unknown bits are all ones.
790 Max = KnownOne|UnknownBits;
791}
Chris Lattner255d8912006-02-11 09:31:47 +0000792
Chris Lattner886ab6c2009-01-31 08:15:18 +0000793/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
794/// SimplifyDemandedBits knows about. See if the instruction has any
795/// properties that allow us to simplify its operands.
796bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000797 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000798 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
799 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
800
801 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
802 KnownZero, KnownOne, 0);
803 if (V == 0) return false;
804 if (V == &Inst) return true;
805 ReplaceInstUsesWith(Inst, V);
806 return true;
807}
808
809/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
810/// specified instruction operand if possible, updating it in place. It returns
811/// true if it made any change and false otherwise.
812bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
813 APInt &KnownZero, APInt &KnownOne,
814 unsigned Depth) {
815 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
816 KnownZero, KnownOne, Depth);
817 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000818 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000819 return true;
820}
821
822
823/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
824/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000825/// that only the bits set in DemandedMask of the result of V are ever used
826/// downstream. Consequently, depending on the mask and V, it may be possible
827/// to replace V with a constant or one of its operands. In such cases, this
828/// function does the replacement and returns true. In all other cases, it
829/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000830/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000831/// to be zero in the expression. These are provided to potentially allow the
832/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
833/// the expression. KnownOne and KnownZero always follow the invariant that
834/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
835/// the bits in KnownOne and KnownZero may only be accurate for those bits set
836/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
837/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000838///
839/// This returns null if it did not change anything and it permits no
840/// simplification. This returns V itself if it did some simplification of V's
841/// operands based on the information about what bits are demanded. This returns
842/// some other non-null value if it found out that V is equal to another value
843/// in the context where the specified bits are demanded, but not for all users.
844Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
845 APInt &KnownZero, APInt &KnownOne,
846 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000847 assert(V != 0 && "Null pointer of Value???");
848 assert(Depth <= 6 && "Limit Search Depth");
849 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000850 const Type *VTy = V->getType();
851 assert((TD || !isa<PointerType>(VTy)) &&
852 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000853 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
854 (!VTy->isIntOrIntVector() ||
855 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000856 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000857 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000858 "Value *V, DemandedMask, KnownZero and KnownOne "
859 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000860 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
861 // We know all of the bits for a constant!
862 KnownOne = CI->getValue() & DemandedMask;
863 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000864 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000865 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000866 if (isa<ConstantPointerNull>(V)) {
867 // We know all of the bits for a constant!
868 KnownOne.clear();
869 KnownZero = DemandedMask;
870 return 0;
871 }
872
Chris Lattner08d2cc72009-01-31 07:26:06 +0000873 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000874 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000875 if (DemandedMask == 0) { // Not demanding any bits from V.
876 if (isa<UndefValue>(V))
877 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000878 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000879 }
880
Chris Lattner4598c942009-01-31 08:24:16 +0000881 if (Depth == 6) // Limit search depth.
882 return 0;
883
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000884 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
885 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
886
Dan Gohman1c8491e2009-04-25 17:12:48 +0000887 Instruction *I = dyn_cast<Instruction>(V);
888 if (!I) {
889 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
890 return 0; // Only analyze instructions.
891 }
892
Chris Lattner4598c942009-01-31 08:24:16 +0000893 // If there are multiple uses of this value and we aren't at the root, then
894 // we can't do any simplifications of the operands, because DemandedMask
895 // only reflects the bits demanded by *one* of the users.
896 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000897 // Despite the fact that we can't simplify this instruction in all User's
898 // context, we can at least compute the knownzero/knownone bits, and we can
899 // do simplifications that apply to *just* the one user if we know that
900 // this instruction has a simpler value in that context.
901 if (I->getOpcode() == Instruction::And) {
902 // If either the LHS or the RHS are Zero, the result is zero.
903 ComputeMaskedBits(I->getOperand(1), DemandedMask,
904 RHSKnownZero, RHSKnownOne, Depth+1);
905 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
906 LHSKnownZero, LHSKnownOne, Depth+1);
907
908 // If all of the demanded bits are known 1 on one side, return the other.
909 // These bits cannot contribute to the result of the 'and' in this
910 // context.
911 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
912 (DemandedMask & ~LHSKnownZero))
913 return I->getOperand(0);
914 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
915 (DemandedMask & ~RHSKnownZero))
916 return I->getOperand(1);
917
918 // If all of the demanded bits in the inputs are known zeros, return zero.
919 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000920 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000921
922 } else if (I->getOpcode() == Instruction::Or) {
923 // We can simplify (X|Y) -> X or Y in the user's context if we know that
924 // only bits from X or Y are demanded.
925
926 // If either the LHS or the RHS are One, the result is One.
927 ComputeMaskedBits(I->getOperand(1), DemandedMask,
928 RHSKnownZero, RHSKnownOne, Depth+1);
929 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
930 LHSKnownZero, LHSKnownOne, Depth+1);
931
932 // If all of the demanded bits are known zero on one side, return the
933 // other. These bits cannot contribute to the result of the 'or' in this
934 // context.
935 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
936 (DemandedMask & ~LHSKnownOne))
937 return I->getOperand(0);
938 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
939 (DemandedMask & ~RHSKnownOne))
940 return I->getOperand(1);
941
942 // If all of the potentially set bits on one side are known to be set on
943 // the other side, just use the 'other' side.
944 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
945 (DemandedMask & (~RHSKnownZero)))
946 return I->getOperand(0);
947 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
948 (DemandedMask & (~LHSKnownZero)))
949 return I->getOperand(1);
950 }
951
Chris Lattner4598c942009-01-31 08:24:16 +0000952 // Compute the KnownZero/KnownOne bits to simplify things downstream.
953 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
954 return 0;
955 }
956
957 // If this is the root being simplified, allow it to have multiple uses,
958 // just set the DemandedMask to all bits so that we can try to simplify the
959 // operands. This allows visitTruncInst (for example) to simplify the
960 // operand of a trunc without duplicating all the logic below.
961 if (Depth == 0 && !V->hasOneUse())
962 DemandedMask = APInt::getAllOnesValue(BitWidth);
963
Reid Spencer8cb68342007-03-12 17:25:59 +0000964 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000965 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000966 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000967 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000968 case Instruction::And:
969 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000970 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
971 RHSKnownZero, RHSKnownOne, Depth+1) ||
972 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000973 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000974 return I;
975 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
976 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000977
978 // If all of the demanded bits are known 1 on one side, return the other.
979 // These bits cannot contribute to the result of the 'and'.
980 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
981 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000982 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000983 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
984 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000985 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000986
987 // If all of the demanded bits in the inputs are known zeros, return zero.
988 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000989 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000990
991 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000992 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000993 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000994
995 // Output known-1 bits are only known if set in both the LHS & RHS.
996 RHSKnownOne &= LHSKnownOne;
997 // Output known-0 are known to be clear if zero in either the LHS | RHS.
998 RHSKnownZero |= LHSKnownZero;
999 break;
1000 case Instruction::Or:
1001 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001002 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1003 RHSKnownZero, RHSKnownOne, Depth+1) ||
1004 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +00001005 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001006 return I;
1007 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1008 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001009
1010 // If all of the demanded bits are known zero on one side, return the other.
1011 // These bits cannot contribute to the result of the 'or'.
1012 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1013 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001014 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001015 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1016 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001017 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001018
1019 // If all of the potentially set bits on one side are known to be set on
1020 // the other side, just use the 'other' side.
1021 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1022 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001023 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001024 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1025 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001026 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001027
1028 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001029 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001030 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001031
1032 // Output known-0 bits are only known if clear in both the LHS & RHS.
1033 RHSKnownZero &= LHSKnownZero;
1034 // Output known-1 are known to be set if set in either the LHS | RHS.
1035 RHSKnownOne |= LHSKnownOne;
1036 break;
1037 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001038 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1039 RHSKnownZero, RHSKnownOne, Depth+1) ||
1040 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001041 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001042 return I;
1043 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1044 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001045
1046 // If all of the demanded bits are known zero on one side, return the other.
1047 // These bits cannot contribute to the result of the 'xor'.
1048 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001049 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001050 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001051 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001052
1053 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1054 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1055 (RHSKnownOne & LHSKnownOne);
1056 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1057 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1058 (RHSKnownOne & LHSKnownZero);
1059
1060 // If all of the demanded bits are known to be zero on one side or the
1061 // other, turn this into an *inclusive* or.
1062 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001063 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1064 Instruction *Or =
1065 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1066 I->getName());
1067 return InsertNewInstBefore(Or, *I);
1068 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001069
1070 // If all of the demanded bits on one side are known, and all of the set
1071 // bits on that side are also known to be set on the other side, turn this
1072 // into an AND, as we know the bits will be cleared.
1073 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1074 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1075 // all known
1076 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001077 Constant *AndC = Constant::getIntegerValue(VTy,
1078 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001079 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001080 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001081 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001082 }
1083 }
1084
1085 // If the RHS is a constant, see if we can simplify it.
1086 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001087 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001088 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001089
Chris Lattnerd0883142009-10-11 22:22:13 +00001090 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1091 // are flipping are known to be set, then the xor is just resetting those
1092 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1093 // simplifying both of them.
1094 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1095 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1096 isa<ConstantInt>(I->getOperand(1)) &&
1097 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1098 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1099 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1100 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1101 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1102
1103 Constant *AndC =
1104 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1105 Instruction *NewAnd =
1106 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1107 InsertNewInstBefore(NewAnd, *I);
1108
1109 Constant *XorC =
1110 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1111 Instruction *NewXor =
1112 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1113 return InsertNewInstBefore(NewXor, *I);
1114 }
1115
1116
Reid Spencer8cb68342007-03-12 17:25:59 +00001117 RHSKnownZero = KnownZeroOut;
1118 RHSKnownOne = KnownOneOut;
1119 break;
1120 }
1121 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001122 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1123 RHSKnownZero, RHSKnownOne, Depth+1) ||
1124 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001125 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001126 return I;
1127 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1128 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001129
1130 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001131 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1132 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001133 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001134
1135 // Only known if known in both the LHS and RHS.
1136 RHSKnownOne &= LHSKnownOne;
1137 RHSKnownZero &= LHSKnownZero;
1138 break;
1139 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001140 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001141 DemandedMask.zext(truncBf);
1142 RHSKnownZero.zext(truncBf);
1143 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001144 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001145 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001146 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001147 DemandedMask.trunc(BitWidth);
1148 RHSKnownZero.trunc(BitWidth);
1149 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001150 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001151 break;
1152 }
1153 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001154 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001155 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001156
1157 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1158 if (const VectorType *SrcVTy =
1159 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1160 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1161 // Don't touch a bitcast between vectors of different element counts.
1162 return false;
1163 } else
1164 // Don't touch a scalar-to-vector bitcast.
1165 return false;
1166 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1167 // Don't touch a vector-to-scalar bitcast.
1168 return false;
1169
Chris Lattner886ab6c2009-01-31 08:15:18 +00001170 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001171 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001172 return I;
1173 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001174 break;
1175 case Instruction::ZExt: {
1176 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001177 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001178
Zhou Shengd48653a2007-03-29 04:45:55 +00001179 DemandedMask.trunc(SrcBitWidth);
1180 RHSKnownZero.trunc(SrcBitWidth);
1181 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001182 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001183 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001184 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001185 DemandedMask.zext(BitWidth);
1186 RHSKnownZero.zext(BitWidth);
1187 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001188 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001189 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001190 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001191 break;
1192 }
1193 case Instruction::SExt: {
1194 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001195 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001196
Reid Spencer8cb68342007-03-12 17:25:59 +00001197 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001198 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001199
Zhou Sheng01542f32007-03-29 02:26:30 +00001200 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001201 // If any of the sign extended bits are demanded, we know that the sign
1202 // bit is demanded.
1203 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001204 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001205
Zhou Shengd48653a2007-03-29 04:45:55 +00001206 InputDemandedBits.trunc(SrcBitWidth);
1207 RHSKnownZero.trunc(SrcBitWidth);
1208 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001209 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001210 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001211 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001212 InputDemandedBits.zext(BitWidth);
1213 RHSKnownZero.zext(BitWidth);
1214 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001215 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001216
1217 // If the sign bit of the input is known set or clear, then we know the
1218 // top bits of the result.
1219
1220 // If the input sign bit is known zero, or if the NewBits are not demanded
1221 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001222 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001223 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001224 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1225 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001226 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001227 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001228 }
1229 break;
1230 }
1231 case Instruction::Add: {
1232 // Figure out what the input bits are. If the top bits of the and result
1233 // are not demanded, then the add doesn't demand them from its input
1234 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001235 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001236
1237 // If there is a constant on the RHS, there are a variety of xformations
1238 // we can do.
1239 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1240 // If null, this should be simplified elsewhere. Some of the xforms here
1241 // won't work if the RHS is zero.
1242 if (RHS->isZero())
1243 break;
1244
1245 // If the top bit of the output is demanded, demand everything from the
1246 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001247 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001248
1249 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001250 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001251 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001252 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001253
1254 // If the RHS of the add has bits set that can't affect the input, reduce
1255 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001256 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001257 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001258
1259 // Avoid excess work.
1260 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1261 break;
1262
1263 // Turn it into OR if input bits are zero.
1264 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1265 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001266 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001267 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001268 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001269 }
1270
1271 // We can say something about the output known-zero and known-one bits,
1272 // depending on potential carries from the input constant and the
1273 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1274 // bits set and the RHS constant is 0x01001, then we know we have a known
1275 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1276
1277 // To compute this, we first compute the potential carry bits. These are
1278 // the bits which may be modified. I'm not aware of a better way to do
1279 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001280 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001281 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001282
1283 // Now that we know which bits have carries, compute the known-1/0 sets.
1284
1285 // Bits are known one if they are known zero in one operand and one in the
1286 // other, and there is no input carry.
1287 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1288 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1289
1290 // Bits are known zero if they are known zero in both operands and there
1291 // is no input carry.
1292 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1293 } else {
1294 // If the high-bits of this ADD are not demanded, then it does not demand
1295 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001296 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001297 // Right fill the mask of bits for this ADD to demand the most
1298 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001299 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001300 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1301 LHSKnownZero, LHSKnownOne, Depth+1) ||
1302 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001303 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001304 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001305 }
1306 }
1307 break;
1308 }
1309 case Instruction::Sub:
1310 // If the high-bits of this SUB are not demanded, then it does not demand
1311 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001312 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001313 // Right fill the mask of bits for this SUB to demand the most
1314 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001315 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001316 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001317 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1318 LHSKnownZero, LHSKnownOne, Depth+1) ||
1319 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001320 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001321 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001322 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001323 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1324 // the known zeros and ones.
1325 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001326 break;
1327 case Instruction::Shl:
1328 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001329 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001330 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001331 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001332 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001333 return I;
1334 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001335 RHSKnownZero <<= ShiftAmt;
1336 RHSKnownOne <<= ShiftAmt;
1337 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001338 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001339 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001340 }
1341 break;
1342 case Instruction::LShr:
1343 // For a logical shift right
1344 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001345 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001346
Reid Spencer8cb68342007-03-12 17:25:59 +00001347 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001348 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001349 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001350 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001351 return I;
1352 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001353 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1354 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001355 if (ShiftAmt) {
1356 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001357 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001358 RHSKnownZero |= HighBits; // high bits known zero.
1359 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001360 }
1361 break;
1362 case Instruction::AShr:
1363 // If this is an arithmetic shift right and only the low-bit is set, we can
1364 // always convert this into a logical shr, even if the shift amount is
1365 // variable. The low bit of the shift cannot be an input sign bit unless
1366 // the shift amount is >= the size of the datatype, which is undefined.
1367 if (DemandedMask == 1) {
1368 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001369 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001370 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001371 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001372 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001373
1374 // If the sign bit is the only bit demanded by this ashr, then there is no
1375 // need to do it, the shift doesn't change the high bit.
1376 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001377 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001378
1379 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001380 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001381
Reid Spencer8cb68342007-03-12 17:25:59 +00001382 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001383 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001384 // If any of the "high bits" are demanded, we should set the sign bit as
1385 // demanded.
1386 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1387 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001388 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001389 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001390 return I;
1391 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001392 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001393 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001394 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1395 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1396
1397 // Handle the sign bits.
1398 APInt SignBit(APInt::getSignBit(BitWidth));
1399 // Adjust to where it is now in the mask.
1400 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1401
1402 // If the input sign bit is known to be zero, or if none of the top bits
1403 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001404 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001405 (HighBits & ~DemandedMask) == HighBits) {
1406 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001407 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001408 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001409 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001410 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1411 RHSKnownOne |= HighBits;
1412 }
1413 }
1414 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001415 case Instruction::SRem:
1416 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001417 APInt RA = Rem->getValue().abs();
1418 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001419 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001420 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001421
Nick Lewycky8e394322008-11-02 02:41:50 +00001422 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001423 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001424 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001425 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001426 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001427
1428 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1429 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001430
1431 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001432
Chris Lattner886ab6c2009-01-31 08:15:18 +00001433 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001434 }
1435 }
1436 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001437 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001438 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1439 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001440 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1441 KnownZero2, KnownOne2, Depth+1) ||
1442 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001443 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001444 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001445
Chris Lattner455e9ab2009-01-21 18:09:24 +00001446 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001447 Leaders = std::max(Leaders,
1448 KnownZero2.countLeadingOnes());
1449 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001450 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001451 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001452 case Instruction::Call:
1453 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1454 switch (II->getIntrinsicID()) {
1455 default: break;
1456 case Intrinsic::bswap: {
1457 // If the only bits demanded come from one byte of the bswap result,
1458 // just shift the input byte into position to eliminate the bswap.
1459 unsigned NLZ = DemandedMask.countLeadingZeros();
1460 unsigned NTZ = DemandedMask.countTrailingZeros();
1461
1462 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1463 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1464 // have 14 leading zeros, round to 8.
1465 NLZ &= ~7;
1466 NTZ &= ~7;
1467 // If we need exactly one byte, we can do this transformation.
1468 if (BitWidth-NLZ-NTZ == 8) {
1469 unsigned ResultBit = NTZ;
1470 unsigned InputBit = BitWidth-NTZ-8;
1471
1472 // Replace this with either a left or right shift to get the byte into
1473 // the right place.
1474 Instruction *NewVal;
1475 if (InputBit > ResultBit)
1476 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001477 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001478 else
1479 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001480 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001481 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001482 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001483 }
1484
1485 // TODO: Could compute known zero/one bits based on the input.
1486 break;
1487 }
1488 }
1489 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001490 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001491 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001492 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001493
1494 // If the client is only demanding bits that we know, return the known
1495 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001496 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1497 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001498 return false;
1499}
1500
Chris Lattner867b99f2006-10-05 06:55:50 +00001501
Mon P Wangaeb06d22008-11-10 04:46:22 +00001502/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001503/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001504/// actually used by the caller. This method analyzes which elements of the
1505/// operand are undef and returns that information in UndefElts.
1506///
1507/// If the information about demanded elements can be used to simplify the
1508/// operation, the operation is simplified, then the resultant value is
1509/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001510Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1511 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001512 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001513 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001514 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001515 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001516
1517 if (isa<UndefValue>(V)) {
1518 // If the entire vector is undefined, just return this info.
1519 UndefElts = EltMask;
1520 return 0;
1521 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1522 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001523 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001524 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001525
Chris Lattner867b99f2006-10-05 06:55:50 +00001526 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001527 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1528 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001529 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001530
1531 std::vector<Constant*> Elts;
1532 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001533 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001534 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001535 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001536 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1537 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001538 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001539 } else { // Otherwise, defined.
1540 Elts.push_back(CP->getOperand(i));
1541 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001542
Chris Lattner867b99f2006-10-05 06:55:50 +00001543 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001544 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001545 return NewCP != CP ? NewCP : 0;
1546 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001547 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001548 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001549
1550 // Check if this is identity. If so, return 0 since we are not simplifying
1551 // anything.
1552 if (DemandedElts == ((1ULL << VWidth) -1))
1553 return 0;
1554
Reid Spencer9d6565a2007-02-15 02:26:10 +00001555 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001556 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001557 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001558 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001559 for (unsigned i = 0; i != VWidth; ++i) {
1560 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1561 Elts.push_back(Elt);
1562 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001563 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001564 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001565 }
1566
Dan Gohman488fbfc2008-09-09 18:11:14 +00001567 // Limit search depth.
1568 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001569 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001570
1571 // If multiple users are using the root value, procede with
1572 // simplification conservatively assuming that all elements
1573 // are needed.
1574 if (!V->hasOneUse()) {
1575 // Quit if we find multiple users of a non-root value though.
1576 // They'll be handled when it's their turn to be visited by
1577 // the main instcombine process.
1578 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001579 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001580 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001581
1582 // Conservatively assume that all elements are needed.
1583 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001584 }
1585
1586 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001587 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001588
1589 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001590 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001591 Value *TmpV;
1592 switch (I->getOpcode()) {
1593 default: break;
1594
1595 case Instruction::InsertElement: {
1596 // If this is a variable index, we don't know which element it overwrites.
1597 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001598 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001599 if (Idx == 0) {
1600 // Note that we can't propagate undef elt info, because we don't know
1601 // which elt is getting updated.
1602 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1603 UndefElts2, Depth+1);
1604 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1605 break;
1606 }
1607
1608 // If this is inserting an element that isn't demanded, remove this
1609 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001610 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001611 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1612 Worklist.Add(I);
1613 return I->getOperand(0);
1614 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001615
1616 // Otherwise, the element inserted overwrites whatever was there, so the
1617 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001618 APInt DemandedElts2 = DemandedElts;
1619 DemandedElts2.clear(IdxNo);
1620 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001621 UndefElts, Depth+1);
1622 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1623
1624 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001625 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001626 break;
1627 }
1628 case Instruction::ShuffleVector: {
1629 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001630 uint64_t LHSVWidth =
1631 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001632 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001633 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001634 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001635 unsigned MaskVal = Shuffle->getMaskValue(i);
1636 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001637 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001638 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001639 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001640 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001641 else
Evan Cheng388df622009-02-03 10:05:09 +00001642 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001643 }
1644 }
1645 }
1646
Nate Begeman7b254672009-02-11 22:36:25 +00001647 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001648 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001649 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001650 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1651
Nate Begeman7b254672009-02-11 22:36:25 +00001652 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001653 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1654 UndefElts3, Depth+1);
1655 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1656
1657 bool NewUndefElts = false;
1658 for (unsigned i = 0; i < VWidth; i++) {
1659 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001660 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001661 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001662 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001663 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001664 NewUndefElts = true;
1665 UndefElts.set(i);
1666 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001667 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001668 if (UndefElts3[MaskVal - LHSVWidth]) {
1669 NewUndefElts = true;
1670 UndefElts.set(i);
1671 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001672 }
1673 }
1674
1675 if (NewUndefElts) {
1676 // Add additional discovered undefs.
1677 std::vector<Constant*> Elts;
1678 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001679 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001680 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001681 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001682 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001683 Shuffle->getMaskValue(i)));
1684 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001685 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001686 MadeChange = true;
1687 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001688 break;
1689 }
Chris Lattner69878332007-04-14 22:29:23 +00001690 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001691 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001692 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1693 if (!VTy) break;
1694 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001695 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001696 unsigned Ratio;
1697
1698 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001699 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001700 // elements as are demanded of us.
1701 Ratio = 1;
1702 InputDemandedElts = DemandedElts;
1703 } else if (VWidth > InVWidth) {
1704 // Untested so far.
1705 break;
1706
1707 // If there are more elements in the result than there are in the source,
1708 // then an input element is live if any of the corresponding output
1709 // elements are live.
1710 Ratio = VWidth/InVWidth;
1711 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001712 if (DemandedElts[OutIdx])
1713 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001714 }
1715 } else {
1716 // Untested so far.
1717 break;
1718
1719 // If there are more elements in the source than there are in the result,
1720 // then an input element is live if the corresponding output element is
1721 // live.
1722 Ratio = InVWidth/VWidth;
1723 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001724 if (DemandedElts[InIdx/Ratio])
1725 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001726 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001727
Chris Lattner69878332007-04-14 22:29:23 +00001728 // div/rem demand all inputs, because they don't want divide by zero.
1729 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1730 UndefElts2, Depth+1);
1731 if (TmpV) {
1732 I->setOperand(0, TmpV);
1733 MadeChange = true;
1734 }
1735
1736 UndefElts = UndefElts2;
1737 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001738 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001739 // If there are more elements in the result than there are in the source,
1740 // then an output element is undef if the corresponding input element is
1741 // undef.
1742 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001743 if (UndefElts2[OutIdx/Ratio])
1744 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001745 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001746 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001747 // If there are more elements in the source than there are in the result,
1748 // then a result element is undef if all of the corresponding input
1749 // elements are undef.
1750 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1751 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001752 if (!UndefElts2[InIdx]) // Not undef?
1753 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001754 }
1755 break;
1756 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001757 case Instruction::And:
1758 case Instruction::Or:
1759 case Instruction::Xor:
1760 case Instruction::Add:
1761 case Instruction::Sub:
1762 case Instruction::Mul:
1763 // div/rem demand all inputs, because they don't want divide by zero.
1764 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1765 UndefElts, Depth+1);
1766 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1767 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1768 UndefElts2, Depth+1);
1769 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1770
1771 // Output elements are undefined if both are undefined. Consider things
1772 // like undef&0. The result is known zero, not undef.
1773 UndefElts &= UndefElts2;
1774 break;
1775
1776 case Instruction::Call: {
1777 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1778 if (!II) break;
1779 switch (II->getIntrinsicID()) {
1780 default: break;
1781
1782 // Binary vector operations that work column-wise. A dest element is a
1783 // function of the corresponding input elements from the two inputs.
1784 case Intrinsic::x86_sse_sub_ss:
1785 case Intrinsic::x86_sse_mul_ss:
1786 case Intrinsic::x86_sse_min_ss:
1787 case Intrinsic::x86_sse_max_ss:
1788 case Intrinsic::x86_sse2_sub_sd:
1789 case Intrinsic::x86_sse2_mul_sd:
1790 case Intrinsic::x86_sse2_min_sd:
1791 case Intrinsic::x86_sse2_max_sd:
1792 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1793 UndefElts, Depth+1);
1794 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1795 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1796 UndefElts2, Depth+1);
1797 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1798
1799 // If only the low elt is demanded and this is a scalarizable intrinsic,
1800 // scalarize it now.
1801 if (DemandedElts == 1) {
1802 switch (II->getIntrinsicID()) {
1803 default: break;
1804 case Intrinsic::x86_sse_sub_ss:
1805 case Intrinsic::x86_sse_mul_ss:
1806 case Intrinsic::x86_sse2_sub_sd:
1807 case Intrinsic::x86_sse2_mul_sd:
1808 // TODO: Lower MIN/MAX/ABS/etc
1809 Value *LHS = II->getOperand(1);
1810 Value *RHS = II->getOperand(2);
1811 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001812 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001813 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001814 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001815 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001816
1817 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001818 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001819 case Intrinsic::x86_sse_sub_ss:
1820 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001821 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001822 II->getName()), *II);
1823 break;
1824 case Intrinsic::x86_sse_mul_ss:
1825 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001826 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001827 II->getName()), *II);
1828 break;
1829 }
1830
1831 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001832 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001833 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001834 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001835 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001836 return New;
1837 }
1838 }
1839
1840 // Output elements are undefined if both are undefined. Consider things
1841 // like undef&0. The result is known zero, not undef.
1842 UndefElts &= UndefElts2;
1843 break;
1844 }
1845 break;
1846 }
1847 }
1848 return MadeChange ? I : 0;
1849}
1850
Dan Gohman45b4e482008-05-19 22:14:15 +00001851
Chris Lattner564a7272003-08-13 19:01:45 +00001852/// AssociativeOpt - Perform an optimization on an associative operator. This
1853/// function is designed to check a chain of associative operators for a
1854/// potential to apply a certain optimization. Since the optimization may be
1855/// applicable if the expression was reassociated, this checks the chain, then
1856/// reassociates the expression as necessary to expose the optimization
1857/// opportunity. This makes use of a special Functor, which must define
1858/// 'shouldApply' and 'apply' methods.
1859///
1860template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001861static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001862 unsigned Opcode = Root.getOpcode();
1863 Value *LHS = Root.getOperand(0);
1864
1865 // Quick check, see if the immediate LHS matches...
1866 if (F.shouldApply(LHS))
1867 return F.apply(Root);
1868
1869 // Otherwise, if the LHS is not of the same opcode as the root, return.
1870 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001871 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001872 // Should we apply this transform to the RHS?
1873 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1874
1875 // If not to the RHS, check to see if we should apply to the LHS...
1876 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1877 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1878 ShouldApply = true;
1879 }
1880
1881 // If the functor wants to apply the optimization to the RHS of LHSI,
1882 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1883 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001884 // Now all of the instructions are in the current basic block, go ahead
1885 // and perform the reassociation.
1886 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1887
1888 // First move the selected RHS to the LHS of the root...
1889 Root.setOperand(0, LHSI->getOperand(1));
1890
1891 // Make what used to be the LHS of the root be the user of the root...
1892 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001893 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001894 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001895 return 0;
1896 }
Chris Lattner65725312004-04-16 18:08:07 +00001897 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001898 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001899 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001900 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001901 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001902
1903 // Now propagate the ExtraOperand down the chain of instructions until we
1904 // get to LHSI.
1905 while (TmpLHSI != LHSI) {
1906 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001907 // Move the instruction to immediately before the chain we are
1908 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001909 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001910 ARI = NextLHSI;
1911
Chris Lattner564a7272003-08-13 19:01:45 +00001912 Value *NextOp = NextLHSI->getOperand(1);
1913 NextLHSI->setOperand(1, ExtraOperand);
1914 TmpLHSI = NextLHSI;
1915 ExtraOperand = NextOp;
1916 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001917
Chris Lattner564a7272003-08-13 19:01:45 +00001918 // Now that the instructions are reassociated, have the functor perform
1919 // the transformation...
1920 return F.apply(Root);
1921 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001922
Chris Lattner564a7272003-08-13 19:01:45 +00001923 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1924 }
1925 return 0;
1926}
1927
Dan Gohman844731a2008-05-13 00:00:25 +00001928namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001929
Nick Lewycky02d639f2008-05-23 04:34:58 +00001930// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001931struct AddRHS {
1932 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001933 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001934 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1935 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001936 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001937 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001938 }
1939};
1940
1941// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1942// iff C1&C2 == 0
1943struct AddMaskingAnd {
1944 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001945 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001946 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001947 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001948 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001949 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001950 }
1951 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001952 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001953 }
1954};
1955
Dan Gohman844731a2008-05-13 00:00:25 +00001956}
1957
Chris Lattner6e7ba452005-01-01 16:22:27 +00001958static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001959 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001960 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001961 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001962
Chris Lattner2eefe512004-04-09 19:05:30 +00001963 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001964 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1965 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001966
Chris Lattner2eefe512004-04-09 19:05:30 +00001967 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1968 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001969 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1970 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001971 }
1972
1973 Value *Op0 = SO, *Op1 = ConstOperand;
1974 if (!ConstIsRHS)
1975 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001976
Chris Lattner6e7ba452005-01-01 16:22:27 +00001977 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001978 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1979 SO->getName()+".op");
1980 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1981 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1982 SO->getName()+".cmp");
1983 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1984 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1985 SO->getName()+".cmp");
1986 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001987}
1988
1989// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1990// constant as the other operand, try to fold the binary operator into the
1991// select arguments. This also works for Cast instructions, which obviously do
1992// not have a second operand.
1993static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1994 InstCombiner *IC) {
1995 // Don't modify shared select instructions
1996 if (!SI->hasOneUse()) return 0;
1997 Value *TV = SI->getOperand(1);
1998 Value *FV = SI->getOperand(2);
1999
2000 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002001 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00002002 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002003
Chris Lattner6e7ba452005-01-01 16:22:27 +00002004 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2005 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2006
Gabor Greif051a9502008-04-06 20:25:17 +00002007 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2008 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002009 }
2010 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002011}
2012
Chris Lattner4e998b22004-09-29 05:07:12 +00002013
Chris Lattner5d1704d2009-09-27 19:57:57 +00002014/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2015/// has a PHI node as operand #0, see if we can fold the instruction into the
2016/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002017///
2018/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2019/// that would normally be unprofitable because they strongly encourage jump
2020/// threading.
2021Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2022 bool AllowAggressive) {
2023 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002024 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002025 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002026 if (NumPHIValues == 0 ||
2027 // We normally only transform phis with a single use, unless we're trying
2028 // hard to make jump threading happen.
2029 (!PN->hasOneUse() && !AllowAggressive))
2030 return 0;
2031
2032
Chris Lattner5d1704d2009-09-27 19:57:57 +00002033 // Check to see if all of the operands of the PHI are simple constants
2034 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002035 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2036 // bail out. We don't do arbitrary constant expressions here because moving
2037 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002038 BasicBlock *NonConstBB = 0;
2039 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002040 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2041 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002042 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002043 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002044 NonConstBB = PN->getIncomingBlock(i);
2045
2046 // If the incoming non-constant value is in I's block, we have an infinite
2047 // loop.
2048 if (NonConstBB == I.getParent())
2049 return 0;
2050 }
2051
2052 // If there is exactly one non-constant value, we can insert a copy of the
2053 // operation in that block. However, if this is a critical edge, we would be
2054 // inserting the computation one some other paths (e.g. inside a loop). Only
2055 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002056 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002057 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2058 if (!BI || !BI->isUnconditional()) return 0;
2059 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002060
2061 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002062 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002063 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002064 InsertNewInstBefore(NewPN, *PN);
2065 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002066
2067 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002068 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2069 // We only currently try to fold the condition of a select when it is a phi,
2070 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002071 Value *TrueV = SI->getTrueValue();
2072 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002073 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002074 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002075 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002076 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2077 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002078 Value *InV = 0;
2079 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002080 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002081 } else {
2082 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002083 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2084 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002085 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002086 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002087 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002088 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002089 }
2090 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002091 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002092 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002093 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002094 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002095 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002096 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002097 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002098 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002099 } else {
2100 assert(PN->getIncomingBlock(i) == NonConstBB);
2101 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002102 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002103 PN->getIncomingValue(i), C, "phitmp",
2104 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002105 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002106 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002107 CI->getPredicate(),
2108 PN->getIncomingValue(i), C, "phitmp",
2109 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002110 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002111 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002112
2113 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002114 }
2115 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002116 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002117 } else {
2118 CastInst *CI = cast<CastInst>(&I);
2119 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002120 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002121 Value *InV;
2122 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002123 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002124 } else {
2125 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002126 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002127 I.getType(), "phitmp",
2128 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002129 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002130 }
2131 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002132 }
2133 }
2134 return ReplaceInstUsesWith(I, NewPN);
2135}
2136
Chris Lattner2454a2e2008-01-29 06:52:45 +00002137
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002138/// WillNotOverflowSignedAdd - Return true if we can prove that:
2139/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2140/// This basically requires proving that the add in the original type would not
2141/// overflow to change the sign bit or have a carry out.
2142bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2143 // There are different heuristics we can use for this. Here are some simple
2144 // ones.
2145
2146 // Add has the property that adding any two 2's complement numbers can only
2147 // have one carry bit which can change a sign. As such, if LHS and RHS each
2148 // have at least two sign bits, we know that the addition of the two values will
2149 // sign extend fine.
2150 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2151 return true;
2152
2153
2154 // If one of the operands only has one non-zero bit, and if the other operand
2155 // has a known-zero bit in a more significant place than it (not including the
2156 // sign bit) the ripple may go up to and fill the zero, but won't change the
2157 // sign. For example, (X & ~4) + 1.
2158
2159 // TODO: Implement.
2160
2161 return false;
2162}
2163
Chris Lattner2454a2e2008-01-29 06:52:45 +00002164
Chris Lattner7e708292002-06-25 16:13:24 +00002165Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002166 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002167 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002168
Chris Lattner66331a42004-04-10 22:01:55 +00002169 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002170 // X + undef -> undef
2171 if (isa<UndefValue>(RHS))
2172 return ReplaceInstUsesWith(I, RHS);
2173
Chris Lattner66331a42004-04-10 22:01:55 +00002174 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002175 if (RHSC->isNullValue())
2176 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002177
Chris Lattner66331a42004-04-10 22:01:55 +00002178 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002179 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002180 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002181 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002182 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002183 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002184
2185 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2186 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002187 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002188 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002189
Eli Friedman709b33d2009-07-13 22:27:52 +00002190 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002191 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002192 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002193 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002194 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002195
2196 if (isa<PHINode>(LHS))
2197 if (Instruction *NV = FoldOpIntoPhi(I))
2198 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002199
Chris Lattner4f637d42006-01-06 17:59:59 +00002200 ConstantInt *XorRHS = 0;
2201 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002202 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002203 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002204 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002205 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002206
Zhou Sheng4351c642007-04-02 08:20:41 +00002207 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002208 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2209 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002210 do {
2211 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002212 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2213 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002214 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2215 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002216 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002217 if (!MaskedValueIsZero(XorLHS,
2218 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002219 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002220 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002221 }
2222 }
2223 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002224 C0080Val = APIntOps::lshr(C0080Val, Size);
2225 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2226 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002227
Reid Spencer35c38852007-03-28 01:36:16 +00002228 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002229 // with funny bit widths then this switch statement should be removed. It
2230 // is just here to get the size of the "middle" type back up to something
2231 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002232 const Type *MiddleType = 0;
2233 switch (Size) {
2234 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002235 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2236 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2237 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002238 }
2239 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002240 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002241 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002242 }
2243 }
Chris Lattner66331a42004-04-10 22:01:55 +00002244 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002245
Owen Anderson1d0be152009-08-13 21:58:54 +00002246 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002247 return BinaryOperator::CreateXor(LHS, RHS);
2248
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002249 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002250 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002251 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002252 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002253
2254 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2255 if (RHSI->getOpcode() == Instruction::Sub)
2256 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2257 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2258 }
2259 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2260 if (LHSI->getOpcode() == Instruction::Sub)
2261 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2262 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2263 }
Robert Bocchino71698282004-07-27 21:02:21 +00002264 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002265
Chris Lattner5c4afb92002-05-08 22:46:53 +00002266 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002267 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002268 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002269 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002270 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002271 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002272 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002273 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002274 }
2275
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002276 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002277 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002278
2279 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002280 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002281 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002282 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002283
Misha Brukmanfd939082005-04-21 23:48:37 +00002284
Chris Lattner50af16a2004-11-13 19:50:12 +00002285 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002286 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002287 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002288 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002289
2290 // X*C1 + X*C2 --> X * (C1+C2)
2291 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002292 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002293 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002294 }
2295
2296 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002297 if (dyn_castFoldableMul(RHS, C2) == LHS)
2298 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002299
Chris Lattnere617c9e2007-01-05 02:17:46 +00002300 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002301 if (dyn_castNotVal(LHS) == RHS ||
2302 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002303 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002304
Chris Lattnerad3448c2003-02-18 19:57:07 +00002305
Chris Lattner564a7272003-08-13 19:01:45 +00002306 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002307 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2308 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002309 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002310
2311 // A+B --> A|B iff A and B have no bits set in common.
2312 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2313 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2314 APInt LHSKnownOne(IT->getBitWidth(), 0);
2315 APInt LHSKnownZero(IT->getBitWidth(), 0);
2316 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2317 if (LHSKnownZero != 0) {
2318 APInt RHSKnownOne(IT->getBitWidth(), 0);
2319 APInt RHSKnownZero(IT->getBitWidth(), 0);
2320 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2321
2322 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002323 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002324 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002325 }
2326 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002327
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002328 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002329 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002330 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002331 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2332 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002333 if (W != Y) {
2334 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002335 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002336 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002337 std::swap(W, X);
2338 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002339 std::swap(Y, Z);
2340 std::swap(W, X);
2341 }
2342 }
2343
2344 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002345 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002346 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002347 }
2348 }
2349 }
2350
Chris Lattner6b032052003-10-02 15:11:26 +00002351 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002352 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002353 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002354 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002355
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002356 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002357 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002358 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002359 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002360 if (Anded == CRHS) {
2361 // See if all bits from the first bit set in the Add RHS up are included
2362 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002363 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002364
2365 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002366 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002367
2368 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002369 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002370
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002371 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2372 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002373 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002374 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002375 }
2376 }
2377 }
2378
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002379 // Try to fold constant add into select arguments.
2380 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002381 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002382 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002383 }
2384
Chris Lattner42790482007-12-20 01:56:58 +00002385 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002386 {
2387 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002388 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002389 if (!SI) {
2390 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002391 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002392 }
Chris Lattner42790482007-12-20 01:56:58 +00002393 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002394 Value *TV = SI->getTrueValue();
2395 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002396 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002397
2398 // Can we fold the add into the argument of the select?
2399 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002400 if (match(FV, m_Zero()) &&
2401 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002402 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002403 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002404 if (match(TV, m_Zero()) &&
2405 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002406 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002407 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002408 }
2409 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002410
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002411 // Check for (add (sext x), y), see if we can merge this into an
2412 // integer add followed by a sext.
2413 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2414 // (add (sext x), cst) --> (sext (add x, cst'))
2415 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2416 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002417 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002418 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002419 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002420 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2421 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002422 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2423 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002424 return new SExtInst(NewAdd, I.getType());
2425 }
2426 }
2427
2428 // (add (sext x), (sext y)) --> (sext (add int x, y))
2429 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2430 // Only do this if x/y have the same type, if at last one of them has a
2431 // single use (so we don't increase the number of sexts), and if the
2432 // integer add will not overflow.
2433 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2434 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2435 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2436 RHSConv->getOperand(0))) {
2437 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002438 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2439 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002440 return new SExtInst(NewAdd, I.getType());
2441 }
2442 }
2443 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002444
2445 return Changed ? &I : 0;
2446}
2447
2448Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2449 bool Changed = SimplifyCommutative(I);
2450 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2451
2452 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2453 // X + 0 --> X
2454 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002455 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002456 (I.getType())->getValueAPF()))
2457 return ReplaceInstUsesWith(I, LHS);
2458 }
2459
2460 if (isa<PHINode>(LHS))
2461 if (Instruction *NV = FoldOpIntoPhi(I))
2462 return NV;
2463 }
2464
2465 // -A + B --> B - A
2466 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002467 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002468 return BinaryOperator::CreateFSub(RHS, LHSV);
2469
2470 // A + -B --> A - B
2471 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002472 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002473 return BinaryOperator::CreateFSub(LHS, V);
2474
2475 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2476 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2477 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2478 return ReplaceInstUsesWith(I, LHS);
2479
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002480 // Check for (add double (sitofp x), y), see if we can merge this into an
2481 // integer add followed by a promotion.
2482 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2483 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2484 // ... if the constant fits in the integer value. This is useful for things
2485 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2486 // requires a constant pool load, and generally allows the add to be better
2487 // instcombined.
2488 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2489 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002490 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002491 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002492 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002493 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2494 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002495 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2496 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002497 return new SIToFPInst(NewAdd, I.getType());
2498 }
2499 }
2500
2501 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2502 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2503 // Only do this if x/y have the same type, if at last one of them has a
2504 // single use (so we don't increase the number of int->fp conversions),
2505 // and if the integer add will not overflow.
2506 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2507 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2508 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2509 RHSConv->getOperand(0))) {
2510 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002511 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2512 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002513 return new SIToFPInst(NewAdd, I.getType());
2514 }
2515 }
2516 }
2517
Chris Lattner7e708292002-06-25 16:13:24 +00002518 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002519}
2520
Chris Lattner7e708292002-06-25 16:13:24 +00002521Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002522 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002523
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002524 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002525 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002526
Chris Lattner233f7dc2002-08-12 21:17:25 +00002527 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002528 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002529 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002530
Chris Lattnere87597f2004-10-16 18:11:37 +00002531 if (isa<UndefValue>(Op0))
2532 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2533 if (isa<UndefValue>(Op1))
2534 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2535
Chris Lattnerd65460f2003-11-05 01:06:05 +00002536 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2537 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002538 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002539 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002540
Chris Lattnerd65460f2003-11-05 01:06:05 +00002541 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002542 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002543 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002544 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002545
Chris Lattner76b7a062007-01-15 07:02:54 +00002546 // -(X >>u 31) -> (X >>s 31)
2547 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002548 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002549 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002550 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002551 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002552 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002553 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002554 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002555 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002556 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002557 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002558 }
2559 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002560 }
2561 else if (SI->getOpcode() == Instruction::AShr) {
2562 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2563 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002564 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002565 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002566 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002567 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002568 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002569 }
2570 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002571 }
2572 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002573 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002574
2575 // Try to fold constant sub into select arguments.
2576 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002577 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002578 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002579
2580 // C - zext(bool) -> bool ? C - 1 : C
2581 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002582 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002583 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002584 }
2585
Owen Anderson1d0be152009-08-13 21:58:54 +00002586 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002587 return BinaryOperator::CreateXor(Op0, Op1);
2588
Chris Lattner43d84d62005-04-07 16:15:25 +00002589 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002590 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002591 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002592 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002593 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002594 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002595 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002596 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002597 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2598 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2599 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002600 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002601 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002602 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002603 }
2604
Chris Lattnerfd059242003-10-15 16:48:29 +00002605 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002606 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2607 // is not used by anyone else...
2608 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002609 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002610 // Swap the two operands of the subexpr...
2611 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2612 Op1I->setOperand(0, IIOp1);
2613 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002614
Chris Lattnera2881962003-02-18 19:28:33 +00002615 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002616 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002617 }
2618
2619 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2620 //
2621 if (Op1I->getOpcode() == Instruction::And &&
2622 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2623 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2624
Chris Lattner74381062009-08-30 07:44:24 +00002625 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002626 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002627 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002628
Reid Spencerac5209e2006-10-16 23:08:08 +00002629 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002630 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002631 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002632 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002633 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002634 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002635 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002636
Chris Lattnerad3448c2003-02-18 19:57:07 +00002637 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002638 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002639 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002640 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002641 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002642 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002643 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002644 }
Chris Lattner40371712002-05-09 01:29:19 +00002645 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002646 }
Chris Lattnera2881962003-02-18 19:28:33 +00002647
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002648 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2649 if (Op0I->getOpcode() == Instruction::Add) {
2650 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2651 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2652 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2653 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2654 } else if (Op0I->getOpcode() == Instruction::Sub) {
2655 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002656 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002657 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002658 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002659 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002660
Chris Lattner50af16a2004-11-13 19:50:12 +00002661 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002662 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002663 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002664 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002665
Chris Lattner50af16a2004-11-13 19:50:12 +00002666 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002667 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002668 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002669 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002670 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002671}
2672
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002673Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2674 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2675
2676 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002677 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002678 return BinaryOperator::CreateFAdd(Op0, V);
2679
2680 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2681 if (Op1I->getOpcode() == Instruction::FAdd) {
2682 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002683 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002684 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002685 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002686 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002687 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002688 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002689 }
2690
2691 return 0;
2692}
2693
Chris Lattnera0141b92007-07-15 20:42:37 +00002694/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2695/// comparison only checks the sign bit. If it only checks the sign bit, set
2696/// TrueIfSigned if the result of the comparison is true when the input value is
2697/// signed.
2698static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2699 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002700 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002701 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2702 TrueIfSigned = true;
2703 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002704 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2705 TrueIfSigned = true;
2706 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002707 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2708 TrueIfSigned = false;
2709 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002710 case ICmpInst::ICMP_UGT:
2711 // True if LHS u> RHS and RHS == high-bit-mask - 1
2712 TrueIfSigned = true;
2713 return RHS->getValue() ==
2714 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2715 case ICmpInst::ICMP_UGE:
2716 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2717 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002718 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002719 default:
2720 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002721 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002722}
2723
Chris Lattner7e708292002-06-25 16:13:24 +00002724Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002725 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002726 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002727
Chris Lattnera2498472009-10-11 21:36:10 +00002728 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002729 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002730
Chris Lattner8af304a2009-10-11 07:53:15 +00002731 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002732 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2733 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002734
2735 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002736 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002737 if (SI->getOpcode() == Instruction::Shl)
2738 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002739 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002740 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002741
Zhou Sheng843f07672007-04-19 05:39:12 +00002742 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002743 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002744 if (CI->equalsInt(1)) // X * 1 == X
2745 return ReplaceInstUsesWith(I, Op0);
2746 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002747 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002748
Zhou Sheng97b52c22007-03-29 01:57:21 +00002749 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002750 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002751 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002752 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002753 }
Chris Lattnera2498472009-10-11 21:36:10 +00002754 } else if (isa<VectorType>(Op1C->getType())) {
2755 if (Op1C->isNullValue())
2756 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002757
Chris Lattnera2498472009-10-11 21:36:10 +00002758 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002759 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002760 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002761
2762 // As above, vector X*splat(1.0) -> X in all defined cases.
2763 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002764 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2765 if (CI->equalsInt(1))
2766 return ReplaceInstUsesWith(I, Op0);
2767 }
2768 }
Chris Lattnera2881962003-02-18 19:28:33 +00002769 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002770
2771 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2772 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002773 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002774 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00002775 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2776 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002777 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002778
2779 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002780
2781 // Try to fold constant mul into select arguments.
2782 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002783 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002784 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002785
2786 if (isa<PHINode>(Op0))
2787 if (Instruction *NV = FoldOpIntoPhi(I))
2788 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002789 }
2790
Dan Gohman186a6362009-08-12 16:04:34 +00002791 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002792 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002793 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002794
Nick Lewycky0c730792008-11-21 07:33:58 +00002795 // (X / Y) * Y = X - (X % Y)
2796 // (X / Y) * -Y = (X % Y) - X
2797 {
Chris Lattnera2498472009-10-11 21:36:10 +00002798 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00002799 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2800 if (!BO ||
2801 (BO->getOpcode() != Instruction::UDiv &&
2802 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00002803 Op1C = Op0;
2804 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002805 }
Chris Lattnera2498472009-10-11 21:36:10 +00002806 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00002807 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002808 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00002809 (BO->getOpcode() == Instruction::UDiv ||
2810 BO->getOpcode() == Instruction::SDiv)) {
2811 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2812
Dan Gohmanfa94b942009-08-12 16:33:09 +00002813 // If the division is exact, X % Y is zero.
2814 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2815 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00002816 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00002817 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00002818 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00002819 }
2820
Chris Lattner74381062009-08-30 07:44:24 +00002821 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002822 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002823 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002824 else
Chris Lattner74381062009-08-30 07:44:24 +00002825 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002826 Rem->takeName(BO);
2827
Chris Lattnera2498472009-10-11 21:36:10 +00002828 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00002829 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002830 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002831 }
2832 }
2833
Chris Lattner8af304a2009-10-11 07:53:15 +00002834 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00002835 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00002836 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002837
Chris Lattner8af304a2009-10-11 07:53:15 +00002838 // X*(1 << Y) --> X << Y
2839 // (1 << Y)*X --> X << Y
2840 {
2841 Value *Y;
2842 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00002843 return BinaryOperator::CreateShl(Op1, Y);
2844 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00002845 return BinaryOperator::CreateShl(Op0, Y);
2846 }
2847
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002848 // If one of the operands of the multiply is a cast from a boolean value, then
2849 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00002850 // X * Y (where Y is 0 or 1) -> X & (0-Y)
2851 if (!isa<VectorType>(I.getType())) {
2852 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00002853 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00002854
Chris Lattnerd2c58362009-10-11 21:29:45 +00002855 Value *BoolCast = 0, *OtherOp = 0;
2856 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00002857 BoolCast = Op0, OtherOp = Op1;
2858 else if (MaskedValueIsZero(Op1, Negative2))
2859 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00002860
Chris Lattner0036e3a2009-10-11 21:22:21 +00002861 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00002862 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2863 BoolCast, "tmp");
2864 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002865 }
2866 }
2867
Chris Lattner7e708292002-06-25 16:13:24 +00002868 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002869}
2870
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002871Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2872 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002873 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002874
2875 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00002876 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2877 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002878 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2879 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2880 if (Op1F->isExactlyValue(1.0))
2881 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00002882 } else if (isa<VectorType>(Op1C->getType())) {
2883 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002884 // As above, vector X*splat(1.0) -> X in all defined cases.
2885 if (Constant *Splat = Op1V->getSplatValue()) {
2886 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2887 if (F->isExactlyValue(1.0))
2888 return ReplaceInstUsesWith(I, Op0);
2889 }
2890 }
2891 }
2892
2893 // Try to fold constant mul into select arguments.
2894 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2895 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2896 return R;
2897
2898 if (isa<PHINode>(Op0))
2899 if (Instruction *NV = FoldOpIntoPhi(I))
2900 return NV;
2901 }
2902
Dan Gohman186a6362009-08-12 16:04:34 +00002903 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002904 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002905 return BinaryOperator::CreateFMul(Op0v, Op1v);
2906
2907 return Changed ? &I : 0;
2908}
2909
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002910/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2911/// instruction.
2912bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2913 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2914
2915 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2916 int NonNullOperand = -1;
2917 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2918 if (ST->isNullValue())
2919 NonNullOperand = 2;
2920 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2921 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2922 if (ST->isNullValue())
2923 NonNullOperand = 1;
2924
2925 if (NonNullOperand == -1)
2926 return false;
2927
2928 Value *SelectCond = SI->getOperand(0);
2929
2930 // Change the div/rem to use 'Y' instead of the select.
2931 I.setOperand(1, SI->getOperand(NonNullOperand));
2932
2933 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2934 // problem. However, the select, or the condition of the select may have
2935 // multiple uses. Based on our knowledge that the operand must be non-zero,
2936 // propagate the known value for the select into other uses of it, and
2937 // propagate a known value of the condition into its other users.
2938
2939 // If the select and condition only have a single use, don't bother with this,
2940 // early exit.
2941 if (SI->use_empty() && SelectCond->hasOneUse())
2942 return true;
2943
2944 // Scan the current block backward, looking for other uses of SI.
2945 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2946
2947 while (BBI != BBFront) {
2948 --BBI;
2949 // If we found a call to a function, we can't assume it will return, so
2950 // information from below it cannot be propagated above it.
2951 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2952 break;
2953
2954 // Replace uses of the select or its condition with the known values.
2955 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2956 I != E; ++I) {
2957 if (*I == SI) {
2958 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002959 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002960 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002961 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2962 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002963 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002964 }
2965 }
2966
2967 // If we past the instruction, quit looking for it.
2968 if (&*BBI == SI)
2969 SI = 0;
2970 if (&*BBI == SelectCond)
2971 SelectCond = 0;
2972
2973 // If we ran out of things to eliminate, break out of the loop.
2974 if (SelectCond == 0 && SI == 0)
2975 break;
2976
2977 }
2978 return true;
2979}
2980
2981
Reid Spencer1628cec2006-10-26 06:15:43 +00002982/// This function implements the transforms on div instructions that work
2983/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2984/// used by the visitors to those instructions.
2985/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002986Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002987 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002988
Chris Lattner50b2ca42008-02-19 06:12:18 +00002989 // undef / X -> 0 for integer.
2990 // undef / X -> undef for FP (the undef could be a snan).
2991 if (isa<UndefValue>(Op0)) {
2992 if (Op0->getType()->isFPOrFPVector())
2993 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002994 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002995 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002996
2997 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002998 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002999 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003000
Reid Spencer1628cec2006-10-26 06:15:43 +00003001 return 0;
3002}
Misha Brukmanfd939082005-04-21 23:48:37 +00003003
Reid Spencer1628cec2006-10-26 06:15:43 +00003004/// This function implements the transforms common to both integer division
3005/// instructions (udiv and sdiv). It is called by the visitors to those integer
3006/// division instructions.
3007/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003008Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003009 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3010
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003011 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003012 if (Op0 == Op1) {
3013 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003014 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003015 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003016 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003017 }
3018
Owen Andersoneed707b2009-07-24 23:12:02 +00003019 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003020 return ReplaceInstUsesWith(I, CI);
3021 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003022
Reid Spencer1628cec2006-10-26 06:15:43 +00003023 if (Instruction *Common = commonDivTransforms(I))
3024 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003025
3026 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3027 // This does not apply for fdiv.
3028 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3029 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003030
3031 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3032 // div X, 1 == X
3033 if (RHS->equalsInt(1))
3034 return ReplaceInstUsesWith(I, Op0);
3035
3036 // (X / C1) / C2 -> X / (C1*C2)
3037 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3038 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3039 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003040 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003041 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003042 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003043 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003044 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003045 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003046 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003047
Reid Spencerbca0e382007-03-23 20:05:17 +00003048 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003049 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3050 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3051 return R;
3052 if (isa<PHINode>(Op0))
3053 if (Instruction *NV = FoldOpIntoPhi(I))
3054 return NV;
3055 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003056 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003057
Chris Lattnera2881962003-02-18 19:28:33 +00003058 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003059 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003060 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003061 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003062
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003063 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003064 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003065 return ReplaceInstUsesWith(I, Op0);
3066
Nick Lewycky895f0852008-11-27 20:21:08 +00003067 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3068 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3069 // div X, 1 == X
3070 if (X->isOne())
3071 return ReplaceInstUsesWith(I, Op0);
3072 }
3073
Reid Spencer1628cec2006-10-26 06:15:43 +00003074 return 0;
3075}
3076
3077Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3078 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3079
3080 // Handle the integer div common cases
3081 if (Instruction *Common = commonIDivTransforms(I))
3082 return Common;
3083
Reid Spencer1628cec2006-10-26 06:15:43 +00003084 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003085 // X udiv C^2 -> X >> C
3086 // Check to see if this is an unsigned division with an exact power of 2,
3087 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003088 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003089 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003090 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003091
3092 // X udiv C, where C >= signbit
3093 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003094 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003095 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003096 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003097 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003098 }
3099
3100 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003101 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003102 if (RHSI->getOpcode() == Instruction::Shl &&
3103 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003104 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003105 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003106 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003107 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003108 if (uint32_t C2 = C1.logBase2())
3109 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003110 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003111 }
3112 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003113 }
3114
Reid Spencer1628cec2006-10-26 06:15:43 +00003115 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3116 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003117 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003118 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003119 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003120 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003121 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003122 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003123 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003124 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003125 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003126 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003127
3128 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003129 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003130 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003131
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003132 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003133 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003134 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003135 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003136 return 0;
3137}
3138
Reid Spencer1628cec2006-10-26 06:15:43 +00003139Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3140 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3141
3142 // Handle the integer div common cases
3143 if (Instruction *Common = commonIDivTransforms(I))
3144 return Common;
3145
3146 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3147 // sdiv X, -1 == -X
3148 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003149 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003150
Dan Gohmanfa94b942009-08-12 16:33:09 +00003151 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003152 if (cast<SDivOperator>(&I)->isExact() &&
3153 RHS->getValue().isNonNegative() &&
3154 RHS->getValue().isPowerOf2()) {
3155 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3156 RHS->getValue().exactLogBase2());
3157 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3158 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003159
3160 // -X/C --> X/-C provided the negation doesn't overflow.
3161 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3162 if (isa<Constant>(Sub->getOperand(0)) &&
3163 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003164 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003165 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3166 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003167 }
3168
3169 // If the sign bits of both operands are zero (i.e. we can prove they are
3170 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003171 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003172 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003173 if (MaskedValueIsZero(Op0, Mask)) {
3174 if (MaskedValueIsZero(Op1, Mask)) {
3175 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3176 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3177 }
3178 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003179 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003180 ShiftedInt->getValue().isPowerOf2()) {
3181 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3182 // Safe because the only negative value (1 << Y) can take on is
3183 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3184 // the sign bit set.
3185 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3186 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003187 }
Eli Friedman8be17392009-07-18 09:53:21 +00003188 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003189
3190 return 0;
3191}
3192
3193Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3194 return commonDivTransforms(I);
3195}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003196
Reid Spencer0a783f72006-11-02 01:53:59 +00003197/// This function implements the transforms on rem instructions that work
3198/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3199/// is used by the visitors to those instructions.
3200/// @brief Transforms common to all three rem instructions
3201Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003202 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003203
Chris Lattner50b2ca42008-02-19 06:12:18 +00003204 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3205 if (I.getType()->isFPOrFPVector())
3206 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003207 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003208 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003209 if (isa<UndefValue>(Op1))
3210 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003211
3212 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003213 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3214 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003215
Reid Spencer0a783f72006-11-02 01:53:59 +00003216 return 0;
3217}
3218
3219/// This function implements the transforms common to both integer remainder
3220/// instructions (urem and srem). It is called by the visitors to those integer
3221/// remainder instructions.
3222/// @brief Common integer remainder transforms
3223Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3224 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3225
3226 if (Instruction *common = commonRemTransforms(I))
3227 return common;
3228
Dale Johannesened6af242009-01-21 00:35:19 +00003229 // 0 % X == 0 for integer, we don't need to preserve faults!
3230 if (Constant *LHS = dyn_cast<Constant>(Op0))
3231 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003232 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003233
Chris Lattner857e8cd2004-12-12 21:48:58 +00003234 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003235 // X % 0 == undef, we don't need to preserve faults!
3236 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003237 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003238
Chris Lattnera2881962003-02-18 19:28:33 +00003239 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003240 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003241
Chris Lattner97943922006-02-28 05:49:21 +00003242 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3243 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3244 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3245 return R;
3246 } else if (isa<PHINode>(Op0I)) {
3247 if (Instruction *NV = FoldOpIntoPhi(I))
3248 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003249 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003250
3251 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003252 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003253 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003254 }
Chris Lattnera2881962003-02-18 19:28:33 +00003255 }
3256
Reid Spencer0a783f72006-11-02 01:53:59 +00003257 return 0;
3258}
3259
3260Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3261 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3262
3263 if (Instruction *common = commonIRemTransforms(I))
3264 return common;
3265
3266 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3267 // X urem C^2 -> X and C
3268 // Check to see if this is an unsigned remainder with an exact power of 2,
3269 // if so, convert to a bitwise and.
3270 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003271 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003272 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003273 }
3274
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003275 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003276 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3277 if (RHSI->getOpcode() == Instruction::Shl &&
3278 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003279 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003280 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003281 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003282 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003283 }
3284 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003285 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003286
Reid Spencer0a783f72006-11-02 01:53:59 +00003287 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3288 // where C1&C2 are powers of two.
3289 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3290 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3291 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3292 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003293 if ((STO->getValue().isPowerOf2()) &&
3294 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003295 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3296 SI->getName()+".t");
3297 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3298 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003299 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003300 }
3301 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003302 }
3303
Chris Lattner3f5b8772002-05-06 16:14:14 +00003304 return 0;
3305}
3306
Reid Spencer0a783f72006-11-02 01:53:59 +00003307Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3308 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3309
Dan Gohmancff55092007-11-05 23:16:33 +00003310 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003311 if (Instruction *Common = commonIRemTransforms(I))
3312 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003313
Dan Gohman186a6362009-08-12 16:04:34 +00003314 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003315 if (!isa<Constant>(RHSNeg) ||
3316 (isa<ConstantInt>(RHSNeg) &&
3317 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003318 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003319 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003320 I.setOperand(1, RHSNeg);
3321 return &I;
3322 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003323
Dan Gohmancff55092007-11-05 23:16:33 +00003324 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003325 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003326 if (I.getType()->isInteger()) {
3327 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3328 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3329 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003330 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003331 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003332 }
3333
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003334 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003335 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3336 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003337
Nick Lewycky9dce8732008-12-20 16:48:00 +00003338 bool hasNegative = false;
3339 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3340 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3341 if (RHS->getValue().isNegative())
3342 hasNegative = true;
3343
3344 if (hasNegative) {
3345 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003346 for (unsigned i = 0; i != VWidth; ++i) {
3347 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3348 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003349 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003350 else
3351 Elts[i] = RHS;
3352 }
3353 }
3354
Owen Andersonaf7ec972009-07-28 21:19:26 +00003355 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003356 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003357 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003358 I.setOperand(1, NewRHSV);
3359 return &I;
3360 }
3361 }
3362 }
3363
Reid Spencer0a783f72006-11-02 01:53:59 +00003364 return 0;
3365}
3366
3367Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003368 return commonRemTransforms(I);
3369}
3370
Chris Lattner457dd822004-06-09 07:59:58 +00003371// isOneBitSet - Return true if there is exactly one bit set in the specified
3372// constant.
3373static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003374 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003375}
3376
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003377// isHighOnes - Return true if the constant is of the form 1+0+.
3378// This is the same as lowones(~X).
3379static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003380 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003381}
3382
Reid Spencere4d87aa2006-12-23 06:05:41 +00003383/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003384/// are carefully arranged to allow folding of expressions such as:
3385///
3386/// (A < B) | (A > B) --> (A != B)
3387///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003388/// Note that this is only valid if the first and second predicates have the
3389/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003390///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003391/// Three bits are used to represent the condition, as follows:
3392/// 0 A > B
3393/// 1 A == B
3394/// 2 A < B
3395///
3396/// <=> Value Definition
3397/// 000 0 Always false
3398/// 001 1 A > B
3399/// 010 2 A == B
3400/// 011 3 A >= B
3401/// 100 4 A < B
3402/// 101 5 A != B
3403/// 110 6 A <= B
3404/// 111 7 Always true
3405///
3406static unsigned getICmpCode(const ICmpInst *ICI) {
3407 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003408 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003409 case ICmpInst::ICMP_UGT: return 1; // 001
3410 case ICmpInst::ICMP_SGT: return 1; // 001
3411 case ICmpInst::ICMP_EQ: return 2; // 010
3412 case ICmpInst::ICMP_UGE: return 3; // 011
3413 case ICmpInst::ICMP_SGE: return 3; // 011
3414 case ICmpInst::ICMP_ULT: return 4; // 100
3415 case ICmpInst::ICMP_SLT: return 4; // 100
3416 case ICmpInst::ICMP_NE: return 5; // 101
3417 case ICmpInst::ICMP_ULE: return 6; // 110
3418 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003419 // True -> 7
3420 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003421 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003422 return 0;
3423 }
3424}
3425
Evan Cheng8db90722008-10-14 17:15:11 +00003426/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3427/// predicate into a three bit mask. It also returns whether it is an ordered
3428/// predicate by reference.
3429static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3430 isOrdered = false;
3431 switch (CC) {
3432 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3433 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003434 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3435 case FCmpInst::FCMP_UGT: return 1; // 001
3436 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3437 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003438 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3439 case FCmpInst::FCMP_UGE: return 3; // 011
3440 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3441 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003442 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3443 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003444 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3445 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003446 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003447 default:
3448 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003449 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003450 return 0;
3451 }
3452}
3453
Reid Spencere4d87aa2006-12-23 06:05:41 +00003454/// getICmpValue - This is the complement of getICmpCode, which turns an
3455/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003456/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003457/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003458static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003459 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003460 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003461 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003462 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003463 case 1:
3464 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003465 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003466 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003467 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3468 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003469 case 3:
3470 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003471 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003472 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003473 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003474 case 4:
3475 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003476 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003477 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003478 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3479 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003480 case 6:
3481 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003482 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003483 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003484 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003485 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003486 }
3487}
3488
Evan Cheng8db90722008-10-14 17:15:11 +00003489/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3490/// opcode and two operands into either a FCmp instruction. isordered is passed
3491/// in to determine which kind of predicate to use in the new fcmp instruction.
3492static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003493 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003494 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003495 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003496 case 0:
3497 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003498 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003499 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003500 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003501 case 1:
3502 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003503 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003504 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003505 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003506 case 2:
3507 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003508 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003509 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003510 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003511 case 3:
3512 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003513 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003514 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003515 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003516 case 4:
3517 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003518 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003519 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003520 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003521 case 5:
3522 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003523 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003524 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003525 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003526 case 6:
3527 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003528 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003529 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003530 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003531 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003532 }
3533}
3534
Chris Lattnerb9553d62008-11-16 04:55:20 +00003535/// PredicatesFoldable - Return true if both predicates match sign or if at
3536/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003537static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003538 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3539 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3540 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003541}
3542
3543namespace {
3544// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3545struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003546 InstCombiner &IC;
3547 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003548 ICmpInst::Predicate pred;
3549 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3550 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3551 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003552 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003553 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3554 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003555 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3556 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003557 return false;
3558 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003559 Instruction *apply(Instruction &Log) const {
3560 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3561 if (ICI->getOperand(0) != LHS) {
3562 assert(ICI->getOperand(1) == LHS);
3563 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003564 }
3565
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003566 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003567 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003568 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003569 unsigned Code;
3570 switch (Log.getOpcode()) {
3571 case Instruction::And: Code = LHSCode & RHSCode; break;
3572 case Instruction::Or: Code = LHSCode | RHSCode; break;
3573 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003574 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003575 }
3576
Nick Lewycky4a134af2009-10-25 05:20:17 +00003577 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003578 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003579 if (Instruction *I = dyn_cast<Instruction>(RV))
3580 return I;
3581 // Otherwise, it's a constant boolean value...
3582 return IC.ReplaceInstUsesWith(Log, RV);
3583 }
3584};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003585} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003586
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003587// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3588// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003589// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003590Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003591 ConstantInt *OpRHS,
3592 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003593 BinaryOperator &TheAnd) {
3594 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003595 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003596 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003597 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003598
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003599 switch (Op->getOpcode()) {
3600 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003601 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003602 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003603 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003604 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003605 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003606 }
3607 break;
3608 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003609 if (Together == AndRHS) // (X | C) & C --> C
3610 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003611
Chris Lattner6e7ba452005-01-01 16:22:27 +00003612 if (Op->hasOneUse() && Together != OpRHS) {
3613 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003614 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003615 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003616 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003617 }
3618 break;
3619 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003620 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003621 // Adding a one to a single bit bit-field should be turned into an XOR
3622 // of the bit. First thing to check is to see if this AND is with a
3623 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003624 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003625
3626 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003627 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003628 // Ok, at this point, we know that we are masking the result of the
3629 // ADD down to exactly one bit. If the constant we are adding has
3630 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003631 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003632
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003633 // Check to see if any bits below the one bit set in AndRHSV are set.
3634 if ((AddRHS & (AndRHSV-1)) == 0) {
3635 // If not, the only thing that can effect the output of the AND is
3636 // the bit specified by AndRHSV. If that bit is set, the effect of
3637 // the XOR is to toggle the bit. If it is clear, then the ADD has
3638 // no effect.
3639 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3640 TheAnd.setOperand(0, X);
3641 return &TheAnd;
3642 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003643 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003644 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003645 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003646 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003647 }
3648 }
3649 }
3650 }
3651 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003652
3653 case Instruction::Shl: {
3654 // We know that the AND will not produce any of the bits shifted in, so if
3655 // the anded constant includes them, clear them now!
3656 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003657 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003658 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003659 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003660 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003661
Zhou Sheng290bec52007-03-29 08:15:12 +00003662 if (CI->getValue() == ShlMask) {
3663 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003664 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3665 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003666 TheAnd.setOperand(1, CI);
3667 return &TheAnd;
3668 }
3669 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003670 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003671 case Instruction::LShr:
3672 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003673 // We know that the AND will not produce any of the bits shifted in, so if
3674 // the anded constant includes them, clear them now! This only applies to
3675 // unsigned shifts, because a signed shr may bring in set bits!
3676 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003677 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003678 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003679 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003680 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003681
Zhou Sheng290bec52007-03-29 08:15:12 +00003682 if (CI->getValue() == ShrMask) {
3683 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003684 return ReplaceInstUsesWith(TheAnd, Op);
3685 } else if (CI != AndRHS) {
3686 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3687 return &TheAnd;
3688 }
3689 break;
3690 }
3691 case Instruction::AShr:
3692 // Signed shr.
3693 // See if this is shifting in some sign extension, then masking it out
3694 // with an and.
3695 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003696 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003697 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003698 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003699 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003700 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003701 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003702 // Make the argument unsigned.
3703 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003704 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003705 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003706 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003707 }
3708 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003709 }
3710 return 0;
3711}
3712
Chris Lattner8b170942002-08-09 23:47:40 +00003713
Chris Lattnera96879a2004-09-29 17:40:11 +00003714/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3715/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003716/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3717/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003718/// insert new instructions.
3719Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003720 bool isSigned, bool Inside,
3721 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003722 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003723 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003724 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003725
Chris Lattnera96879a2004-09-29 17:40:11 +00003726 if (Inside) {
3727 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003728 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003729
Reid Spencere4d87aa2006-12-23 06:05:41 +00003730 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003731 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003732 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003733 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003734 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003735 }
3736
3737 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003738 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003739 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003740 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003741 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003742 }
3743
3744 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003745 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003746
Reid Spencere4e40032007-03-21 23:19:50 +00003747 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003748 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003749 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003750 ICmpInst::Predicate pred = (isSigned ?
3751 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003752 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003753 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003754
Reid Spencere4e40032007-03-21 23:19:50 +00003755 // Emit V-Lo >u Hi-1-Lo
3756 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003757 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003758 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003759 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003760 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003761}
3762
Chris Lattner7203e152005-09-18 07:22:02 +00003763// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3764// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3765// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3766// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003767static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003768 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003769 uint32_t BitWidth = Val->getType()->getBitWidth();
3770 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003771
3772 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003773 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003774 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003775 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003776 return true;
3777}
3778
Chris Lattner7203e152005-09-18 07:22:02 +00003779/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3780/// where isSub determines whether the operator is a sub. If we can fold one of
3781/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003782///
3783/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3784/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3785/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3786///
3787/// return (A +/- B).
3788///
3789Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003790 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003791 Instruction &I) {
3792 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3793 if (!LHSI || LHSI->getNumOperands() != 2 ||
3794 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3795
3796 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3797
3798 switch (LHSI->getOpcode()) {
3799 default: return 0;
3800 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003801 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003802 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003803 if ((Mask->getValue().countLeadingZeros() +
3804 Mask->getValue().countPopulation()) ==
3805 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003806 break;
3807
3808 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3809 // part, we don't need any explicit masks to take them out of A. If that
3810 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003811 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003812 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003813 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003814 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003815 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003816 break;
3817 }
3818 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003819 return 0;
3820 case Instruction::Or:
3821 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003822 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003823 if ((Mask->getValue().countLeadingZeros() +
3824 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003825 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003826 break;
3827 return 0;
3828 }
3829
Chris Lattnerc8e77562005-09-18 04:24:45 +00003830 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003831 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3832 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003833}
3834
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003835/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3836Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3837 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003838 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003839 ConstantInt *LHSCst, *RHSCst;
3840 ICmpInst::Predicate LHSCC, RHSCC;
3841
Chris Lattnerea065fb2008-11-16 05:10:52 +00003842 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003843 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003844 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003845 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003846 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003847 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003848
3849 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3850 // where C is a power of 2
3851 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3852 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003853 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003854 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003855 }
3856
3857 // From here on, we only handle:
3858 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3859 if (Val != Val2) return 0;
3860
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003861 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3862 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3863 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3864 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3865 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3866 return 0;
3867
3868 // We can't fold (ugt x, C) & (sgt x, C2).
3869 if (!PredicatesFoldable(LHSCC, RHSCC))
3870 return 0;
3871
3872 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003873 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00003874 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003875 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00003876 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003877 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003878 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003879 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3880
3881 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003882 std::swap(LHS, RHS);
3883 std::swap(LHSCst, RHSCst);
3884 std::swap(LHSCC, RHSCC);
3885 }
3886
3887 // At this point, we know we have have two icmp instructions
3888 // comparing a value against two constants and and'ing the result
3889 // together. Because of the above check, we know that we only have
3890 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3891 // (from the FoldICmpLogical check above), that the two constants
3892 // are not equal and that the larger constant is on the RHS
3893 assert(LHSCst != RHSCst && "Compares not folded above?");
3894
3895 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003896 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003897 case ICmpInst::ICMP_EQ:
3898 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003899 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003900 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3901 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3902 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003903 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003904 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3905 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3906 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3907 return ReplaceInstUsesWith(I, LHS);
3908 }
3909 case ICmpInst::ICMP_NE:
3910 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003911 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003912 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003913 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003914 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003915 break; // (X != 13 & X u< 15) -> no change
3916 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003917 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003918 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003919 break; // (X != 13 & X s< 15) -> no change
3920 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3921 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3922 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3923 return ReplaceInstUsesWith(I, RHS);
3924 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003925 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003926 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003927 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003928 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003929 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003930 }
3931 break; // (X != 13 & X != 15) -> no change
3932 }
3933 break;
3934 case ICmpInst::ICMP_ULT:
3935 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003936 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003937 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3938 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003939 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003940 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3941 break;
3942 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3943 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3944 return ReplaceInstUsesWith(I, LHS);
3945 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3946 break;
3947 }
3948 break;
3949 case ICmpInst::ICMP_SLT:
3950 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003951 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003952 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3953 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003954 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003955 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3956 break;
3957 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3958 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3959 return ReplaceInstUsesWith(I, LHS);
3960 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3961 break;
3962 }
3963 break;
3964 case ICmpInst::ICMP_UGT:
3965 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003966 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003967 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3968 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3969 return ReplaceInstUsesWith(I, RHS);
3970 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3971 break;
3972 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003973 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003974 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003975 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003976 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003977 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003978 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003979 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3980 break;
3981 }
3982 break;
3983 case ICmpInst::ICMP_SGT:
3984 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003985 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003986 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3987 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3988 return ReplaceInstUsesWith(I, RHS);
3989 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3990 break;
3991 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003992 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003993 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003994 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003995 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003996 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003997 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003998 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3999 break;
4000 }
4001 break;
4002 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004003
4004 return 0;
4005}
4006
Chris Lattner42d1be02009-07-23 05:14:02 +00004007Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4008 FCmpInst *RHS) {
4009
4010 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4011 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4012 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4013 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4014 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4015 // If either of the constants are nans, then the whole thing returns
4016 // false.
4017 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004018 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004019 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004020 LHS->getOperand(0), RHS->getOperand(0));
4021 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004022
4023 // Handle vector zeros. This occurs because the canonical form of
4024 // "fcmp ord x,x" is "fcmp ord x, 0".
4025 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4026 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004027 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004028 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004029 return 0;
4030 }
4031
4032 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4033 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4034 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4035
4036
4037 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4038 // Swap RHS operands to match LHS.
4039 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4040 std::swap(Op1LHS, Op1RHS);
4041 }
4042
4043 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4044 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4045 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004046 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004047
4048 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004049 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004050 if (Op0CC == FCmpInst::FCMP_TRUE)
4051 return ReplaceInstUsesWith(I, RHS);
4052 if (Op1CC == FCmpInst::FCMP_TRUE)
4053 return ReplaceInstUsesWith(I, LHS);
4054
4055 bool Op0Ordered;
4056 bool Op1Ordered;
4057 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4058 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4059 if (Op1Pred == 0) {
4060 std::swap(LHS, RHS);
4061 std::swap(Op0Pred, Op1Pred);
4062 std::swap(Op0Ordered, Op1Ordered);
4063 }
4064 if (Op0Pred == 0) {
4065 // uno && ueq -> uno && (uno || eq) -> ueq
4066 // ord && olt -> ord && (ord && lt) -> olt
4067 if (Op0Ordered == Op1Ordered)
4068 return ReplaceInstUsesWith(I, RHS);
4069
4070 // uno && oeq -> uno && (ord && eq) -> false
4071 // uno && ord -> false
4072 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004073 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004074 // ord && ueq -> ord && (uno || eq) -> oeq
4075 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4076 Op0LHS, Op0RHS, Context));
4077 }
4078 }
4079
4080 return 0;
4081}
4082
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004083
Chris Lattner7e708292002-06-25 16:13:24 +00004084Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004085 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004086 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004087
Chris Lattnere87597f2004-10-16 18:11:37 +00004088 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004089 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004090
Chris Lattner6e7ba452005-01-01 16:22:27 +00004091 // and X, X = X
4092 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004093 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004094
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004095 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004096 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004097 if (SimplifyDemandedInstructionBits(I))
4098 return &I;
4099 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004100 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004101 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004102 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004103 } else if (isa<ConstantAggregateZero>(Op1)) {
4104 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004105 }
4106 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004107
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004108 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004109 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004110 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004111
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004112 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004113 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004114 Value *Op0LHS = Op0I->getOperand(0);
4115 Value *Op0RHS = Op0I->getOperand(1);
4116 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004117 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004118 case Instruction::Xor:
4119 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004120 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004121 if (!Op0I->hasOneUse()) break;
4122
4123 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4124 // Not masking anything out for the LHS, move to RHS.
4125 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4126 Op0RHS->getName()+".masked");
4127 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4128 }
4129 if (!isa<Constant>(Op0RHS) &&
4130 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4131 // Not masking anything out for the RHS, move to LHS.
4132 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4133 Op0LHS->getName()+".masked");
4134 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004135 }
4136
Chris Lattner6e7ba452005-01-01 16:22:27 +00004137 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004138 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004139 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4140 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4141 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4142 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004143 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004144 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004145 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004146 break;
4147
4148 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004149 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4150 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4151 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4152 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004153 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004154
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004155 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4156 // has 1's for all bits that the subtraction with A might affect.
4157 if (Op0I->hasOneUse()) {
4158 uint32_t BitWidth = AndRHSMask.getBitWidth();
4159 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4160 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4161
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004162 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004163 if (!(A && A->isZero()) && // avoid infinite recursion.
4164 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004165 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004166 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4167 }
4168 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004169 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004170
4171 case Instruction::Shl:
4172 case Instruction::LShr:
4173 // (1 << x) & 1 --> zext(x == 0)
4174 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004175 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004176 Value *NewICmp =
4177 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004178 return new ZExtInst(NewICmp, I.getType());
4179 }
4180 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004181 }
4182
Chris Lattner58403262003-07-23 19:25:52 +00004183 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004184 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004185 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004186 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004187 // If this is an integer truncation or change from signed-to-unsigned, and
4188 // if the source is an and/or with immediate, transform it. This
4189 // frequently occurs for bitfield accesses.
4190 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004191 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004192 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004193 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004194 if (CastOp->getOpcode() == Instruction::And) {
4195 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004196 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4197 // This will fold the two constants together, which may allow
4198 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004199 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004200 CastOp->getOperand(0), I.getType(),
4201 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004202 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004203 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004204 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004205 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004206 } else if (CastOp->getOpcode() == Instruction::Or) {
4207 // Change: and (cast (or X, C1) to T), C2
4208 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004209 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004210 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004211 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004212 return ReplaceInstUsesWith(I, AndRHS);
4213 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004214 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004215 }
Chris Lattner06782f82003-07-23 19:36:21 +00004216 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004217
4218 // Try to fold constant and into select arguments.
4219 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004220 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004221 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004222 if (isa<PHINode>(Op0))
4223 if (Instruction *NV = FoldOpIntoPhi(I))
4224 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004225 }
4226
Dan Gohman186a6362009-08-12 16:04:34 +00004227 Value *Op0NotVal = dyn_castNotVal(Op0);
4228 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004229
Chris Lattner5b62aa72004-06-18 06:07:51 +00004230 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004231 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004232
Misha Brukmancb6267b2004-07-30 12:50:08 +00004233 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004234 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004235 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4236 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004237 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004238 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004239
4240 {
Chris Lattner003b6202007-06-15 05:58:24 +00004241 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004242 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004243 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4244 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004245
4246 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004247 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004248 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004249 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004250 }
4251 }
4252
Dan Gohman4ae51262009-08-12 16:23:25 +00004253 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004254 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4255 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004256
4257 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004258 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004259 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004260 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004261 }
4262 }
Chris Lattner64daab52006-04-01 08:03:55 +00004263
4264 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004265 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004266 if (A == Op1) { // (A^B)&A -> A&(A^B)
4267 I.swapOperands(); // Simplify below
4268 std::swap(Op0, Op1);
4269 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4270 cast<BinaryOperator>(Op0)->swapOperands();
4271 I.swapOperands(); // Simplify below
4272 std::swap(Op0, Op1);
4273 }
4274 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004275
Chris Lattner64daab52006-04-01 08:03:55 +00004276 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004277 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004278 if (B == Op0) { // B&(A^B) -> B&(B^A)
4279 cast<BinaryOperator>(Op1)->swapOperands();
4280 std::swap(A, B);
4281 }
Chris Lattner74381062009-08-30 07:44:24 +00004282 if (A == Op0) // A&(A^B) -> A & ~B
4283 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004284 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004285
4286 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004287 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4288 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004289 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004290 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4291 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004292 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004293 }
4294
Reid Spencere4d87aa2006-12-23 06:05:41 +00004295 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4296 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004297 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004298 return R;
4299
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004300 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4301 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4302 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004303 }
4304
Chris Lattner6fc205f2006-05-05 06:39:07 +00004305 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004306 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4307 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4308 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4309 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004310 if (SrcTy == Op1C->getOperand(0)->getType() &&
4311 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004312 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004313 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4314 I.getType(), TD) &&
4315 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4316 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004317 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4318 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004319 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004320 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004321 }
Chris Lattnere511b742006-11-14 07:46:50 +00004322
4323 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004324 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4325 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4326 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004327 SI0->getOperand(1) == SI1->getOperand(1) &&
4328 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004329 Value *NewOp =
4330 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4331 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004332 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004333 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004334 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004335 }
4336
Evan Cheng8db90722008-10-14 17:15:11 +00004337 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004338 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004339 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4340 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4341 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004342 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004343
Chris Lattner7e708292002-06-25 16:13:24 +00004344 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004345}
4346
Chris Lattner8c34cd22008-10-05 02:13:19 +00004347/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4348/// capable of providing pieces of a bswap. The subexpression provides pieces
4349/// of a bswap if it is proven that each of the non-zero bytes in the output of
4350/// the expression came from the corresponding "byte swapped" byte in some other
4351/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4352/// we know that the expression deposits the low byte of %X into the high byte
4353/// of the bswap result and that all other bytes are zero. This expression is
4354/// accepted, the high byte of ByteValues is set to X to indicate a correct
4355/// match.
4356///
4357/// This function returns true if the match was unsuccessful and false if so.
4358/// On entry to the function the "OverallLeftShift" is a signed integer value
4359/// indicating the number of bytes that the subexpression is later shifted. For
4360/// example, if the expression is later right shifted by 16 bits, the
4361/// OverallLeftShift value would be -2 on entry. This is used to specify which
4362/// byte of ByteValues is actually being set.
4363///
4364/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4365/// byte is masked to zero by a user. For example, in (X & 255), X will be
4366/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4367/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4368/// always in the local (OverallLeftShift) coordinate space.
4369///
4370static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4371 SmallVector<Value*, 8> &ByteValues) {
4372 if (Instruction *I = dyn_cast<Instruction>(V)) {
4373 // If this is an or instruction, it may be an inner node of the bswap.
4374 if (I->getOpcode() == Instruction::Or) {
4375 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4376 ByteValues) ||
4377 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4378 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004379 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004380
4381 // If this is a logical shift by a constant multiple of 8, recurse with
4382 // OverallLeftShift and ByteMask adjusted.
4383 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4384 unsigned ShAmt =
4385 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4386 // Ensure the shift amount is defined and of a byte value.
4387 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4388 return true;
4389
4390 unsigned ByteShift = ShAmt >> 3;
4391 if (I->getOpcode() == Instruction::Shl) {
4392 // X << 2 -> collect(X, +2)
4393 OverallLeftShift += ByteShift;
4394 ByteMask >>= ByteShift;
4395 } else {
4396 // X >>u 2 -> collect(X, -2)
4397 OverallLeftShift -= ByteShift;
4398 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004399 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004400 }
4401
4402 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4403 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4404
4405 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4406 ByteValues);
4407 }
4408
4409 // If this is a logical 'and' with a mask that clears bytes, clear the
4410 // corresponding bytes in ByteMask.
4411 if (I->getOpcode() == Instruction::And &&
4412 isa<ConstantInt>(I->getOperand(1))) {
4413 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4414 unsigned NumBytes = ByteValues.size();
4415 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4416 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4417
4418 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4419 // If this byte is masked out by a later operation, we don't care what
4420 // the and mask is.
4421 if ((ByteMask & (1 << i)) == 0)
4422 continue;
4423
4424 // If the AndMask is all zeros for this byte, clear the bit.
4425 APInt MaskB = AndMask & Byte;
4426 if (MaskB == 0) {
4427 ByteMask &= ~(1U << i);
4428 continue;
4429 }
4430
4431 // If the AndMask is not all ones for this byte, it's not a bytezap.
4432 if (MaskB != Byte)
4433 return true;
4434
4435 // Otherwise, this byte is kept.
4436 }
4437
4438 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4439 ByteValues);
4440 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004441 }
4442
Chris Lattner8c34cd22008-10-05 02:13:19 +00004443 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4444 // the input value to the bswap. Some observations: 1) if more than one byte
4445 // is demanded from this input, then it could not be successfully assembled
4446 // into a byteswap. At least one of the two bytes would not be aligned with
4447 // their ultimate destination.
4448 if (!isPowerOf2_32(ByteMask)) return true;
4449 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004450
Chris Lattner8c34cd22008-10-05 02:13:19 +00004451 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4452 // is demanded, it needs to go into byte 0 of the result. This means that the
4453 // byte needs to be shifted until it lands in the right byte bucket. The
4454 // shift amount depends on the position: if the byte is coming from the high
4455 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4456 // low part, it must be shifted left.
4457 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4458 if (InputByteNo < ByteValues.size()/2) {
4459 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4460 return true;
4461 } else {
4462 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4463 return true;
4464 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004465
4466 // If the destination byte value is already defined, the values are or'd
4467 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004468 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004469 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004470 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004471 return false;
4472}
4473
4474/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4475/// If so, insert the new bswap intrinsic and return it.
4476Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004477 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004478 if (!ITy || ITy->getBitWidth() % 16 ||
4479 // ByteMask only allows up to 32-byte values.
4480 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004481 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004482
4483 /// ByteValues - For each byte of the result, we keep track of which value
4484 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004485 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004486 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004487
4488 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004489 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4490 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004491 return 0;
4492
4493 // Check to see if all of the bytes come from the same value.
4494 Value *V = ByteValues[0];
4495 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4496
4497 // Check to make sure that all of the bytes come from the same value.
4498 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4499 if (ByteValues[i] != V)
4500 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004501 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004502 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004503 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004504 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004505}
4506
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004507/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4508/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4509/// we can simplify this expression to "cond ? C : D or B".
4510static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004511 Value *C, Value *D,
4512 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004513 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004514 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004515 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004516 return 0;
4517
Chris Lattnera6a474d2008-11-16 04:26:55 +00004518 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004519 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004520 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004521 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004522 return SelectInst::Create(Cond, C, B);
4523 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004524 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004525 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004526 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004527 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004528 return 0;
4529}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004530
Chris Lattner69d4ced2008-11-16 05:20:07 +00004531/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4532Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4533 ICmpInst *LHS, ICmpInst *RHS) {
4534 Value *Val, *Val2;
4535 ConstantInt *LHSCst, *RHSCst;
4536 ICmpInst::Predicate LHSCC, RHSCC;
4537
4538 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004539 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004540 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004541 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004542 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004543 return 0;
4544
4545 // From here on, we only handle:
4546 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4547 if (Val != Val2) return 0;
4548
4549 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4550 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4551 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4552 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4553 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4554 return 0;
4555
4556 // We can't fold (ugt x, C) | (sgt x, C2).
4557 if (!PredicatesFoldable(LHSCC, RHSCC))
4558 return 0;
4559
4560 // Ensure that the larger constant is on the RHS.
4561 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004562 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004563 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004564 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004565 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4566 else
4567 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4568
4569 if (ShouldSwap) {
4570 std::swap(LHS, RHS);
4571 std::swap(LHSCst, RHSCst);
4572 std::swap(LHSCC, RHSCC);
4573 }
4574
4575 // At this point, we know we have have two icmp instructions
4576 // comparing a value against two constants and or'ing the result
4577 // together. Because of the above check, we know that we only have
4578 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4579 // FoldICmpLogical check above), that the two constants are not
4580 // equal.
4581 assert(LHSCst != RHSCst && "Compares not folded above?");
4582
4583 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004584 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004585 case ICmpInst::ICMP_EQ:
4586 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004587 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004588 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004589 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004590 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004591 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004592 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004593 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004594 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004595 }
4596 break; // (X == 13 | X == 15) -> no change
4597 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4598 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4599 break;
4600 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4601 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4602 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4603 return ReplaceInstUsesWith(I, RHS);
4604 }
4605 break;
4606 case ICmpInst::ICMP_NE:
4607 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004608 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004609 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4610 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4611 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4612 return ReplaceInstUsesWith(I, LHS);
4613 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4614 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4615 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004616 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004617 }
4618 break;
4619 case ICmpInst::ICMP_ULT:
4620 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004621 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004622 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4623 break;
4624 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4625 // If RHSCst is [us]MAXINT, it is always false. Not handling
4626 // this can cause overflow.
4627 if (RHSCst->isMaxValue(false))
4628 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004629 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004630 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004631 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4632 break;
4633 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4634 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4635 return ReplaceInstUsesWith(I, RHS);
4636 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4637 break;
4638 }
4639 break;
4640 case ICmpInst::ICMP_SLT:
4641 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004642 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004643 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4644 break;
4645 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4646 // If RHSCst is [us]MAXINT, it is always false. Not handling
4647 // this can cause overflow.
4648 if (RHSCst->isMaxValue(true))
4649 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004650 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004651 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004652 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4653 break;
4654 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4655 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4656 return ReplaceInstUsesWith(I, RHS);
4657 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4658 break;
4659 }
4660 break;
4661 case ICmpInst::ICMP_UGT:
4662 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004663 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004664 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4665 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4666 return ReplaceInstUsesWith(I, LHS);
4667 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4668 break;
4669 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4670 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004671 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004672 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4673 break;
4674 }
4675 break;
4676 case ICmpInst::ICMP_SGT:
4677 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004678 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004679 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4680 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4681 return ReplaceInstUsesWith(I, LHS);
4682 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4683 break;
4684 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4685 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004686 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004687 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4688 break;
4689 }
4690 break;
4691 }
4692 return 0;
4693}
4694
Chris Lattner5414cc52009-07-23 05:46:22 +00004695Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4696 FCmpInst *RHS) {
4697 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4698 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4699 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4700 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4701 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4702 // If either of the constants are nans, then the whole thing returns
4703 // true.
4704 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004705 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004706
4707 // Otherwise, no need to compare the two constants, compare the
4708 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004709 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004710 LHS->getOperand(0), RHS->getOperand(0));
4711 }
4712
4713 // Handle vector zeros. This occurs because the canonical form of
4714 // "fcmp uno x,x" is "fcmp uno x, 0".
4715 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4716 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004717 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004718 LHS->getOperand(0), RHS->getOperand(0));
4719
4720 return 0;
4721 }
4722
4723 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4724 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4725 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4726
4727 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4728 // Swap RHS operands to match LHS.
4729 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4730 std::swap(Op1LHS, Op1RHS);
4731 }
4732 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4733 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4734 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004735 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004736 Op0LHS, Op0RHS);
4737 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004738 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004739 if (Op0CC == FCmpInst::FCMP_FALSE)
4740 return ReplaceInstUsesWith(I, RHS);
4741 if (Op1CC == FCmpInst::FCMP_FALSE)
4742 return ReplaceInstUsesWith(I, LHS);
4743 bool Op0Ordered;
4744 bool Op1Ordered;
4745 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4746 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4747 if (Op0Ordered == Op1Ordered) {
4748 // If both are ordered or unordered, return a new fcmp with
4749 // or'ed predicates.
4750 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4751 Op0LHS, Op0RHS, Context);
4752 if (Instruction *I = dyn_cast<Instruction>(RV))
4753 return I;
4754 // Otherwise, it's a constant boolean value...
4755 return ReplaceInstUsesWith(I, RV);
4756 }
4757 }
4758 return 0;
4759}
4760
Bill Wendlinga698a472008-12-01 08:23:25 +00004761/// FoldOrWithConstants - This helper function folds:
4762///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004763/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004764///
4765/// into:
4766///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004767/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004768///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004769/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004770Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004771 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004772 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4773 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004774
Bill Wendling286a0542008-12-02 06:24:20 +00004775 Value *V1 = 0;
4776 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004777 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004778
Bill Wendling29976b92008-12-02 06:18:11 +00004779 APInt Xor = CI1->getValue() ^ CI2->getValue();
4780 if (!Xor.isAllOnesValue()) return 0;
4781
Bill Wendling286a0542008-12-02 06:24:20 +00004782 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004783 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004784 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004785 }
4786
4787 return 0;
4788}
4789
Chris Lattner7e708292002-06-25 16:13:24 +00004790Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004791 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004792 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004793
Chris Lattner42593e62007-03-24 23:56:43 +00004794 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004795 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004796
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004797 // or X, X = X
4798 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004799 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004800
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004801 // See if we can simplify any instructions used by the instruction whose sole
4802 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004803 if (SimplifyDemandedInstructionBits(I))
4804 return &I;
4805 if (isa<VectorType>(I.getType())) {
4806 if (isa<ConstantAggregateZero>(Op1)) {
4807 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4808 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4809 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4810 return ReplaceInstUsesWith(I, I.getOperand(1));
4811 }
Chris Lattner42593e62007-03-24 23:56:43 +00004812 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004813
Chris Lattner3f5b8772002-05-06 16:14:14 +00004814 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004815 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004816 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004817 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004818 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004819 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004820 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004821 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004822 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004823 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004824 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004825
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004826 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004827 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004828 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004829 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004830 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004831 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004832 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004833 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004834
4835 // Try to fold constant and into select arguments.
4836 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004837 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004838 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004839 if (isa<PHINode>(Op0))
4840 if (Instruction *NV = FoldOpIntoPhi(I))
4841 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004842 }
4843
Chris Lattner4f637d42006-01-06 17:59:59 +00004844 Value *A = 0, *B = 0;
4845 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004846
Dan Gohman4ae51262009-08-12 16:23:25 +00004847 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004848 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4849 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004850 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004851 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4852 return ReplaceInstUsesWith(I, Op0);
4853
Chris Lattner6423d4c2006-07-10 20:25:24 +00004854 // (A | B) | C and A | (B | C) -> bswap if possible.
4855 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004856 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4857 match(Op1, m_Or(m_Value(), m_Value())) ||
4858 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4859 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004860 if (Instruction *BSwap = MatchBSwap(I))
4861 return BSwap;
4862 }
4863
Chris Lattner6e4c6492005-05-09 04:58:36 +00004864 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004865 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004866 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004867 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004868 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004869 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004870 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004871 }
4872
4873 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004874 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004875 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004876 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004877 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004878 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004879 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004880 }
4881
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004882 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004883 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004884 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4885 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004886 Value *V1 = 0, *V2 = 0, *V3 = 0;
4887 C1 = dyn_cast<ConstantInt>(C);
4888 C2 = dyn_cast<ConstantInt>(D);
4889 if (C1 && C2) { // (A & C1)|(B & C2)
4890 // If we have: ((V + N) & C1) | (V & C2)
4891 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4892 // replace with V+N.
4893 if (C1->getValue() == ~C2->getValue()) {
4894 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004895 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004896 // Add commutes, try both ways.
4897 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4898 return ReplaceInstUsesWith(I, A);
4899 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4900 return ReplaceInstUsesWith(I, A);
4901 }
4902 // Or commutes, try both ways.
4903 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004904 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004905 // Add commutes, try both ways.
4906 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4907 return ReplaceInstUsesWith(I, B);
4908 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4909 return ReplaceInstUsesWith(I, B);
4910 }
4911 }
Chris Lattner044e5332007-04-08 08:01:49 +00004912 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004913 }
4914
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004915 // Check to see if we have any common things being and'ed. If so, find the
4916 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004917 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4918 if (A == B) // (A & C)|(A & D) == A & (C|D)
4919 V1 = A, V2 = C, V3 = D;
4920 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4921 V1 = A, V2 = B, V3 = C;
4922 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4923 V1 = C, V2 = A, V3 = D;
4924 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4925 V1 = C, V2 = A, V3 = B;
4926
4927 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004928 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004929 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004930 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004931 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004932
Dan Gohman1975d032008-10-30 20:40:10 +00004933 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004934 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004935 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004936 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004937 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004938 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004939 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004940 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004941 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004942
Bill Wendlingb01865c2008-11-30 13:52:49 +00004943 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004944 if ((match(C, m_Not(m_Specific(D))) &&
4945 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004946 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004947 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004948 if ((match(A, m_Not(m_Specific(D))) &&
4949 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004950 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004951 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004952 if ((match(C, m_Not(m_Specific(B))) &&
4953 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004954 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004955 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004956 if ((match(A, m_Not(m_Specific(B))) &&
4957 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004958 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004959 }
Chris Lattnere511b742006-11-14 07:46:50 +00004960
4961 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004962 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4963 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4964 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004965 SI0->getOperand(1) == SI1->getOperand(1) &&
4966 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004967 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4968 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004969 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004970 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004971 }
4972 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004973
Bill Wendlingb3833d12008-12-01 01:07:11 +00004974 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004975 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4976 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004977 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004978 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004979 }
4980 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004981 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4982 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004983 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004984 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004985 }
4986
Chris Lattner48b59ec2009-10-26 15:40:07 +00004987 if ((A = dyn_castNotVal(Op0))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004988 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004989 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004990 } else {
4991 A = 0;
4992 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004993 // Note, A is still live here!
Chris Lattner48b59ec2009-10-26 15:40:07 +00004994 if ((B = dyn_castNotVal(Op1))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004995 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004996 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004997
Misha Brukmancb6267b2004-07-30 12:50:08 +00004998 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004999 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00005000 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00005001 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005002 }
Chris Lattnera27231a2003-03-10 23:13:59 +00005003 }
Chris Lattnera2881962003-02-18 19:28:33 +00005004
Reid Spencere4d87aa2006-12-23 06:05:41 +00005005 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5006 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005007 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005008 return R;
5009
Chris Lattner69d4ced2008-11-16 05:20:07 +00005010 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5011 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5012 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005013 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005014
5015 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005016 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005017 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005018 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005019 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5020 !isa<ICmpInst>(Op1C->getOperand(0))) {
5021 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005022 if (SrcTy == Op1C->getOperand(0)->getType() &&
5023 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005024 // Only do this if the casts both really cause code to be
5025 // generated.
5026 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5027 I.getType(), TD) &&
5028 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5029 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005030 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5031 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005032 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005033 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005034 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005035 }
Chris Lattner99c65742007-10-24 05:38:08 +00005036 }
5037
5038
5039 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5040 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005041 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5042 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5043 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005044 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005045
Chris Lattner7e708292002-06-25 16:13:24 +00005046 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005047}
5048
Dan Gohman844731a2008-05-13 00:00:25 +00005049namespace {
5050
Chris Lattnerc317d392004-02-16 01:20:27 +00005051// XorSelf - Implements: X ^ X --> 0
5052struct XorSelf {
5053 Value *RHS;
5054 XorSelf(Value *rhs) : RHS(rhs) {}
5055 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5056 Instruction *apply(BinaryOperator &Xor) const {
5057 return &Xor;
5058 }
5059};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005060
Dan Gohman844731a2008-05-13 00:00:25 +00005061}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005062
Chris Lattner7e708292002-06-25 16:13:24 +00005063Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005064 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005065 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005066
Evan Chengd34af782008-03-25 20:07:13 +00005067 if (isa<UndefValue>(Op1)) {
5068 if (isa<UndefValue>(Op0))
5069 // Handle undef ^ undef -> 0 special case. This is a common
5070 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005071 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005072 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005073 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005074
Chris Lattnerc317d392004-02-16 01:20:27 +00005075 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005076 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005077 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005078 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005079 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005080
5081 // See if we can simplify any instructions used by the instruction whose sole
5082 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005083 if (SimplifyDemandedInstructionBits(I))
5084 return &I;
5085 if (isa<VectorType>(I.getType()))
5086 if (isa<ConstantAggregateZero>(Op1))
5087 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005088
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005089 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005090 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005091 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5092 if (Op0I->getOpcode() == Instruction::And ||
5093 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005094 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5095 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5096 if (dyn_castNotVal(Op0I->getOperand(1)))
5097 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005098 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005099 Value *NotY =
5100 Builder->CreateNot(Op0I->getOperand(1),
5101 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005102 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005103 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005104 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005105 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005106
5107 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5108 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5109 if (isFreeToInvert(Op0I->getOperand(0)) &&
5110 isFreeToInvert(Op0I->getOperand(1))) {
5111 Value *NotX =
5112 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5113 Value *NotY =
5114 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5115 if (Op0I->getOpcode() == Instruction::And)
5116 return BinaryOperator::CreateOr(NotX, NotY);
5117 return BinaryOperator::CreateAnd(NotX, NotY);
5118 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005119 }
5120 }
5121 }
5122
5123
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005124 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005125 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005126 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005127 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005128 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005129 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005130
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005131 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005132 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005133 FCI->getOperand(0), FCI->getOperand(1));
5134 }
5135
Nick Lewycky517e1f52008-05-31 19:01:33 +00005136 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5137 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5138 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5139 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5140 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005141 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5142 (RHS == ConstantExpr::getCast(Opcode,
5143 ConstantInt::getTrue(*Context),
5144 Op0C->getDestTy()))) {
5145 CI->setPredicate(CI->getInversePredicate());
5146 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005147 }
5148 }
5149 }
5150 }
5151
Reid Spencere4d87aa2006-12-23 06:05:41 +00005152 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005153 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005154 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5155 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005156 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5157 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005158 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005159 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005160 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005161
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005162 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005163 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005164 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005165 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005166 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005167 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005168 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005169 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005170 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005171 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005172 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005173 Constant *C = ConstantInt::get(*Context,
5174 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005175 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005176
Chris Lattner7c4049c2004-01-12 19:35:11 +00005177 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005178 } else if (Op0I->getOpcode() == Instruction::Or) {
5179 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005180 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005181 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005182 // Anything in both C1 and C2 is known to be zero, remove it from
5183 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005184 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5185 NewRHS = ConstantExpr::getAnd(NewRHS,
5186 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005187 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005188 I.setOperand(0, Op0I->getOperand(0));
5189 I.setOperand(1, NewRHS);
5190 return &I;
5191 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005192 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005193 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005194 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005195
5196 // Try to fold constant and into select arguments.
5197 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005198 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005199 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005200 if (isa<PHINode>(Op0))
5201 if (Instruction *NV = FoldOpIntoPhi(I))
5202 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005203 }
5204
Dan Gohman186a6362009-08-12 16:04:34 +00005205 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005206 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005207 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005208
Dan Gohman186a6362009-08-12 16:04:34 +00005209 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005210 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005211 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005212
Chris Lattner318bf792007-03-18 22:51:34 +00005213
5214 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5215 if (Op1I) {
5216 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005217 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005218 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005219 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005220 I.swapOperands();
5221 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005222 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005223 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005224 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005225 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005226 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005227 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005228 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005229 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005230 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005231 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005232 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005233 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005234 std::swap(A, B);
5235 }
Chris Lattner318bf792007-03-18 22:51:34 +00005236 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005237 I.swapOperands(); // Simplified below.
5238 std::swap(Op0, Op1);
5239 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005240 }
Chris Lattner318bf792007-03-18 22:51:34 +00005241 }
5242
5243 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5244 if (Op0I) {
5245 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005246 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005247 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005248 if (A == Op1) // (B|A)^B == (A|B)^B
5249 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005250 if (B == Op1) // (A|B)^B == A & ~B
5251 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005252 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005253 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005254 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005255 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005256 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005257 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005258 if (A == Op1) // (A&B)^A -> (B&A)^A
5259 std::swap(A, B);
5260 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005261 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005262 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005263 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005264 }
Chris Lattner318bf792007-03-18 22:51:34 +00005265 }
5266
5267 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5268 if (Op0I && Op1I && Op0I->isShift() &&
5269 Op0I->getOpcode() == Op1I->getOpcode() &&
5270 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5271 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005272 Value *NewOp =
5273 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5274 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005275 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005276 Op1I->getOperand(1));
5277 }
5278
5279 if (Op0I && Op1I) {
5280 Value *A, *B, *C, *D;
5281 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005282 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5283 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005284 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005285 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005286 }
5287 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005288 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5289 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005290 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005291 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005292 }
5293
5294 // (A & B)^(C & D)
5295 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005296 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5297 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005298 // (X & Y)^(X & Y) -> (Y^Z) & X
5299 Value *X = 0, *Y = 0, *Z = 0;
5300 if (A == C)
5301 X = A, Y = B, Z = D;
5302 else if (A == D)
5303 X = A, Y = B, Z = C;
5304 else if (B == C)
5305 X = B, Y = A, Z = D;
5306 else if (B == D)
5307 X = B, Y = A, Z = C;
5308
5309 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005310 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005311 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005312 }
5313 }
5314 }
5315
Reid Spencere4d87aa2006-12-23 06:05:41 +00005316 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5317 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005318 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005319 return R;
5320
Chris Lattner6fc205f2006-05-05 06:39:07 +00005321 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005322 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005323 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005324 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5325 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005326 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005327 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005328 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5329 I.getType(), TD) &&
5330 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5331 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005332 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5333 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005334 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005335 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005336 }
Chris Lattner99c65742007-10-24 05:38:08 +00005337 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005338
Chris Lattner7e708292002-06-25 16:13:24 +00005339 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005340}
5341
Owen Andersond672ecb2009-07-03 00:17:18 +00005342static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005343 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005344 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005345}
Chris Lattnera96879a2004-09-29 17:40:11 +00005346
Dan Gohman6de29f82009-06-15 22:12:54 +00005347static bool HasAddOverflow(ConstantInt *Result,
5348 ConstantInt *In1, ConstantInt *In2,
5349 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005350 if (IsSigned)
5351 if (In2->getValue().isNegative())
5352 return Result->getValue().sgt(In1->getValue());
5353 else
5354 return Result->getValue().slt(In1->getValue());
5355 else
5356 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005357}
5358
Dan Gohman6de29f82009-06-15 22:12:54 +00005359/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005360/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005361static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005362 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005363 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005364 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005365
Dan Gohman6de29f82009-06-15 22:12:54 +00005366 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5367 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005368 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005369 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5370 ExtractElement(In1, Idx, Context),
5371 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005372 IsSigned))
5373 return true;
5374 }
5375 return false;
5376 }
5377
5378 return HasAddOverflow(cast<ConstantInt>(Result),
5379 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5380 IsSigned);
5381}
5382
5383static bool HasSubOverflow(ConstantInt *Result,
5384 ConstantInt *In1, ConstantInt *In2,
5385 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005386 if (IsSigned)
5387 if (In2->getValue().isNegative())
5388 return Result->getValue().slt(In1->getValue());
5389 else
5390 return Result->getValue().sgt(In1->getValue());
5391 else
5392 return Result->getValue().ugt(In1->getValue());
5393}
5394
Dan Gohman6de29f82009-06-15 22:12:54 +00005395/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5396/// overflowed for this type.
5397static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005398 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005399 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005400 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005401
5402 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5403 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005404 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005405 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5406 ExtractElement(In1, Idx, Context),
5407 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005408 IsSigned))
5409 return true;
5410 }
5411 return false;
5412 }
5413
5414 return HasSubOverflow(cast<ConstantInt>(Result),
5415 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5416 IsSigned);
5417}
5418
Chris Lattner574da9b2005-01-13 20:14:25 +00005419/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5420/// code necessary to compute the offset from the base pointer (without adding
5421/// in the base pointer). Return the result as a signed integer of intptr size.
5422static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005423 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005424 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005425 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005426 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005427
5428 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005429 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005430 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005431
Gabor Greif177dd3f2008-06-12 21:37:33 +00005432 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5433 ++i, ++GTI) {
5434 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005435 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005436 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5437 if (OpC->isZero()) continue;
5438
5439 // Handle a struct index, which adds its field offset to the pointer.
5440 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5441 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5442
Chris Lattner74381062009-08-30 07:44:24 +00005443 Result = IC.Builder->CreateAdd(Result,
5444 ConstantInt::get(IntPtrTy, Size),
5445 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005446 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005447 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005448
Owen Andersoneed707b2009-07-24 23:12:02 +00005449 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005450 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005451 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5452 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005453 // Emit an add instruction.
5454 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005455 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005456 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005457 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005458 if (Op->getType() != IntPtrTy)
5459 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005460 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005461 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005462 // We'll let instcombine(mul) convert this to a shl if possible.
5463 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005464 }
5465
5466 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005467 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005468 }
5469 return Result;
5470}
5471
Chris Lattner10c0d912008-04-22 02:53:33 +00005472
Dan Gohman8f080f02009-07-17 22:16:21 +00005473/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5474/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5475/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5476/// be complex, and scales are involved. The above expression would also be
5477/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5478/// This later form is less amenable to optimization though, and we are allowed
5479/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005480///
5481/// If we can't emit an optimized form for this expression, this returns null.
5482///
5483static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5484 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005485 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005486 gep_type_iterator GTI = gep_type_begin(GEP);
5487
5488 // Check to see if this gep only has a single variable index. If so, and if
5489 // any constant indices are a multiple of its scale, then we can compute this
5490 // in terms of the scale of the variable index. For example, if the GEP
5491 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5492 // because the expression will cross zero at the same point.
5493 unsigned i, e = GEP->getNumOperands();
5494 int64_t Offset = 0;
5495 for (i = 1; i != e; ++i, ++GTI) {
5496 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5497 // Compute the aggregate offset of constant indices.
5498 if (CI->isZero()) continue;
5499
5500 // Handle a struct index, which adds its field offset to the pointer.
5501 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5502 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5503 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005504 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005505 Offset += Size*CI->getSExtValue();
5506 }
5507 } else {
5508 // Found our variable index.
5509 break;
5510 }
5511 }
5512
5513 // If there are no variable indices, we must have a constant offset, just
5514 // evaluate it the general way.
5515 if (i == e) return 0;
5516
5517 Value *VariableIdx = GEP->getOperand(i);
5518 // Determine the scale factor of the variable element. For example, this is
5519 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005520 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005521
5522 // Verify that there are no other variable indices. If so, emit the hard way.
5523 for (++i, ++GTI; i != e; ++i, ++GTI) {
5524 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5525 if (!CI) return 0;
5526
5527 // Compute the aggregate offset of constant indices.
5528 if (CI->isZero()) continue;
5529
5530 // Handle a struct index, which adds its field offset to the pointer.
5531 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5532 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5533 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005534 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005535 Offset += Size*CI->getSExtValue();
5536 }
5537 }
5538
5539 // Okay, we know we have a single variable index, which must be a
5540 // pointer/array/vector index. If there is no offset, life is simple, return
5541 // the index.
5542 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5543 if (Offset == 0) {
5544 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5545 // we don't need to bother extending: the extension won't affect where the
5546 // computation crosses zero.
5547 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005548 VariableIdx = new TruncInst(VariableIdx,
5549 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005550 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005551 return VariableIdx;
5552 }
5553
5554 // Otherwise, there is an index. The computation we will do will be modulo
5555 // the pointer size, so get it.
5556 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5557
5558 Offset &= PtrSizeMask;
5559 VariableScale &= PtrSizeMask;
5560
5561 // To do this transformation, any constant index must be a multiple of the
5562 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5563 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5564 // multiple of the variable scale.
5565 int64_t NewOffs = Offset / (int64_t)VariableScale;
5566 if (Offset != NewOffs*(int64_t)VariableScale)
5567 return 0;
5568
5569 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005570 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005571 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005572 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005573 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005574 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005575 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005576 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005577}
5578
5579
Reid Spencere4d87aa2006-12-23 06:05:41 +00005580/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005581/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005582Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005583 ICmpInst::Predicate Cond,
5584 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005585 // Look through bitcasts.
5586 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5587 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005588
Chris Lattner574da9b2005-01-13 20:14:25 +00005589 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005590 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005591 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005592 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005593 // know pointers can't overflow since the gep is inbounds. See if we can
5594 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005595 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5596
5597 // If not, synthesize the offset the hard way.
5598 if (Offset == 0)
5599 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005600 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005601 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005602 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005603 // If the base pointers are different, but the indices are the same, just
5604 // compare the base pointer.
5605 if (PtrBase != GEPRHS->getOperand(0)) {
5606 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005607 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005608 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005609 if (IndicesTheSame)
5610 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5611 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5612 IndicesTheSame = false;
5613 break;
5614 }
5615
5616 // If all indices are the same, just compare the base pointers.
5617 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005618 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005619 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005620
5621 // Otherwise, the base pointers are different and the indices are
5622 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005623 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005624 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005625
Chris Lattnere9d782b2005-01-13 22:25:21 +00005626 // If one of the GEPs has all zero indices, recurse.
5627 bool AllZeros = true;
5628 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5629 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5630 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5631 AllZeros = false;
5632 break;
5633 }
5634 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005635 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5636 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005637
5638 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005639 AllZeros = true;
5640 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5641 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5642 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5643 AllZeros = false;
5644 break;
5645 }
5646 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005647 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005648
Chris Lattner4401c9c2005-01-14 00:20:05 +00005649 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5650 // If the GEPs only differ by one index, compare it.
5651 unsigned NumDifferences = 0; // Keep track of # differences.
5652 unsigned DiffOperand = 0; // The operand that differs.
5653 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5654 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005655 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5656 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005657 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005658 NumDifferences = 2;
5659 break;
5660 } else {
5661 if (NumDifferences++) break;
5662 DiffOperand = i;
5663 }
5664 }
5665
5666 if (NumDifferences == 0) // SAME GEP?
5667 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005668 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005669 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005670
Chris Lattner4401c9c2005-01-14 00:20:05 +00005671 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005672 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5673 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005674 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005675 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005676 }
5677 }
5678
Reid Spencere4d87aa2006-12-23 06:05:41 +00005679 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005680 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005681 if (TD &&
5682 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005683 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5684 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5685 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5686 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005687 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005688 }
5689 }
5690 return 0;
5691}
5692
Chris Lattnera5406232008-05-19 20:18:56 +00005693/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5694///
5695Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5696 Instruction *LHSI,
5697 Constant *RHSC) {
5698 if (!isa<ConstantFP>(RHSC)) return 0;
5699 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5700
5701 // Get the width of the mantissa. We don't want to hack on conversions that
5702 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005703 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005704 if (MantissaWidth == -1) return 0; // Unknown.
5705
5706 // Check to see that the input is converted from an integer type that is small
5707 // enough that preserves all bits. TODO: check here for "known" sign bits.
5708 // 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 +00005709 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005710
5711 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005712 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5713 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005714 ++InputSize;
5715
5716 // If the conversion would lose info, don't hack on this.
5717 if ((int)InputSize > MantissaWidth)
5718 return 0;
5719
5720 // Otherwise, we can potentially simplify the comparison. We know that it
5721 // will always come through as an integer value and we know the constant is
5722 // not a NAN (it would have been previously simplified).
5723 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5724
5725 ICmpInst::Predicate Pred;
5726 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005727 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005728 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005729 case FCmpInst::FCMP_OEQ:
5730 Pred = ICmpInst::ICMP_EQ;
5731 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005732 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005733 case FCmpInst::FCMP_OGT:
5734 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5735 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005736 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005737 case FCmpInst::FCMP_OGE:
5738 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5739 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005740 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005741 case FCmpInst::FCMP_OLT:
5742 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5743 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005744 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005745 case FCmpInst::FCMP_OLE:
5746 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5747 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005748 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005749 case FCmpInst::FCMP_ONE:
5750 Pred = ICmpInst::ICMP_NE;
5751 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005752 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005753 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005754 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005755 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005756 }
5757
5758 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5759
5760 // Now we know that the APFloat is a normal number, zero or inf.
5761
Chris Lattner85162782008-05-20 03:50:52 +00005762 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005763 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005764 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005765
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005766 if (!LHSUnsigned) {
5767 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5768 // and large values.
5769 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5770 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5771 APFloat::rmNearestTiesToEven);
5772 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5773 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5774 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005775 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5776 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005777 }
5778 } else {
5779 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5780 // +INF and large values.
5781 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5782 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5783 APFloat::rmNearestTiesToEven);
5784 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5785 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5786 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005787 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5788 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005789 }
Chris Lattnera5406232008-05-19 20:18:56 +00005790 }
5791
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005792 if (!LHSUnsigned) {
5793 // See if the RHS value is < SignedMin.
5794 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5795 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5796 APFloat::rmNearestTiesToEven);
5797 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5798 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5799 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005800 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5801 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005802 }
Chris Lattnera5406232008-05-19 20:18:56 +00005803 }
5804
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005805 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5806 // [0, UMAX], but it may still be fractional. See if it is fractional by
5807 // casting the FP value to the integer value and back, checking for equality.
5808 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005809 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005810 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5811 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005812 if (!RHS.isZero()) {
5813 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005814 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5815 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005816 if (!Equal) {
5817 // If we had a comparison against a fractional value, we have to adjust
5818 // the compare predicate and sometimes the value. RHSC is rounded towards
5819 // zero at this point.
5820 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005821 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005822 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005823 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005824 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005825 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005826 case ICmpInst::ICMP_ULE:
5827 // (float)int <= 4.4 --> int <= 4
5828 // (float)int <= -4.4 --> false
5829 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005830 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005831 break;
5832 case ICmpInst::ICMP_SLE:
5833 // (float)int <= 4.4 --> int <= 4
5834 // (float)int <= -4.4 --> int < -4
5835 if (RHS.isNegative())
5836 Pred = ICmpInst::ICMP_SLT;
5837 break;
5838 case ICmpInst::ICMP_ULT:
5839 // (float)int < -4.4 --> false
5840 // (float)int < 4.4 --> int <= 4
5841 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005842 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005843 Pred = ICmpInst::ICMP_ULE;
5844 break;
5845 case ICmpInst::ICMP_SLT:
5846 // (float)int < -4.4 --> int < -4
5847 // (float)int < 4.4 --> int <= 4
5848 if (!RHS.isNegative())
5849 Pred = ICmpInst::ICMP_SLE;
5850 break;
5851 case ICmpInst::ICMP_UGT:
5852 // (float)int > 4.4 --> int > 4
5853 // (float)int > -4.4 --> true
5854 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005855 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005856 break;
5857 case ICmpInst::ICMP_SGT:
5858 // (float)int > 4.4 --> int > 4
5859 // (float)int > -4.4 --> int >= -4
5860 if (RHS.isNegative())
5861 Pred = ICmpInst::ICMP_SGE;
5862 break;
5863 case ICmpInst::ICMP_UGE:
5864 // (float)int >= -4.4 --> true
5865 // (float)int >= 4.4 --> int > 4
5866 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005867 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005868 Pred = ICmpInst::ICMP_UGT;
5869 break;
5870 case ICmpInst::ICMP_SGE:
5871 // (float)int >= -4.4 --> int >= -4
5872 // (float)int >= 4.4 --> int > 4
5873 if (!RHS.isNegative())
5874 Pred = ICmpInst::ICMP_SGT;
5875 break;
5876 }
Chris Lattnera5406232008-05-19 20:18:56 +00005877 }
5878 }
5879
5880 // Lower this FP comparison into an appropriate integer version of the
5881 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005882 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005883}
5884
Reid Spencere4d87aa2006-12-23 06:05:41 +00005885Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5886 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005887 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005888
Chris Lattner58e97462007-01-14 19:42:17 +00005889 // Fold trivial predicates.
5890 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005891 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005892 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005893 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005894
5895 // Simplify 'fcmp pred X, X'
5896 if (Op0 == Op1) {
5897 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005898 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005899 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5900 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5901 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner9e17b632009-09-02 05:12:37 +00005902 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005903 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5904 case FCmpInst::FCMP_OLT: // True if ordered and less than
5905 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner9e17b632009-09-02 05:12:37 +00005906 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005907
5908 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5909 case FCmpInst::FCMP_ULT: // True if unordered or less than
5910 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5911 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5912 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5913 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005914 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005915 return &I;
5916
5917 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5918 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5919 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5920 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5921 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5922 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005923 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005924 return &I;
5925 }
5926 }
5927
Reid Spencere4d87aa2006-12-23 06:05:41 +00005928 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005929 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005930
Reid Spencere4d87aa2006-12-23 06:05:41 +00005931 // Handle fcmp with constant RHS
5932 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005933 // If the constant is a nan, see if we can fold the comparison based on it.
5934 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5935 if (CFP->getValueAPF().isNaN()) {
5936 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005937 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005938 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5939 "Comparison must be either ordered or unordered!");
5940 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005941 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005942 }
5943 }
5944
Reid Spencere4d87aa2006-12-23 06:05:41 +00005945 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5946 switch (LHSI->getOpcode()) {
5947 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005948 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5949 // block. If in the same block, we're encouraging jump threading. If
5950 // not, we are just pessimizing the code by making an i1 phi.
5951 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00005952 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005953 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005954 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005955 case Instruction::SIToFP:
5956 case Instruction::UIToFP:
5957 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5958 return NV;
5959 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005960 case Instruction::Select:
5961 // If either operand of the select is a constant, we can fold the
5962 // comparison into the select arms, which will cause one to be
5963 // constant folded and the select turned into a bitwise or.
5964 Value *Op1 = 0, *Op2 = 0;
5965 if (LHSI->hasOneUse()) {
5966 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5967 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005968 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005969 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005970 Op2 = Builder->CreateFCmp(I.getPredicate(),
5971 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005972 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5973 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005974 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005975 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005976 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5977 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005978 }
5979 }
5980
5981 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005982 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005983 break;
5984 }
5985 }
5986
5987 return Changed ? &I : 0;
5988}
5989
5990Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5991 bool Changed = SimplifyCompare(I);
5992 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5993 const Type *Ty = Op0->getType();
5994
5995 // icmp X, X
5996 if (Op0 == Op1)
Chris Lattner9e17b632009-09-02 05:12:37 +00005997 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005998 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005999
6000 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00006001 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006002
Reid Spencere4d87aa2006-12-23 06:05:41 +00006003 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00006004 // addresses never equal each other! We already know that Op0 != Op1.
Chris Lattnerbbc33852009-10-05 02:47:47 +00006005 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
Misha Brukmanfd939082005-04-21 23:48:37 +00006006 isa<ConstantPointerNull>(Op0)) &&
Chris Lattnerbbc33852009-10-05 02:47:47 +00006007 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00006008 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00006009 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006010 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00006011
Reid Spencere4d87aa2006-12-23 06:05:41 +00006012 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006013 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006014 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006015 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006016 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006017 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006018 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006019 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006020 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006021 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006022
Reid Spencere4d87aa2006-12-23 06:05:41 +00006023 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006024 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006025 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006026 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006027 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006028 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006029 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006030 case ICmpInst::ICMP_SGT:
6031 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006032 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006033 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006034 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006035 return BinaryOperator::CreateAnd(Not, Op0);
6036 }
6037 case ICmpInst::ICMP_UGE:
6038 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6039 // FALL THROUGH
6040 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006041 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006042 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006043 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006044 case ICmpInst::ICMP_SGE:
6045 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6046 // FALL THROUGH
6047 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006048 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006049 return BinaryOperator::CreateOr(Not, Op0);
6050 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006051 }
Chris Lattner8b170942002-08-09 23:47:40 +00006052 }
6053
Dan Gohman1c8491e2009-04-25 17:12:48 +00006054 unsigned BitWidth = 0;
6055 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006056 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6057 else if (Ty->isIntOrIntVector())
6058 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006059
6060 bool isSignBit = false;
6061
Dan Gohman81b28ce2008-09-16 18:46:06 +00006062 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006063 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006064 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006065
Chris Lattnerb6566012008-01-05 01:18:20 +00006066 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6067 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006068 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006069 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006070 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006071 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006072
Dan Gohman81b28ce2008-09-16 18:46:06 +00006073 // If we have an icmp le or icmp ge instruction, turn it into the
6074 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6075 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006076 switch (I.getPredicate()) {
6077 default: break;
6078 case ICmpInst::ICMP_ULE:
6079 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006080 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006081 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006082 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006083 case ICmpInst::ICMP_SLE:
6084 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006085 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006086 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006087 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006088 case ICmpInst::ICMP_UGE:
6089 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006090 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006091 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006092 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006093 case ICmpInst::ICMP_SGE:
6094 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006095 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006096 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006097 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006098 }
6099
Chris Lattner183661e2008-07-11 05:40:05 +00006100 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006101 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006102 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006103 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6104 }
6105
6106 // See if we can fold the comparison based on range information we can get
6107 // by checking whether bits are known to be zero or one in the input.
6108 if (BitWidth != 0) {
6109 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6110 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6111
6112 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006113 isSignBit ? APInt::getSignBit(BitWidth)
6114 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006115 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006116 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006117 if (SimplifyDemandedBits(I.getOperandUse(1),
6118 APInt::getAllOnesValue(BitWidth),
6119 Op1KnownZero, Op1KnownOne, 0))
6120 return &I;
6121
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006122 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006123 // in. Compute the Min, Max and RHS values based on the known bits. For the
6124 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006125 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6126 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006127 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006128 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6129 Op0Min, Op0Max);
6130 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6131 Op1Min, Op1Max);
6132 } else {
6133 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6134 Op0Min, Op0Max);
6135 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6136 Op1Min, Op1Max);
6137 }
6138
Chris Lattner183661e2008-07-11 05:40:05 +00006139 // If Min and Max are known to be the same, then SimplifyDemandedBits
6140 // figured out that the LHS is a constant. Just constant fold this now so
6141 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006142 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006143 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006144 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006146 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006147 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006148
Chris Lattner183661e2008-07-11 05:40:05 +00006149 // Based on the range information we know about the LHS, see if we can
6150 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006151 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006152 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006153 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006154 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006155 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006156 break;
6157 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006158 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006159 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006160 break;
6161 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006162 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006163 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006165 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006166 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006167 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006168 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6169 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006170 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006171 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006172
6173 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6174 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006175 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006176 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006177 }
Chris Lattner84dff672008-07-11 05:08:55 +00006178 break;
6179 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006180 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006181 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006182 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006183 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006184
6185 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006186 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006187 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6188 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006189 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006190 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006191
6192 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6193 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006194 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006195 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006196 }
Chris Lattner84dff672008-07-11 05:08:55 +00006197 break;
6198 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006199 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006200 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006201 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006202 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006203 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006204 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006205 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6206 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006207 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006208 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006209 }
Chris Lattner84dff672008-07-11 05:08:55 +00006210 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006211 case ICmpInst::ICMP_SGT:
6212 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006213 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006214 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006215 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006216
6217 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006218 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006219 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6220 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006221 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006222 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006223 }
6224 break;
6225 case ICmpInst::ICMP_SGE:
6226 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6227 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006228 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006229 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006230 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006231 break;
6232 case ICmpInst::ICMP_SLE:
6233 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6234 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006235 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006236 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006237 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006238 break;
6239 case ICmpInst::ICMP_UGE:
6240 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6241 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006242 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006243 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006244 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006245 break;
6246 case ICmpInst::ICMP_ULE:
6247 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6248 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006249 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006250 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006251 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006252 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006253 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006254
6255 // Turn a signed comparison into an unsigned one if both operands
6256 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006257 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006258 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6259 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006260 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006261 }
6262
6263 // Test if the ICmpInst instruction is used exclusively by a select as
6264 // part of a minimum or maximum operation. If so, refrain from doing
6265 // any other folding. This helps out other analyses which understand
6266 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6267 // and CodeGen. And in this case, at least one of the comparison
6268 // operands has at least one user besides the compare (the select),
6269 // which would often largely negate the benefit of folding anyway.
6270 if (I.hasOneUse())
6271 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6272 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6273 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6274 return 0;
6275
6276 // See if we are doing a comparison between a constant and an instruction that
6277 // can be folded into the comparison.
6278 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006279 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006280 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006281 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006282 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006283 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6284 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006285 }
6286
Chris Lattner01deb9d2007-04-03 17:43:25 +00006287 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006288 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6289 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6290 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006291 case Instruction::GetElementPtr:
6292 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006293 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006294 bool isAllZeros = true;
6295 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6296 if (!isa<Constant>(LHSI->getOperand(i)) ||
6297 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6298 isAllZeros = false;
6299 break;
6300 }
6301 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006302 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006303 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006304 }
6305 break;
6306
Chris Lattner6970b662005-04-23 15:31:55 +00006307 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006308 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006309 // block. If in the same block, we're encouraging jump threading. If
6310 // not, we are just pessimizing the code by making an i1 phi.
6311 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006312 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006313 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006314 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006315 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006316 // If either operand of the select is a constant, we can fold the
6317 // comparison into the select arms, which will cause one to be
6318 // constant folded and the select turned into a bitwise or.
6319 Value *Op1 = 0, *Op2 = 0;
6320 if (LHSI->hasOneUse()) {
6321 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6322 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006323 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006324 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006325 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6326 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006327 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6328 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006329 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006330 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006331 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6332 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006333 }
6334 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006335
Chris Lattner6970b662005-04-23 15:31:55 +00006336 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006337 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006338 break;
6339 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006340 case Instruction::Call:
6341 // If we have (malloc != null), and if the malloc has a single use, we
6342 // can assume it is successful and remove the malloc.
6343 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6344 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006345 // Need to explicitly erase malloc call here, instead of adding it to
6346 // Worklist, because it won't get DCE'd from the Worklist since
6347 // isInstructionTriviallyDead() returns false for function calls.
6348 // It is OK to replace LHSI/MallocCall with Undef because the
6349 // instruction that uses it will be erased via Worklist.
6350 if (extractMallocCall(LHSI)) {
6351 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6352 EraseInstFromFunction(*LHSI);
6353 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006354 ConstantInt::get(Type::getInt1Ty(*Context),
6355 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006356 }
6357 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6358 if (MallocCall->hasOneUse()) {
6359 MallocCall->replaceAllUsesWith(
6360 UndefValue::get(MallocCall->getType()));
6361 EraseInstFromFunction(*MallocCall);
6362 Worklist.Add(LHSI); // The malloc's bitcast use.
6363 return ReplaceInstUsesWith(I,
6364 ConstantInt::get(Type::getInt1Ty(*Context),
6365 !I.isTrueWhenEqual()));
6366 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006367 }
6368 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006369 }
Chris Lattner6970b662005-04-23 15:31:55 +00006370 }
6371
Reid Spencere4d87aa2006-12-23 06:05:41 +00006372 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006373 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006374 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006375 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006376 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006377 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6378 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006379 return NI;
6380
Reid Spencere4d87aa2006-12-23 06:05:41 +00006381 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006382 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6383 // now.
6384 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6385 if (isa<PointerType>(Op0->getType()) &&
6386 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006387 // We keep moving the cast from the left operand over to the right
6388 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006389 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006390
Chris Lattner57d86372007-01-06 01:45:59 +00006391 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6392 // so eliminate it as well.
6393 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6394 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006395
Chris Lattnerde90b762003-11-03 04:25:02 +00006396 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006397 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006398 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006399 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006400 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006401 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006402 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006403 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006404 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006405 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006406 }
Chris Lattner57d86372007-01-06 01:45:59 +00006407 }
6408
6409 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006410 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006411 // This comes up when you have code like
6412 // int X = A < B;
6413 // if (X) ...
6414 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006415 // with a constant or another cast from the same type.
6416 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006417 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006418 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006419 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006420
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006421 // See if it's the same type of instruction on the left and right.
6422 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6423 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006424 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006425 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006426 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006427 default: break;
6428 case Instruction::Add:
6429 case Instruction::Sub:
6430 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006431 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006432 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006433 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006434 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6435 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6436 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006437 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006438 ? I.getUnsignedPredicate()
6439 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006440 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006441 Op1I->getOperand(0));
6442 }
6443
6444 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006445 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006446 ? I.getUnsignedPredicate()
6447 : I.getSignedPredicate();
6448 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006449 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006450 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006451 }
6452 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006453 break;
6454 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006455 if (!I.isEquality())
6456 break;
6457
Nick Lewycky5d52c452008-08-21 05:56:10 +00006458 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6459 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6460 // Mask = -1 >> count-trailing-zeros(Cst).
6461 if (!CI->isZero() && !CI->isOne()) {
6462 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006463 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006464 APInt::getLowBitsSet(AP.getBitWidth(),
6465 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006466 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006467 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6468 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006469 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006470 }
6471 }
6472 break;
6473 }
6474 }
6475 }
6476 }
6477
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006478 // ~x < ~y --> y < x
6479 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006480 if (match(Op0, m_Not(m_Value(A))) &&
6481 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006482 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006483 }
6484
Chris Lattner65b72ba2006-09-18 04:22:48 +00006485 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006486 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006487
6488 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006489 if (match(Op0, m_Neg(m_Value(A))) &&
6490 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006491 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006492
Dan Gohman4ae51262009-08-12 16:23:25 +00006493 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006494 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6495 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006496 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006497 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006498 }
6499
Dan Gohman4ae51262009-08-12 16:23:25 +00006500 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006501 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006502 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006503 if (match(B, m_ConstantInt(C1)) &&
6504 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006505 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006506 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006507 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6508 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006509 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006510
6511 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006512 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6513 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6514 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6515 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006516 }
6517 }
6518
Dan Gohman4ae51262009-08-12 16:23:25 +00006519 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006520 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006521 // A == (A^B) -> B == 0
6522 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006523 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006524 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006525 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006526
6527 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006528 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006529 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006530 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006531
6532 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006533 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006534 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006535 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006536
Chris Lattner9c2328e2006-11-14 06:06:06 +00006537 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6538 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006539 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6540 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006541 Value *X = 0, *Y = 0, *Z = 0;
6542
6543 if (A == C) {
6544 X = B; Y = D; Z = A;
6545 } else if (A == D) {
6546 X = B; Y = C; Z = A;
6547 } else if (B == C) {
6548 X = A; Y = D; Z = B;
6549 } else if (B == D) {
6550 X = A; Y = C; Z = B;
6551 }
6552
6553 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006554 Op1 = Builder->CreateXor(X, Y, "tmp");
6555 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006556 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006557 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006558 return &I;
6559 }
6560 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006561 }
Chris Lattner7e708292002-06-25 16:13:24 +00006562 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006563}
6564
Chris Lattner562ef782007-06-20 23:46:26 +00006565
6566/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6567/// and CmpRHS are both known to be integer constants.
6568Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6569 ConstantInt *DivRHS) {
6570 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6571 const APInt &CmpRHSV = CmpRHS->getValue();
6572
6573 // FIXME: If the operand types don't match the type of the divide
6574 // then don't attempt this transform. The code below doesn't have the
6575 // logic to deal with a signed divide and an unsigned compare (and
6576 // vice versa). This is because (x /s C1) <s C2 produces different
6577 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6578 // (x /u C1) <u C2. Simply casting the operands and result won't
6579 // work. :( The if statement below tests that condition and bails
6580 // if it finds it.
6581 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00006582 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00006583 return 0;
6584 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006585 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006586 if (DivIsSigned && DivRHS->isAllOnesValue())
6587 return 0; // The overflow computation also screws up here
6588 if (DivRHS->isOne())
6589 return 0; // Not worth bothering, and eliminates some funny cases
6590 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006591
6592 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6593 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6594 // C2 (CI). By solving for X we can turn this into a range check
6595 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006596 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006597
6598 // Determine if the product overflows by seeing if the product is
6599 // not equal to the divide. Make sure we do the same kind of divide
6600 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006601 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6602 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006603
6604 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006605 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006606
Chris Lattner1dbfd482007-06-21 18:11:19 +00006607 // Figure out the interval that is being checked. For example, a comparison
6608 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6609 // Compute this interval based on the constants involved and the signedness of
6610 // the compare/divide. This computes a half-open interval, keeping track of
6611 // whether either value in the interval overflows. After analysis each
6612 // overflow variable is set to 0 if it's corresponding bound variable is valid
6613 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6614 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006615 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006616
Chris Lattner562ef782007-06-20 23:46:26 +00006617 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006618 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006619 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006620 HiOverflow = LoOverflow = ProdOV;
6621 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006622 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006623 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006624 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006625 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006626 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006627 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006628 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006629 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6630 HiOverflow = LoOverflow = ProdOV;
6631 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006632 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006633 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006634 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006635 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006636 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6637 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006638 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006639 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006640 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006641 true) ? -1 : 0;
6642 }
Chris Lattner562ef782007-06-20 23:46:26 +00006643 }
Dan Gohman76491272008-02-13 22:09:18 +00006644 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006645 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006646 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006647 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006648 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006649 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6650 HiOverflow = 1; // [INTMIN+1, overflow)
6651 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6652 }
Dan Gohman76491272008-02-13 22:09:18 +00006653 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006654 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006655 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006656 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006657 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006658 LoOverflow = AddWithOverflow(LoBound, HiBound,
6659 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006660 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006661 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6662 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006663 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006664 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006665 }
6666
Chris Lattner1dbfd482007-06-21 18:11:19 +00006667 // Dividing by a negative swaps the condition. LT <-> GT
6668 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006669 }
6670
6671 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006672 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006673 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006674 case ICmpInst::ICMP_EQ:
6675 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006676 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006677 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006678 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006679 ICmpInst::ICMP_UGE, X, LoBound);
6680 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006681 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006682 ICmpInst::ICMP_ULT, X, HiBound);
6683 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006684 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006685 case ICmpInst::ICMP_NE:
6686 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006687 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006688 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006689 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006690 ICmpInst::ICMP_ULT, X, LoBound);
6691 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006692 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006693 ICmpInst::ICMP_UGE, X, HiBound);
6694 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006695 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006696 case ICmpInst::ICMP_ULT:
6697 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006698 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006699 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006700 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006701 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006702 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006703 case ICmpInst::ICMP_UGT:
6704 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006705 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006706 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006707 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006708 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006709 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006710 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006711 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006712 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006713 }
6714}
6715
6716
Chris Lattner01deb9d2007-04-03 17:43:25 +00006717/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6718///
6719Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6720 Instruction *LHSI,
6721 ConstantInt *RHS) {
6722 const APInt &RHSV = RHS->getValue();
6723
6724 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006725 case Instruction::Trunc:
6726 if (ICI.isEquality() && LHSI->hasOneUse()) {
6727 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6728 // of the high bits truncated out of x are known.
6729 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6730 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6731 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6732 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6733 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6734
6735 // If all the high bits are known, we can do this xform.
6736 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6737 // Pull in the high bits from known-ones set.
6738 APInt NewRHS(RHS->getValue());
6739 NewRHS.zext(SrcBits);
6740 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006741 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006742 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006743 }
6744 }
6745 break;
6746
Duncan Sands0091bf22007-04-04 06:42:45 +00006747 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006748 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6749 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6750 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006751 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6752 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006753 Value *CompareVal = LHSI->getOperand(0);
6754
6755 // If the sign bit of the XorCST is not set, there is no change to
6756 // the operation, just stop using the Xor.
6757 if (!XorCST->getValue().isNegative()) {
6758 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006759 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006760 return &ICI;
6761 }
6762
6763 // Was the old condition true if the operand is positive?
6764 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6765
6766 // If so, the new one isn't.
6767 isTrueIfPositive ^= true;
6768
6769 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006770 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006771 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006772 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006773 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006774 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006775 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006776
6777 if (LHSI->hasOneUse()) {
6778 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6779 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6780 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006781 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006782 ? ICI.getUnsignedPredicate()
6783 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006784 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006785 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006786 }
6787
6788 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006789 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006790 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006791 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006792 ? ICI.getUnsignedPredicate()
6793 : ICI.getSignedPredicate();
6794 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006795 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006796 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006797 }
6798 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006799 }
6800 break;
6801 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6802 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6803 LHSI->getOperand(0)->hasOneUse()) {
6804 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6805
6806 // If the LHS is an AND of a truncating cast, we can widen the
6807 // and/compare to be the input width without changing the value
6808 // produced, eliminating a cast.
6809 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6810 // We can do this transformation if either the AND constant does not
6811 // have its sign bit set or if it is an equality comparison.
6812 // Extending a relational comparison when we're checking the sign
6813 // bit would not work.
6814 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006815 (ICI.isEquality() ||
6816 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006817 uint32_t BitWidth =
6818 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6819 APInt NewCST = AndCST->getValue();
6820 NewCST.zext(BitWidth);
6821 APInt NewCI = RHSV;
6822 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006823 Value *NewAnd =
6824 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006825 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006826 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006827 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006828 }
6829 }
6830
6831 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6832 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6833 // happens a LOT in code produced by the C front-end, for bitfield
6834 // access.
6835 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6836 if (Shift && !Shift->isShift())
6837 Shift = 0;
6838
6839 ConstantInt *ShAmt;
6840 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6841 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6842 const Type *AndTy = AndCST->getType(); // Type of the and.
6843
6844 // We can fold this as long as we can't shift unknown bits
6845 // into the mask. This can only happen with signed shift
6846 // rights, as they sign-extend.
6847 if (ShAmt) {
6848 bool CanFold = Shift->isLogicalShift();
6849 if (!CanFold) {
6850 // To test for the bad case of the signed shr, see if any
6851 // of the bits shifted in could be tested after the mask.
6852 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6853 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6854
6855 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6856 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6857 AndCST->getValue()) == 0)
6858 CanFold = true;
6859 }
6860
6861 if (CanFold) {
6862 Constant *NewCst;
6863 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006864 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006865 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006866 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006867
6868 // Check to see if we are shifting out any of the bits being
6869 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006870 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006871 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006872 // If we shifted bits out, the fold is not going to work out.
6873 // As a special case, check to see if this means that the
6874 // result is always true or false now.
6875 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006876 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006877 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006878 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006879 } else {
6880 ICI.setOperand(1, NewCst);
6881 Constant *NewAndCST;
6882 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006883 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006884 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006885 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006886 LHSI->setOperand(1, NewAndCST);
6887 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006888 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006889 return &ICI;
6890 }
6891 }
6892 }
6893
6894 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6895 // preferable because it allows the C<<Y expression to be hoisted out
6896 // of a loop if Y is invariant and X is not.
6897 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006898 ICI.isEquality() && !Shift->isArithmeticShift() &&
6899 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006900 // Compute C << Y.
6901 Value *NS;
6902 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006903 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006904 } else {
6905 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006906 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006907 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006908
6909 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006910 Value *NewAnd =
6911 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006912
6913 ICI.setOperand(0, NewAnd);
6914 return &ICI;
6915 }
6916 }
6917 break;
6918
Chris Lattnera0141b92007-07-15 20:42:37 +00006919 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6920 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6921 if (!ShAmt) break;
6922
6923 uint32_t TypeBits = RHSV.getBitWidth();
6924
6925 // Check that the shift amount is in range. If not, don't perform
6926 // undefined shifts. When the shift is visited it will be
6927 // simplified.
6928 if (ShAmt->uge(TypeBits))
6929 break;
6930
6931 if (ICI.isEquality()) {
6932 // If we are comparing against bits always shifted out, the
6933 // comparison cannot succeed.
6934 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006935 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006936 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006937 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6938 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006939 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006940 return ReplaceInstUsesWith(ICI, Cst);
6941 }
6942
6943 if (LHSI->hasOneUse()) {
6944 // Otherwise strength reduce the shift into an and.
6945 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6946 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006947 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006948 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006949
Chris Lattner74381062009-08-30 07:44:24 +00006950 Value *And =
6951 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006952 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006953 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006954 }
6955 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006956
6957 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6958 bool TrueIfSigned = false;
6959 if (LHSI->hasOneUse() &&
6960 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6961 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006962 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006963 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006964 Value *And =
6965 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006966 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006967 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006968 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006969 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006970 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006971
6972 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006973 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006974 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006975 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006976 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006977
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006978 // Check that the shift amount is in range. If not, don't perform
6979 // undefined shifts. When the shift is visited it will be
6980 // simplified.
6981 uint32_t TypeBits = RHSV.getBitWidth();
6982 if (ShAmt->uge(TypeBits))
6983 break;
6984
6985 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006986
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006987 // If we are comparing against bits always shifted out, the
6988 // comparison cannot succeed.
6989 APInt Comp = RHSV << ShAmtVal;
6990 if (LHSI->getOpcode() == Instruction::LShr)
6991 Comp = Comp.lshr(ShAmtVal);
6992 else
6993 Comp = Comp.ashr(ShAmtVal);
6994
6995 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6996 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006997 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006998 return ReplaceInstUsesWith(ICI, Cst);
6999 }
7000
7001 // Otherwise, check to see if the bits shifted out are known to be zero.
7002 // If so, we can compare against the unshifted value:
7003 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007004 if (LHSI->hasOneUse() &&
7005 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007006 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007007 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007008 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007009 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007010
Evan Chengf30752c2008-04-23 00:38:06 +00007011 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007012 // Otherwise strength reduce the shift into an and.
7013 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007014 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007015
Chris Lattner74381062009-08-30 07:44:24 +00007016 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7017 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007018 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007019 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007020 }
7021 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007022 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007023
7024 case Instruction::SDiv:
7025 case Instruction::UDiv:
7026 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7027 // Fold this div into the comparison, producing a range check.
7028 // Determine, based on the divide type, what the range is being
7029 // checked. If there is an overflow on the low or high side, remember
7030 // it, otherwise compute the range [low, hi) bounding the new value.
7031 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007032 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7033 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7034 DivRHS))
7035 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007036 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007037
7038 case Instruction::Add:
7039 // Fold: icmp pred (add, X, C1), C2
7040
7041 if (!ICI.isEquality()) {
7042 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7043 if (!LHSC) break;
7044 const APInt &LHSV = LHSC->getValue();
7045
7046 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7047 .subtract(LHSV);
7048
Nick Lewycky4a134af2009-10-25 05:20:17 +00007049 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007050 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007051 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007052 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007053 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007054 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007055 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007056 }
7057 } else {
7058 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007059 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007060 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007061 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007062 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007063 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007064 }
7065 }
7066 }
7067 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007068 }
7069
7070 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7071 if (ICI.isEquality()) {
7072 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7073
7074 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7075 // the second operand is a constant, simplify a bit.
7076 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7077 switch (BO->getOpcode()) {
7078 case Instruction::SRem:
7079 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7080 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7081 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7082 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007083 Value *NewRem =
7084 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7085 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007086 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007087 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007088 }
7089 }
7090 break;
7091 case Instruction::Add:
7092 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7093 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7094 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007095 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007096 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007097 } else if (RHSV == 0) {
7098 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7099 // efficiently invertible, or if the add has just this one use.
7100 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7101
Dan Gohman186a6362009-08-12 16:04:34 +00007102 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007103 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007104 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007105 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007106 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007107 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007108 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007109 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007110 }
7111 }
7112 break;
7113 case Instruction::Xor:
7114 // For the xor case, we can xor two constants together, eliminating
7115 // the explicit xor.
7116 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007117 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007118 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007119
7120 // FALLTHROUGH
7121 case Instruction::Sub:
7122 // Replace (([sub|xor] A, B) != 0) with (A != B)
7123 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007124 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007125 BO->getOperand(1));
7126 break;
7127
7128 case Instruction::Or:
7129 // If bits are being or'd in that are not present in the constant we
7130 // are comparing against, then the comparison could never succeed!
7131 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007132 Constant *NotCI = ConstantExpr::getNot(RHS);
7133 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007134 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007135 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007136 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007137 }
7138 break;
7139
7140 case Instruction::And:
7141 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7142 // If bits are being compared against that are and'd out, then the
7143 // comparison can never succeed!
7144 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007145 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007146 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007147 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007148
7149 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7150 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007151 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007152 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007153 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007154
7155 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007156 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007157 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007158 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007159 ICmpInst::Predicate pred = isICMP_NE ?
7160 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007161 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007162 }
7163
7164 // ((X & ~7) == 0) --> X < 8
7165 if (RHSV == 0 && isHighOnes(BOC)) {
7166 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007167 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007168 ICmpInst::Predicate pred = isICMP_NE ?
7169 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007170 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007171 }
7172 }
7173 default: break;
7174 }
7175 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7176 // Handle icmp {eq|ne} <intrinsic>, intcst.
7177 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007178 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007179 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007180 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007181 return &ICI;
7182 }
7183 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007184 }
7185 return 0;
7186}
7187
7188/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7189/// We only handle extending casts so far.
7190///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007191Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7192 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007193 Value *LHSCIOp = LHSCI->getOperand(0);
7194 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007195 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007196 Value *RHSCIOp;
7197
Chris Lattner8c756c12007-05-05 22:41:33 +00007198 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7199 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007200 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7201 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007202 cast<IntegerType>(DestTy)->getBitWidth()) {
7203 Value *RHSOp = 0;
7204 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007205 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007206 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7207 RHSOp = RHSC->getOperand(0);
7208 // If the pointer types don't match, insert a bitcast.
7209 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007210 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007211 }
7212
7213 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007214 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007215 }
7216
7217 // The code below only handles extension cast instructions, so far.
7218 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007219 if (LHSCI->getOpcode() != Instruction::ZExt &&
7220 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007221 return 0;
7222
Reid Spencere4d87aa2006-12-23 06:05:41 +00007223 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007224 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007225
Reid Spencere4d87aa2006-12-23 06:05:41 +00007226 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007227 // Not an extension from the same type?
7228 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007229 if (RHSCIOp->getType() != LHSCIOp->getType())
7230 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007231
Nick Lewycky4189a532008-01-28 03:48:02 +00007232 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007233 // and the other is a zext), then we can't handle this.
7234 if (CI->getOpcode() != LHSCI->getOpcode())
7235 return 0;
7236
Nick Lewycky4189a532008-01-28 03:48:02 +00007237 // Deal with equality cases early.
7238 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007239 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007240
7241 // A signed comparison of sign extended values simplifies into a
7242 // signed comparison.
7243 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007244 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007245
7246 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007247 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007248 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007249
Reid Spencere4d87aa2006-12-23 06:05:41 +00007250 // If we aren't dealing with a constant on the RHS, exit early
7251 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7252 if (!CI)
7253 return 0;
7254
7255 // Compute the constant that would happen if we truncated to SrcTy then
7256 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007257 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7258 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007259 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007260
7261 // If the re-extended constant didn't change...
7262 if (Res2 == CI) {
7263 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7264 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007265 // %A = sext i16 %X to i32
7266 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007267 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007268 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007269 // because %A may have negative value.
7270 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007271 // However, we allow this when the compare is EQ/NE, because they are
7272 // signless.
7273 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007274 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007275 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007276 }
7277
7278 // The re-extended constant changed so the constant cannot be represented
7279 // in the shorter type. Consequently, we cannot emit a simple comparison.
7280
7281 // First, handle some easy cases. We know the result cannot be equal at this
7282 // point so handle the ICI.isEquality() cases
7283 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007284 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007285 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007286 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007287
7288 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7289 // should have been folded away previously and not enter in here.
7290 Value *Result;
7291 if (isSignedCmp) {
7292 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007293 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007294 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007295 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007296 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007297 } else {
7298 // We're performing an unsigned comparison.
7299 if (isSignedExt) {
7300 // We're performing an unsigned comp with a sign extended value.
7301 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007302 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007303 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007304 } else {
7305 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007306 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007307 }
7308 }
7309
7310 // Finally, return the value computed.
7311 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007312 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007313 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007314
7315 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7316 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7317 "ICmp should be folded!");
7318 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007319 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007320 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007321}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007322
Reid Spencer832254e2007-02-02 02:16:23 +00007323Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7324 return commonShiftTransforms(I);
7325}
7326
7327Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7328 return commonShiftTransforms(I);
7329}
7330
7331Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007332 if (Instruction *R = commonShiftTransforms(I))
7333 return R;
7334
7335 Value *Op0 = I.getOperand(0);
7336
7337 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7338 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7339 if (CSI->isAllOnesValue())
7340 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007341
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007342 // See if we can turn a signed shr into an unsigned shr.
7343 if (MaskedValueIsZero(Op0,
7344 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7345 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7346
7347 // Arithmetic shifting an all-sign-bit value is a no-op.
7348 unsigned NumSignBits = ComputeNumSignBits(Op0);
7349 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7350 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007351
Chris Lattner348f6652007-12-06 01:59:46 +00007352 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007353}
7354
7355Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7356 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007357 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007358
7359 // shl X, 0 == X and shr X, 0 == X
7360 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007361 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7362 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007363 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007364
Reid Spencere4d87aa2006-12-23 06:05:41 +00007365 if (isa<UndefValue>(Op0)) {
7366 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007367 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007368 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007369 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007370 }
7371 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007372 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7373 return ReplaceInstUsesWith(I, Op0);
7374 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007375 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007376 }
7377
Dan Gohman9004c8a2009-05-21 02:28:33 +00007378 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007379 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007380 return &I;
7381
Chris Lattner2eefe512004-04-09 19:05:30 +00007382 // Try to fold constant and into select arguments.
7383 if (isa<Constant>(Op0))
7384 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007385 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007386 return R;
7387
Reid Spencerb83eb642006-10-20 07:07:24 +00007388 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007389 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7390 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007391 return 0;
7392}
7393
Reid Spencerb83eb642006-10-20 07:07:24 +00007394Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007395 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007396 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007397
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007398 // See if we can simplify any instructions used by the instruction whose sole
7399 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007400 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007401
Dan Gohmana119de82009-06-14 23:30:43 +00007402 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7403 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007404 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007405 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007406 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007407 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007408 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007409 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007410 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007411 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007412 }
7413
7414 // ((X*C1) << C2) == (X * (C1 << C2))
7415 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7416 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7417 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007418 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007419 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007420
7421 // Try to fold constant and into select arguments.
7422 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7423 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7424 return R;
7425 if (isa<PHINode>(Op0))
7426 if (Instruction *NV = FoldOpIntoPhi(I))
7427 return NV;
7428
Chris Lattner8999dd32007-12-22 09:07:47 +00007429 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7430 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7431 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7432 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7433 // place. Don't try to do this transformation in this case. Also, we
7434 // require that the input operand is a shift-by-constant so that we have
7435 // confidence that the shifts will get folded together. We could do this
7436 // xform in more cases, but it is unlikely to be profitable.
7437 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7438 isa<ConstantInt>(TrOp->getOperand(1))) {
7439 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007440 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007441 // (shift2 (shift1 & 0x00FF), c2)
7442 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007443
7444 // For logical shifts, the truncation has the effect of making the high
7445 // part of the register be zeros. Emulate this by inserting an AND to
7446 // clear the top bits as needed. This 'and' will usually be zapped by
7447 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007448 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7449 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007450 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7451
7452 // The mask we constructed says what the trunc would do if occurring
7453 // between the shifts. We want to know the effect *after* the second
7454 // shift. We know that it is a logical shift by a constant, so adjust the
7455 // mask as appropriate.
7456 if (I.getOpcode() == Instruction::Shl)
7457 MaskV <<= Op1->getZExtValue();
7458 else {
7459 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7460 MaskV = MaskV.lshr(Op1->getZExtValue());
7461 }
7462
Chris Lattner74381062009-08-30 07:44:24 +00007463 // shift1 & 0x00FF
7464 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7465 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007466
7467 // Return the value truncated to the interesting size.
7468 return new TruncInst(And, I.getType());
7469 }
7470 }
7471
Chris Lattner4d5542c2006-01-06 07:12:35 +00007472 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007473 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7474 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7475 Value *V1, *V2;
7476 ConstantInt *CC;
7477 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007478 default: break;
7479 case Instruction::Add:
7480 case Instruction::And:
7481 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007482 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007483 // These operators commute.
7484 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007485 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007486 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007487 m_Specific(Op1)))) {
7488 Value *YS = // (Y << C)
7489 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7490 // (X + (Y << C))
7491 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7492 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007493 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007494 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007495 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007496 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007497
Chris Lattner150f12a2005-09-18 06:30:59 +00007498 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007499 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007500 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007501 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007502 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007503 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007504 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007505 Value *YS = // (Y << C)
7506 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7507 Op0BO->getName());
7508 // X & (CC << C)
7509 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7510 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007511 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007512 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007513 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007514
Reid Spencera07cb7d2007-02-02 14:41:37 +00007515 // FALL THROUGH.
7516 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007517 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007518 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007519 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007520 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007521 Value *YS = // (Y << C)
7522 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7523 // (X + (Y << C))
7524 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7525 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007526 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007527 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007528 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007529 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007530
Chris Lattner13d4ab42006-05-31 21:14:00 +00007531 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007532 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7533 match(Op0BO->getOperand(0),
7534 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007535 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007536 cast<BinaryOperator>(Op0BO->getOperand(0))
7537 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007538 Value *YS = // (Y << C)
7539 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7540 // X & (CC << C)
7541 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7542 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007543
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007544 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007545 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007546
Chris Lattner11021cb2005-09-18 05:12:10 +00007547 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007548 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007549 }
7550
7551
7552 // If the operand is an bitwise operator with a constant RHS, and the
7553 // shift is the only use, we can pull it out of the shift.
7554 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7555 bool isValid = true; // Valid only for And, Or, Xor
7556 bool highBitSet = false; // Transform if high bit of constant set?
7557
7558 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007559 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007560 case Instruction::Add:
7561 isValid = isLeftShift;
7562 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007563 case Instruction::Or:
7564 case Instruction::Xor:
7565 highBitSet = false;
7566 break;
7567 case Instruction::And:
7568 highBitSet = true;
7569 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007570 }
7571
7572 // If this is a signed shift right, and the high bit is modified
7573 // by the logical operation, do not perform the transformation.
7574 // The highBitSet boolean indicates the value of the high bit of
7575 // the constant which would cause it to be modified for this
7576 // operation.
7577 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007578 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007579 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007580
7581 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007582 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007583
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007584 Value *NewShift =
7585 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007586 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007587
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007588 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007589 NewRHS);
7590 }
7591 }
7592 }
7593 }
7594
Chris Lattnerad0124c2006-01-06 07:52:12 +00007595 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007596 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7597 if (ShiftOp && !ShiftOp->isShift())
7598 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007599
Reid Spencerb83eb642006-10-20 07:07:24 +00007600 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007601 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007602 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7603 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007604 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7605 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7606 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007607
Zhou Sheng4351c642007-04-02 08:20:41 +00007608 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007609
7610 const IntegerType *Ty = cast<IntegerType>(I.getType());
7611
7612 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007613 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007614 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7615 // saturates.
7616 if (AmtSum >= TypeBits) {
7617 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007618 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007619 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7620 }
7621
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007622 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007623 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007624 }
7625
7626 if (ShiftOp->getOpcode() == Instruction::LShr &&
7627 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007628 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007629 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007630
Chris Lattnerb87056f2007-02-05 00:57:54 +00007631 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007632 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007633 }
7634
7635 if (ShiftOp->getOpcode() == Instruction::AShr &&
7636 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007637 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007638 if (AmtSum >= TypeBits)
7639 AmtSum = TypeBits-1;
7640
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007641 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007642
Zhou Shenge9e03f62007-03-28 15:02:20 +00007643 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007644 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007645 }
7646
Chris Lattnerb87056f2007-02-05 00:57:54 +00007647 // Okay, if we get here, one shift must be left, and the other shift must be
7648 // right. See if the amounts are equal.
7649 if (ShiftAmt1 == ShiftAmt2) {
7650 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7651 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007652 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007653 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007654 }
7655 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7656 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007657 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007658 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007659 }
7660 // We can simplify ((X << C) >>s C) into a trunc + sext.
7661 // NOTE: we could do this for any C, but that would make 'unusual' integer
7662 // types. For now, just stick to ones well-supported by the code
7663 // generators.
7664 const Type *SExtType = 0;
7665 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007666 case 1 :
7667 case 8 :
7668 case 16 :
7669 case 32 :
7670 case 64 :
7671 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007672 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007673 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007674 default: break;
7675 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007676 if (SExtType)
7677 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007678 // Otherwise, we can't handle it yet.
7679 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007680 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007681
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007682 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007683 if (I.getOpcode() == Instruction::Shl) {
7684 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7685 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007686 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007687
Reid Spencer55702aa2007-03-25 21:11:44 +00007688 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007689 return BinaryOperator::CreateAnd(Shift,
7690 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007691 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007692
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007693 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007694 if (I.getOpcode() == Instruction::LShr) {
7695 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007696 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007697
Reid Spencerd5e30f02007-03-26 17:18:58 +00007698 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007699 return BinaryOperator::CreateAnd(Shift,
7700 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007701 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007702
7703 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7704 } else {
7705 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007706 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007707
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007708 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007709 if (I.getOpcode() == Instruction::Shl) {
7710 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7711 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007712 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7713 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007714
Reid Spencer55702aa2007-03-25 21:11:44 +00007715 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007716 return BinaryOperator::CreateAnd(Shift,
7717 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007718 }
7719
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007720 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007721 if (I.getOpcode() == Instruction::LShr) {
7722 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007723 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007724
Reid Spencer68d27cf2007-03-26 23:45:51 +00007725 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007726 return BinaryOperator::CreateAnd(Shift,
7727 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007728 }
7729
7730 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007731 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007732 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007733 return 0;
7734}
7735
Chris Lattnera1be5662002-05-02 17:06:02 +00007736
Chris Lattnercfd65102005-10-29 04:36:15 +00007737/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7738/// expression. If so, decompose it, returning some value X, such that Val is
7739/// X*Scale+Offset.
7740///
7741static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007742 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007743 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7744 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007745 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007746 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007747 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007748 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007749 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7750 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7751 if (I->getOpcode() == Instruction::Shl) {
7752 // This is a value scaled by '1 << the shift amt'.
7753 Scale = 1U << RHS->getZExtValue();
7754 Offset = 0;
7755 return I->getOperand(0);
7756 } else if (I->getOpcode() == Instruction::Mul) {
7757 // This value is scaled by 'RHS'.
7758 Scale = RHS->getZExtValue();
7759 Offset = 0;
7760 return I->getOperand(0);
7761 } else if (I->getOpcode() == Instruction::Add) {
7762 // We have X+C. Check to see if we really have (X*C2)+C1,
7763 // where C1 is divisible by C2.
7764 unsigned SubScale;
7765 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007766 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7767 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007768 Offset += RHS->getZExtValue();
7769 Scale = SubScale;
7770 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007771 }
7772 }
7773 }
7774
7775 // Otherwise, we can't look past this.
7776 Scale = 1;
7777 Offset = 0;
7778 return Val;
7779}
7780
7781
Chris Lattnerb3f83972005-10-24 06:03:58 +00007782/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7783/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007784Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00007785 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007786 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007787
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007788 BuilderTy AllocaBuilder(*Builder);
7789 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7790
Chris Lattnerb53c2382005-10-24 06:22:12 +00007791 // Remove any uses of AI that are dead.
7792 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007793
Chris Lattnerb53c2382005-10-24 06:22:12 +00007794 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7795 Instruction *User = cast<Instruction>(*UI++);
7796 if (isInstructionTriviallyDead(User)) {
7797 while (UI != E && *UI == User)
7798 ++UI; // If this instruction uses AI more than once, don't break UI.
7799
Chris Lattnerb53c2382005-10-24 06:22:12 +00007800 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007801 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007802 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007803 }
7804 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007805
7806 // This requires TargetData to get the alloca alignment and size information.
7807 if (!TD) return 0;
7808
Chris Lattnerb3f83972005-10-24 06:03:58 +00007809 // Get the type really allocated and the type casted to.
7810 const Type *AllocElTy = AI.getAllocatedType();
7811 const Type *CastElTy = PTy->getElementType();
7812 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007813
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007814 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7815 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007816 if (CastElTyAlign < AllocElTyAlign) return 0;
7817
Chris Lattner39387a52005-10-24 06:35:18 +00007818 // If the allocation has multiple uses, only promote it if we are strictly
7819 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007820 // same, we open the door to infinite loops of various kinds. (A reference
7821 // from a dbg.declare doesn't count as a use for this purpose.)
7822 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7823 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007824
Duncan Sands777d2302009-05-09 07:06:46 +00007825 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7826 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007827 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007828
Chris Lattner455fcc82005-10-29 03:19:53 +00007829 // See if we can satisfy the modulus by pulling a scale out of the array
7830 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007831 unsigned ArraySizeScale;
7832 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007833 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007834 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7835 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007836
Chris Lattner455fcc82005-10-29 03:19:53 +00007837 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7838 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007839 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7840 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007841
Chris Lattner455fcc82005-10-29 03:19:53 +00007842 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7843 Value *Amt = 0;
7844 if (Scale == 1) {
7845 Amt = NumElements;
7846 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007847 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007848 // Insert before the alloca, not before the cast.
7849 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007850 }
7851
Jeff Cohen86796be2007-04-04 16:58:57 +00007852 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007853 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007854 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007855 }
7856
Victor Hernandez7b929da2009-10-23 21:09:37 +00007857 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007858 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007859 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007860
Dale Johannesena0a66372009-03-05 00:39:02 +00007861 // If the allocation has one real use plus a dbg.declare, just remove the
7862 // declare.
7863 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7864 EraseInstFromFunction(*DI);
7865 }
7866 // If the allocation has multiple real uses, insert a cast and change all
7867 // things that used it to use the new cast. This will also hack on CI, but it
7868 // will die soon.
7869 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007870 // New is the allocation instruction, pointer typed. AI is the original
7871 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007872 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007873 AI.replaceAllUsesWith(NewCast);
7874 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007875 return ReplaceInstUsesWith(CI, New);
7876}
7877
Chris Lattner70074e02006-05-13 02:06:03 +00007878/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007879/// and return it as type Ty without inserting any new casts and without
7880/// changing the computed value. This is used by code that tries to decide
7881/// whether promoting or shrinking integer operations to wider or smaller types
7882/// will allow us to eliminate a truncate or extend.
7883///
7884/// This is a truncation operation if Ty is smaller than V->getType(), or an
7885/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007886///
7887/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7888/// should return true if trunc(V) can be computed by computing V in the smaller
7889/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7890/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7891/// efficiently truncated.
7892///
7893/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7894/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7895/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007896bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007897 unsigned CastOpc,
7898 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007899 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007900 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007901 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007902
7903 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007904 if (!I) return false;
7905
Dan Gohman6de29f82009-06-15 22:12:54 +00007906 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007907
Chris Lattner951626b2007-08-02 06:11:14 +00007908 // If this is an extension or truncate, we can often eliminate it.
7909 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7910 // If this is a cast from the destination type, we can trivially eliminate
7911 // it, and this will remove a cast overall.
7912 if (I->getOperand(0)->getType() == Ty) {
7913 // If the first operand is itself a cast, and is eliminable, do not count
7914 // this as an eliminable cast. We would prefer to eliminate those two
7915 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007916 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007917 ++NumCastsRemoved;
7918 return true;
7919 }
7920 }
7921
7922 // We can't extend or shrink something that has multiple uses: doing so would
7923 // require duplicating the instruction in general, which isn't profitable.
7924 if (!I->hasOneUse()) return false;
7925
Evan Chengf35fd542009-01-15 17:01:23 +00007926 unsigned Opc = I->getOpcode();
7927 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007928 case Instruction::Add:
7929 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007930 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007931 case Instruction::And:
7932 case Instruction::Or:
7933 case Instruction::Xor:
7934 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007935 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007936 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007937 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007938 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007939
Eli Friedman070a9812009-07-13 22:46:01 +00007940 case Instruction::UDiv:
7941 case Instruction::URem: {
7942 // UDiv and URem can be truncated if all the truncated bits are zero.
7943 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7944 uint32_t BitWidth = Ty->getScalarSizeInBits();
7945 if (BitWidth < OrigBitWidth) {
7946 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7947 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7948 MaskedValueIsZero(I->getOperand(1), Mask)) {
7949 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7950 NumCastsRemoved) &&
7951 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7952 NumCastsRemoved);
7953 }
7954 }
7955 break;
7956 }
Chris Lattner46b96052006-11-29 07:18:39 +00007957 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007958 // If we are truncating the result of this SHL, and if it's a shift of a
7959 // constant amount, we can always perform a SHL in a smaller type.
7960 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007961 uint32_t BitWidth = Ty->getScalarSizeInBits();
7962 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007963 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007964 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007965 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007966 }
7967 break;
7968 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007969 // If this is a truncate of a logical shr, we can truncate it to a smaller
7970 // lshr iff we know that the bits we would otherwise be shifting in are
7971 // already zeros.
7972 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007973 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7974 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007975 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007976 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007977 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7978 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007979 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007980 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007981 }
7982 }
Chris Lattner46b96052006-11-29 07:18:39 +00007983 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007984 case Instruction::ZExt:
7985 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007986 case Instruction::Trunc:
7987 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007988 // can safely replace it. Note that replacing it does not reduce the number
7989 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007990 if (Opc == CastOpc)
7991 return true;
7992
7993 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007994 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007995 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007996 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007997 case Instruction::Select: {
7998 SelectInst *SI = cast<SelectInst>(I);
7999 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008000 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008001 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008002 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008003 }
Chris Lattner8114b712008-06-18 04:00:49 +00008004 case Instruction::PHI: {
8005 // We can change a phi if we can change all operands.
8006 PHINode *PN = cast<PHINode>(I);
8007 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8008 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008009 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008010 return false;
8011 return true;
8012 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008013 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008014 // TODO: Can handle more cases here.
8015 break;
8016 }
8017
8018 return false;
8019}
8020
8021/// EvaluateInDifferentType - Given an expression that
8022/// CanEvaluateInDifferentType returns true for, actually insert the code to
8023/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008024Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008025 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008026 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00008027 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00008028 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008029
8030 // Otherwise, it must be an instruction.
8031 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008032 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008033 unsigned Opc = I->getOpcode();
8034 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008035 case Instruction::Add:
8036 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008037 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008038 case Instruction::And:
8039 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008040 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008041 case Instruction::AShr:
8042 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008043 case Instruction::Shl:
8044 case Instruction::UDiv:
8045 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008046 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008047 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008048 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008049 break;
8050 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008051 case Instruction::Trunc:
8052 case Instruction::ZExt:
8053 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008054 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008055 // just return the source. There's no need to insert it because it is not
8056 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008057 if (I->getOperand(0)->getType() == Ty)
8058 return I->getOperand(0);
8059
Chris Lattner8114b712008-06-18 04:00:49 +00008060 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008061 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008062 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008063 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008064 case Instruction::Select: {
8065 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8066 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8067 Res = SelectInst::Create(I->getOperand(0), True, False);
8068 break;
8069 }
Chris Lattner8114b712008-06-18 04:00:49 +00008070 case Instruction::PHI: {
8071 PHINode *OPN = cast<PHINode>(I);
8072 PHINode *NPN = PHINode::Create(Ty);
8073 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8074 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8075 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8076 }
8077 Res = NPN;
8078 break;
8079 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008080 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008081 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008082 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008083 break;
8084 }
8085
Chris Lattner8114b712008-06-18 04:00:49 +00008086 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008087 return InsertNewInstBefore(Res, *I);
8088}
8089
Reid Spencer3da59db2006-11-27 01:05:10 +00008090/// @brief Implement the transforms common to all CastInst visitors.
8091Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008092 Value *Src = CI.getOperand(0);
8093
Dan Gohman23d9d272007-05-11 21:10:54 +00008094 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008095 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008096 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008097 if (Instruction::CastOps opc =
8098 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8099 // The first cast (CSrc) is eliminable so we need to fix up or replace
8100 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008101 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008102 }
8103 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008104
Reid Spencer3da59db2006-11-27 01:05:10 +00008105 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008106 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8107 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8108 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008109
8110 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008111 if (isa<PHINode>(Src))
8112 if (Instruction *NV = FoldOpIntoPhi(CI))
8113 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008114
Reid Spencer3da59db2006-11-27 01:05:10 +00008115 return 0;
8116}
8117
Chris Lattner46cd5a12009-01-09 05:44:56 +00008118/// FindElementAtOffset - Given a type and a constant offset, determine whether
8119/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008120/// the specified offset. If so, fill them into NewIndices and return the
8121/// resultant element type, otherwise return null.
8122static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8123 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008124 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008125 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008126 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008127 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008128
8129 // Start with the index over the outer type. Note that the type size
8130 // might be zero (even if the offset isn't zero) if the indexed type
8131 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008132 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008133 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008134 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008135 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008136 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008137
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008138 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008139 if (Offset < 0) {
8140 --FirstIdx;
8141 Offset += TySize;
8142 assert(Offset >= 0);
8143 }
8144 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8145 }
8146
Owen Andersoneed707b2009-07-24 23:12:02 +00008147 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008148
8149 // Index into the types. If we fail, set OrigBase to null.
8150 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008151 // Indexing into tail padding between struct/array elements.
8152 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008153 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008154
Chris Lattner46cd5a12009-01-09 05:44:56 +00008155 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8156 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008157 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8158 "Offset must stay within the indexed type");
8159
Chris Lattner46cd5a12009-01-09 05:44:56 +00008160 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008161 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008162
8163 Offset -= SL->getElementOffset(Elt);
8164 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008165 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008166 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008167 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008168 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008169 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008170 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008171 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008172 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008173 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008174 }
8175 }
8176
Chris Lattner3914f722009-01-24 01:00:13 +00008177 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008178}
8179
Chris Lattnerd3e28342007-04-27 17:44:50 +00008180/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8181Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8182 Value *Src = CI.getOperand(0);
8183
Chris Lattnerd3e28342007-04-27 17:44:50 +00008184 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008185 // If casting the result of a getelementptr instruction with no offset, turn
8186 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008187 if (GEP->hasAllZeroIndices()) {
8188 // Changing the cast operand is usually not a good idea but it is safe
8189 // here because the pointer operand is being replaced with another
8190 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008191 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008192 CI.setOperand(0, GEP->getOperand(0));
8193 return &CI;
8194 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008195
8196 // If the GEP has a single use, and the base pointer is a bitcast, and the
8197 // GEP computes a constant offset, see if we can convert these three
8198 // instructions into fewer. This typically happens with unions and other
8199 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008200 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008201 if (GEP->hasAllConstantIndices()) {
8202 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008203 ConstantInt *OffsetV =
8204 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008205 int64_t Offset = OffsetV->getSExtValue();
8206
8207 // Get the base pointer input of the bitcast, and the type it points to.
8208 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8209 const Type *GEPIdxTy =
8210 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008211 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008212 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008213 // If we were able to index down into an element, create the GEP
8214 // and bitcast the result. This eliminates one bitcast, potentially
8215 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008216 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8217 Builder->CreateInBoundsGEP(OrigBase,
8218 NewIndices.begin(), NewIndices.end()) :
8219 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008220 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008221
Chris Lattner46cd5a12009-01-09 05:44:56 +00008222 if (isa<BitCastInst>(CI))
8223 return new BitCastInst(NGEP, CI.getType());
8224 assert(isa<PtrToIntInst>(CI));
8225 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008226 }
8227 }
8228 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008229 }
8230
8231 return commonCastTransforms(CI);
8232}
8233
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008234/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8235/// type like i42. We don't want to introduce operations on random non-legal
8236/// integer types where they don't already exist in the code. In the future,
8237/// we should consider making this based off target-data, so that 32-bit targets
8238/// won't get i64 operations etc.
8239static bool isSafeIntegerType(const Type *Ty) {
8240 switch (Ty->getPrimitiveSizeInBits()) {
8241 case 8:
8242 case 16:
8243 case 32:
8244 case 64:
8245 return true;
8246 default:
8247 return false;
8248 }
8249}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008250
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008251/// commonIntCastTransforms - This function implements the common transforms
8252/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008253Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8254 if (Instruction *Result = commonCastTransforms(CI))
8255 return Result;
8256
8257 Value *Src = CI.getOperand(0);
8258 const Type *SrcTy = Src->getType();
8259 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008260 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8261 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008262
Reid Spencer3da59db2006-11-27 01:05:10 +00008263 // See if we can simplify any instructions used by the LHS whose sole
8264 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008265 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008266 return &CI;
8267
8268 // If the source isn't an instruction or has more than one use then we
8269 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008270 Instruction *SrcI = dyn_cast<Instruction>(Src);
8271 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008272 return 0;
8273
Chris Lattnerc739cd62007-03-03 05:27:34 +00008274 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008275 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008276 // Only do this if the dest type is a simple type, don't convert the
8277 // expression tree to something weird like i93 unless the source is also
8278 // strange.
8279 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008280 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8281 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008282 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008283 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008284 // eliminates the cast, so it is always a win. If this is a zero-extension,
8285 // we need to do an AND to maintain the clear top-part of the computation,
8286 // so we require that the input have eliminated at least one cast. If this
8287 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008288 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008289 bool DoXForm = false;
8290 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008291 switch (CI.getOpcode()) {
8292 default:
8293 // All the others use floating point so we shouldn't actually
8294 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008295 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008296 case Instruction::Trunc:
8297 DoXForm = true;
8298 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008299 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008300 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008301 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008302 // If it's unnecessary to issue an AND to clear the high bits, it's
8303 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008304 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008305 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8306 if (MaskedValueIsZero(TryRes, Mask))
8307 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008308
8309 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008310 if (TryI->use_empty())
8311 EraseInstFromFunction(*TryI);
8312 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008313 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008314 }
Evan Chengf35fd542009-01-15 17:01:23 +00008315 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008316 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008317 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008318 // If we do not have to emit the truncate + sext pair, then it's always
8319 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008320 //
8321 // It's not safe to eliminate the trunc + sext pair if one of the
8322 // eliminated cast is a truncate. e.g.
8323 // t2 = trunc i32 t1 to i16
8324 // t3 = sext i16 t2 to i32
8325 // !=
8326 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008327 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008328 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8329 if (NumSignBits > (DestBitSize - SrcBitSize))
8330 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008331
8332 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008333 if (TryI->use_empty())
8334 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008335 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008336 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008337 }
Evan Chengf35fd542009-01-15 17:01:23 +00008338 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008339
8340 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008341 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8342 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008343 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8344 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008345 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008346 // Just replace this cast with the result.
8347 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008348
Reid Spencer3da59db2006-11-27 01:05:10 +00008349 assert(Res->getType() == DestTy);
8350 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008351 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008352 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008353 // Just replace this cast with the result.
8354 return ReplaceInstUsesWith(CI, Res);
8355 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008356 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008357
8358 // If the high bits are already zero, just replace this cast with the
8359 // result.
8360 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8361 if (MaskedValueIsZero(Res, Mask))
8362 return ReplaceInstUsesWith(CI, Res);
8363
8364 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008365 Constant *C = ConstantInt::get(*Context,
8366 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008367 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008368 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008369 case Instruction::SExt: {
8370 // If the high bits are already filled with sign bit, just replace this
8371 // cast with the result.
8372 unsigned NumSignBits = ComputeNumSignBits(Res);
8373 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008374 return ReplaceInstUsesWith(CI, Res);
8375
Reid Spencer3da59db2006-11-27 01:05:10 +00008376 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008377 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008378 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008379 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008380 }
8381 }
8382
8383 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8384 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8385
8386 switch (SrcI->getOpcode()) {
8387 case Instruction::Add:
8388 case Instruction::Mul:
8389 case Instruction::And:
8390 case Instruction::Or:
8391 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008392 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008393 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8394 // Don't insert two casts unless at least one can be eliminated.
8395 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008396 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008397 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8398 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008399 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008400 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008401 }
8402 }
8403
8404 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8405 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8406 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008407 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008408 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008409 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008410 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008411 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008412 }
8413 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008414
Eli Friedman65445c52009-07-13 21:45:57 +00008415 case Instruction::Shl: {
8416 // Canonicalize trunc inside shl, if we can.
8417 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8418 if (CI && DestBitSize < SrcBitSize &&
8419 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008420 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8421 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008422 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008423 }
8424 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008425 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008426 }
8427 return 0;
8428}
8429
Chris Lattner8a9f5712007-04-11 06:57:46 +00008430Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008431 if (Instruction *Result = commonIntCastTransforms(CI))
8432 return Result;
8433
8434 Value *Src = CI.getOperand(0);
8435 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008436 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8437 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008438
8439 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008440 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008441 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008442 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008443 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008444 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008445 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008446
Chris Lattner4f9797d2009-03-24 18:15:30 +00008447 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8448 ConstantInt *ShAmtV = 0;
8449 Value *ShiftOp = 0;
8450 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008451 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008452 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8453
8454 // Get a mask for the bits shifting in.
8455 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8456 if (MaskedValueIsZero(ShiftOp, Mask)) {
8457 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008458 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008459
8460 // Okay, we can shrink this. Truncate the input, then return a new
8461 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008462 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008463 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008464 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008465 }
8466 }
8467
8468 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008469}
8470
Evan Chengb98a10e2008-03-24 00:21:34 +00008471/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8472/// in order to eliminate the icmp.
8473Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8474 bool DoXform) {
8475 // If we are just checking for a icmp eq of a single bit and zext'ing it
8476 // to an integer, then shift the bit to the appropriate place and then
8477 // cast to integer to avoid the comparison.
8478 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8479 const APInt &Op1CV = Op1C->getValue();
8480
8481 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8482 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8483 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8484 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8485 if (!DoXform) return ICI;
8486
8487 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008488 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008489 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008490 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008491 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008492 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008493
8494 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008495 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008496 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008497 }
8498
8499 return ReplaceInstUsesWith(CI, In);
8500 }
8501
8502
8503
8504 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8505 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8506 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8507 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8508 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8509 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8510 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8511 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8512 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8513 // This only works for EQ and NE
8514 ICI->isEquality()) {
8515 // If Op1C some other power of two, convert:
8516 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8517 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8518 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8519 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8520
8521 APInt KnownZeroMask(~KnownZero);
8522 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8523 if (!DoXform) return ICI;
8524
8525 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8526 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8527 // (X&4) == 2 --> false
8528 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008529 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008530 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008531 return ReplaceInstUsesWith(CI, Res);
8532 }
8533
8534 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8535 Value *In = ICI->getOperand(0);
8536 if (ShiftAmt) {
8537 // Perform a logical shr by shiftamt.
8538 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008539 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8540 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008541 }
8542
8543 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008544 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008545 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008546 }
8547
8548 if (CI.getType() == In->getType())
8549 return ReplaceInstUsesWith(CI, In);
8550 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008551 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008552 }
8553 }
8554 }
8555
8556 return 0;
8557}
8558
Chris Lattner8a9f5712007-04-11 06:57:46 +00008559Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008560 // If one of the common conversion will work ..
8561 if (Instruction *Result = commonIntCastTransforms(CI))
8562 return Result;
8563
8564 Value *Src = CI.getOperand(0);
8565
Chris Lattnera84f47c2009-02-17 20:47:23 +00008566 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8567 // types and if the sizes are just right we can convert this into a logical
8568 // 'and' which will be much cheaper than the pair of casts.
8569 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8570 // Get the sizes of the types involved. We know that the intermediate type
8571 // will be smaller than A or C, but don't know the relation between A and C.
8572 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008573 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8574 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8575 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008576 // If we're actually extending zero bits, then if
8577 // SrcSize < DstSize: zext(a & mask)
8578 // SrcSize == DstSize: a & mask
8579 // SrcSize > DstSize: trunc(a) & mask
8580 if (SrcSize < DstSize) {
8581 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008582 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008583 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008584 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008585 }
8586
8587 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008588 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008589 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008590 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008591 }
8592 if (SrcSize > DstSize) {
8593 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008594 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008595 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008596 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008597 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008598 }
8599 }
8600
Evan Chengb98a10e2008-03-24 00:21:34 +00008601 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8602 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008603
Evan Chengb98a10e2008-03-24 00:21:34 +00008604 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8605 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8606 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8607 // of the (zext icmp) will be transformed.
8608 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8609 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8610 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8611 (transformZExtICmp(LHS, CI, false) ||
8612 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008613 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8614 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008615 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008616 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008617 }
8618
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008619 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008620 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8621 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8622 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8623 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008624 if (TI0->getType() == CI.getType())
8625 return
8626 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008627 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008628 }
8629
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008630 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8631 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8632 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8633 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8634 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8635 And->getOperand(1) == C)
8636 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8637 Value *TI0 = TI->getOperand(0);
8638 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008639 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008640 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008641 return BinaryOperator::CreateXor(NewAnd, ZC);
8642 }
8643 }
8644
Reid Spencer3da59db2006-11-27 01:05:10 +00008645 return 0;
8646}
8647
Chris Lattner8a9f5712007-04-11 06:57:46 +00008648Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008649 if (Instruction *I = commonIntCastTransforms(CI))
8650 return I;
8651
Chris Lattner8a9f5712007-04-11 06:57:46 +00008652 Value *Src = CI.getOperand(0);
8653
Dan Gohman1975d032008-10-30 20:40:10 +00008654 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008655 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008656 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008657 Constant::getAllOnesValue(CI.getType()),
8658 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008659
8660 // See if the value being truncated is already sign extended. If so, just
8661 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008662 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008663 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008664 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8665 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8666 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008667 unsigned NumSignBits = ComputeNumSignBits(Op);
8668
8669 if (OpBits == DestBits) {
8670 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8671 // bits, it is already ready.
8672 if (NumSignBits > DestBits-MidBits)
8673 return ReplaceInstUsesWith(CI, Op);
8674 } else if (OpBits < DestBits) {
8675 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8676 // bits, just sext from i32.
8677 if (NumSignBits > OpBits-MidBits)
8678 return new SExtInst(Op, CI.getType(), "tmp");
8679 } else {
8680 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8681 // bits, just truncate to i32.
8682 if (NumSignBits > OpBits-MidBits)
8683 return new TruncInst(Op, CI.getType(), "tmp");
8684 }
8685 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008686
8687 // If the input is a shl/ashr pair of a same constant, then this is a sign
8688 // extension from a smaller value. If we could trust arbitrary bitwidth
8689 // integers, we could turn this into a truncate to the smaller bit and then
8690 // use a sext for the whole extension. Since we don't, look deeper and check
8691 // for a truncate. If the source and dest are the same type, eliminate the
8692 // trunc and extend and just do shifts. For example, turn:
8693 // %a = trunc i32 %i to i8
8694 // %b = shl i8 %a, 6
8695 // %c = ashr i8 %b, 6
8696 // %d = sext i8 %c to i32
8697 // into:
8698 // %a = shl i32 %i, 30
8699 // %d = ashr i32 %a, 30
8700 Value *A = 0;
8701 ConstantInt *BA = 0, *CA = 0;
8702 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008703 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008704 BA == CA && isa<TruncInst>(A)) {
8705 Value *I = cast<TruncInst>(A)->getOperand(0);
8706 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008707 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8708 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008709 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008710 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008711 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008712 return BinaryOperator::CreateAShr(I, ShAmtV);
8713 }
8714 }
8715
Chris Lattnerba417832007-04-11 06:12:58 +00008716 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008717}
8718
Chris Lattnerb7530652008-01-27 05:29:54 +00008719/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8720/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008721static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008722 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008723 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008724 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008725 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8726 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008727 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008728 return 0;
8729}
8730
8731/// LookThroughFPExtensions - If this is an fp extension instruction, look
8732/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008733static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008734 if (Instruction *I = dyn_cast<Instruction>(V))
8735 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008736 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008737
8738 // If this value is a constant, return the constant in the smallest FP type
8739 // that can accurately represent it. This allows us to turn
8740 // (float)((double)X+2.0) into x+2.0f.
8741 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008742 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008743 return V; // No constant folding of this.
8744 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008745 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008746 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008747 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008748 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008749 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008750 return V;
8751 // Don't try to shrink to various long double types.
8752 }
8753
8754 return V;
8755}
8756
8757Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8758 if (Instruction *I = commonCastTransforms(CI))
8759 return I;
8760
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008761 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008762 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008763 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008764 // many builtins (sqrt, etc).
8765 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8766 if (OpI && OpI->hasOneUse()) {
8767 switch (OpI->getOpcode()) {
8768 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008769 case Instruction::FAdd:
8770 case Instruction::FSub:
8771 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008772 case Instruction::FDiv:
8773 case Instruction::FRem:
8774 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008775 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8776 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008777 if (LHSTrunc->getType() != SrcTy &&
8778 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008779 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008780 // If the source types were both smaller than the destination type of
8781 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008782 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8783 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008784 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8785 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008786 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008787 }
8788 }
8789 break;
8790 }
8791 }
8792 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008793}
8794
8795Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8796 return commonCastTransforms(CI);
8797}
8798
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008799Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008800 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8801 if (OpI == 0)
8802 return commonCastTransforms(FI);
8803
8804 // fptoui(uitofp(X)) --> X
8805 // fptoui(sitofp(X)) --> X
8806 // This is safe if the intermediate type has enough bits in its mantissa to
8807 // accurately represent all values of X. For example, do not do this with
8808 // i64->float->i64. This is also safe for sitofp case, because any negative
8809 // 'X' value would cause an undefined result for the fptoui.
8810 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8811 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008812 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008813 OpI->getType()->getFPMantissaWidth())
8814 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008815
8816 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008817}
8818
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008819Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008820 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8821 if (OpI == 0)
8822 return commonCastTransforms(FI);
8823
8824 // fptosi(sitofp(X)) --> X
8825 // fptosi(uitofp(X)) --> X
8826 // This is safe if the intermediate type has enough bits in its mantissa to
8827 // accurately represent all values of X. For example, do not do this with
8828 // i64->float->i64. This is also safe for sitofp case, because any negative
8829 // 'X' value would cause an undefined result for the fptoui.
8830 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8831 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008832 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008833 OpI->getType()->getFPMantissaWidth())
8834 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008835
8836 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008837}
8838
8839Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8840 return commonCastTransforms(CI);
8841}
8842
8843Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8844 return commonCastTransforms(CI);
8845}
8846
Chris Lattnera0e69692009-03-24 18:35:40 +00008847Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8848 // If the destination integer type is smaller than the intptr_t type for
8849 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8850 // trunc to be exposed to other transforms. Don't do this for extending
8851 // ptrtoint's, because we don't know if the target sign or zero extends its
8852 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008853 if (TD &&
8854 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008855 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8856 TD->getIntPtrType(CI.getContext()),
8857 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008858 return new TruncInst(P, CI.getType());
8859 }
8860
Chris Lattnerd3e28342007-04-27 17:44:50 +00008861 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008862}
8863
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008864Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008865 // If the source integer type is larger than the intptr_t type for
8866 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8867 // allows the trunc to be exposed to other transforms. Don't do this for
8868 // extending inttoptr's, because we don't know if the target sign or zero
8869 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008870 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008871 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008872 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8873 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008874 return new IntToPtrInst(P, CI.getType());
8875 }
8876
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008877 if (Instruction *I = commonCastTransforms(CI))
8878 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008879
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008880 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008881}
8882
Chris Lattnerd3e28342007-04-27 17:44:50 +00008883Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008884 // If the operands are integer typed then apply the integer transforms,
8885 // otherwise just apply the common ones.
8886 Value *Src = CI.getOperand(0);
8887 const Type *SrcTy = Src->getType();
8888 const Type *DestTy = CI.getType();
8889
Eli Friedman7e25d452009-07-13 20:53:00 +00008890 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008891 if (Instruction *I = commonPointerCastTransforms(CI))
8892 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008893 } else {
8894 if (Instruction *Result = commonCastTransforms(CI))
8895 return Result;
8896 }
8897
8898
8899 // Get rid of casts from one type to the same type. These are useless and can
8900 // be replaced by the operand.
8901 if (DestTy == Src->getType())
8902 return ReplaceInstUsesWith(CI, Src);
8903
Reid Spencer3da59db2006-11-27 01:05:10 +00008904 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008905 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8906 const Type *DstElTy = DstPTy->getElementType();
8907 const Type *SrcElTy = SrcPTy->getElementType();
8908
Nate Begeman83ad90a2008-03-31 00:22:16 +00008909 // If the address spaces don't match, don't eliminate the bitcast, which is
8910 // required for changing types.
8911 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8912 return 0;
8913
Victor Hernandez83d63912009-09-18 22:35:49 +00008914 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008915 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008916 // There is no need to modify malloc calls because it is their bitcast that
8917 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00008918 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00008919 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8920 return V;
8921
Chris Lattnerd717c182007-05-05 22:32:24 +00008922 // If the source and destination are pointers, and this cast is equivalent
8923 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008924 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008925 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008926 unsigned NumZeros = 0;
8927 while (SrcElTy != DstElTy &&
8928 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8929 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8930 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8931 ++NumZeros;
8932 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008933
Chris Lattnerd3e28342007-04-27 17:44:50 +00008934 // If we found a path from the src to dest, create the getelementptr now.
8935 if (SrcElTy == DstElTy) {
8936 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008937 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8938 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008939 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008940 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008941
Eli Friedman2451a642009-07-18 23:06:53 +00008942 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8943 if (DestVTy->getNumElements() == 1) {
8944 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008945 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008946 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008947 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008948 }
8949 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8950 }
8951 }
8952
8953 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8954 if (SrcVTy->getNumElements() == 1) {
8955 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008956 Value *Elem =
8957 Builder->CreateExtractElement(Src,
8958 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008959 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8960 }
8961 }
8962 }
8963
Reid Spencer3da59db2006-11-27 01:05:10 +00008964 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8965 if (SVI->hasOneUse()) {
8966 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8967 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008968 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008969 cast<VectorType>(DestTy)->getNumElements() ==
8970 SVI->getType()->getNumElements() &&
8971 SVI->getType()->getNumElements() ==
8972 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008973 CastInst *Tmp;
8974 // If either of the operands is a cast from CI.getType(), then
8975 // evaluating the shuffle in the casted destination's type will allow
8976 // us to eliminate at least one cast.
8977 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8978 Tmp->getOperand(0)->getType() == DestTy) ||
8979 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8980 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008981 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8982 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008983 // Return a new shuffle vector. Use the same element ID's, as we
8984 // know the vector types match #elts.
8985 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008986 }
8987 }
8988 }
8989 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008990 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008991}
8992
Chris Lattnere576b912004-04-09 23:46:01 +00008993/// GetSelectFoldableOperands - We want to turn code that looks like this:
8994/// %C = or %A, %B
8995/// %D = select %cond, %C, %A
8996/// into:
8997/// %C = select %cond, %B, 0
8998/// %D = or %A, %C
8999///
9000/// Assuming that the specified instruction is an operand to the select, return
9001/// a bitmask indicating which operands of this instruction are foldable if they
9002/// equal the other incoming value of the select.
9003///
9004static unsigned GetSelectFoldableOperands(Instruction *I) {
9005 switch (I->getOpcode()) {
9006 case Instruction::Add:
9007 case Instruction::Mul:
9008 case Instruction::And:
9009 case Instruction::Or:
9010 case Instruction::Xor:
9011 return 3; // Can fold through either operand.
9012 case Instruction::Sub: // Can only fold on the amount subtracted.
9013 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009014 case Instruction::LShr:
9015 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009016 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009017 default:
9018 return 0; // Cannot fold
9019 }
9020}
9021
9022/// GetSelectFoldableConstant - For the same transformation as the previous
9023/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009024static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009025 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009026 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009027 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009028 case Instruction::Add:
9029 case Instruction::Sub:
9030 case Instruction::Or:
9031 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009032 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009033 case Instruction::LShr:
9034 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009035 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009036 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009037 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009038 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009039 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009040 }
9041}
9042
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009043/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9044/// have the same opcode and only one use each. Try to simplify this.
9045Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9046 Instruction *FI) {
9047 if (TI->getNumOperands() == 1) {
9048 // If this is a non-volatile load or a cast from the same type,
9049 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009050 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009051 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9052 return 0;
9053 } else {
9054 return 0; // unknown unary op.
9055 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009056
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009057 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009058 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009059 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009060 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009061 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009062 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009063 }
9064
Reid Spencer832254e2007-02-02 02:16:23 +00009065 // Only handle binary operators here.
9066 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009067 return 0;
9068
9069 // Figure out if the operations have any operands in common.
9070 Value *MatchOp, *OtherOpT, *OtherOpF;
9071 bool MatchIsOpZero;
9072 if (TI->getOperand(0) == FI->getOperand(0)) {
9073 MatchOp = TI->getOperand(0);
9074 OtherOpT = TI->getOperand(1);
9075 OtherOpF = FI->getOperand(1);
9076 MatchIsOpZero = true;
9077 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9078 MatchOp = TI->getOperand(1);
9079 OtherOpT = TI->getOperand(0);
9080 OtherOpF = FI->getOperand(0);
9081 MatchIsOpZero = false;
9082 } else if (!TI->isCommutative()) {
9083 return 0;
9084 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9085 MatchOp = TI->getOperand(0);
9086 OtherOpT = TI->getOperand(1);
9087 OtherOpF = FI->getOperand(0);
9088 MatchIsOpZero = true;
9089 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9090 MatchOp = TI->getOperand(1);
9091 OtherOpT = TI->getOperand(0);
9092 OtherOpF = FI->getOperand(1);
9093 MatchIsOpZero = true;
9094 } else {
9095 return 0;
9096 }
9097
9098 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009099 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9100 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009101 InsertNewInstBefore(NewSI, SI);
9102
9103 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9104 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009105 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009106 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009107 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009108 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009109 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009110 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009111}
9112
Evan Chengde621922009-03-31 20:42:45 +00009113static bool isSelect01(Constant *C1, Constant *C2) {
9114 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9115 if (!C1I)
9116 return false;
9117 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9118 if (!C2I)
9119 return false;
9120 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9121}
9122
9123/// FoldSelectIntoOp - Try fold the select into one of the operands to
9124/// facilitate further optimization.
9125Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9126 Value *FalseVal) {
9127 // See the comment above GetSelectFoldableOperands for a description of the
9128 // transformation we are doing here.
9129 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9130 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9131 !isa<Constant>(FalseVal)) {
9132 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9133 unsigned OpToFold = 0;
9134 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9135 OpToFold = 1;
9136 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9137 OpToFold = 2;
9138 }
9139
9140 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009141 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009142 Value *OOp = TVI->getOperand(2-OpToFold);
9143 // Avoid creating select between 2 constants unless it's selecting
9144 // between 0 and 1.
9145 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9146 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9147 InsertNewInstBefore(NewSel, SI);
9148 NewSel->takeName(TVI);
9149 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9150 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009151 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009152 }
9153 }
9154 }
9155 }
9156 }
9157
9158 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9159 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9160 !isa<Constant>(TrueVal)) {
9161 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9162 unsigned OpToFold = 0;
9163 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9164 OpToFold = 1;
9165 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9166 OpToFold = 2;
9167 }
9168
9169 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009170 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009171 Value *OOp = FVI->getOperand(2-OpToFold);
9172 // Avoid creating select between 2 constants unless it's selecting
9173 // between 0 and 1.
9174 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9175 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9176 InsertNewInstBefore(NewSel, SI);
9177 NewSel->takeName(FVI);
9178 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9179 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009180 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009181 }
9182 }
9183 }
9184 }
9185 }
9186
9187 return 0;
9188}
9189
Dan Gohman81b28ce2008-09-16 18:46:06 +00009190/// visitSelectInstWithICmp - Visit a SelectInst that has an
9191/// ICmpInst as its first operand.
9192///
9193Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9194 ICmpInst *ICI) {
9195 bool Changed = false;
9196 ICmpInst::Predicate Pred = ICI->getPredicate();
9197 Value *CmpLHS = ICI->getOperand(0);
9198 Value *CmpRHS = ICI->getOperand(1);
9199 Value *TrueVal = SI.getTrueValue();
9200 Value *FalseVal = SI.getFalseValue();
9201
9202 // Check cases where the comparison is with a constant that
9203 // can be adjusted to fit the min/max idiom. We may edit ICI in
9204 // place here, so make sure the select is the only user.
9205 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009206 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009207 switch (Pred) {
9208 default: break;
9209 case ICmpInst::ICMP_ULT:
9210 case ICmpInst::ICMP_SLT: {
9211 // X < MIN ? T : F --> F
9212 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9213 return ReplaceInstUsesWith(SI, FalseVal);
9214 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009215 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009216 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9217 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9218 Pred = ICmpInst::getSwappedPredicate(Pred);
9219 CmpRHS = AdjustedRHS;
9220 std::swap(FalseVal, TrueVal);
9221 ICI->setPredicate(Pred);
9222 ICI->setOperand(1, CmpRHS);
9223 SI.setOperand(1, TrueVal);
9224 SI.setOperand(2, FalseVal);
9225 Changed = true;
9226 }
9227 break;
9228 }
9229 case ICmpInst::ICMP_UGT:
9230 case ICmpInst::ICMP_SGT: {
9231 // X > MAX ? T : F --> F
9232 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9233 return ReplaceInstUsesWith(SI, FalseVal);
9234 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009235 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009236 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9237 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9238 Pred = ICmpInst::getSwappedPredicate(Pred);
9239 CmpRHS = AdjustedRHS;
9240 std::swap(FalseVal, TrueVal);
9241 ICI->setPredicate(Pred);
9242 ICI->setOperand(1, CmpRHS);
9243 SI.setOperand(1, TrueVal);
9244 SI.setOperand(2, FalseVal);
9245 Changed = true;
9246 }
9247 break;
9248 }
9249 }
9250
Dan Gohman1975d032008-10-30 20:40:10 +00009251 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9252 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009253 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009254 if (match(TrueVal, m_ConstantInt<-1>()) &&
9255 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009256 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009257 else if (match(TrueVal, m_ConstantInt<0>()) &&
9258 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009259 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9260
Dan Gohman1975d032008-10-30 20:40:10 +00009261 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9262 // If we are just checking for a icmp eq of a single bit and zext'ing it
9263 // to an integer, then shift the bit to the appropriate place and then
9264 // cast to integer to avoid the comparison.
9265 const APInt &Op1CV = CI->getValue();
9266
9267 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9268 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9269 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009270 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009271 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009272 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009273 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009274 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009275 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009276 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009277 if (In->getType() != SI.getType())
9278 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009279 true/*SExt*/, "tmp", ICI);
9280
9281 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009282 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009283 In->getName()+".not"), *ICI);
9284
9285 return ReplaceInstUsesWith(SI, In);
9286 }
9287 }
9288 }
9289
Dan Gohman81b28ce2008-09-16 18:46:06 +00009290 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9291 // Transform (X == Y) ? X : Y -> Y
9292 if (Pred == ICmpInst::ICMP_EQ)
9293 return ReplaceInstUsesWith(SI, FalseVal);
9294 // Transform (X != Y) ? X : Y -> X
9295 if (Pred == ICmpInst::ICMP_NE)
9296 return ReplaceInstUsesWith(SI, TrueVal);
9297 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9298
9299 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9300 // Transform (X == Y) ? Y : X -> X
9301 if (Pred == ICmpInst::ICMP_EQ)
9302 return ReplaceInstUsesWith(SI, FalseVal);
9303 // Transform (X != Y) ? Y : X -> Y
9304 if (Pred == ICmpInst::ICMP_NE)
9305 return ReplaceInstUsesWith(SI, TrueVal);
9306 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9307 }
9308
9309 /// NOTE: if we wanted to, this is where to detect integer ABS
9310
9311 return Changed ? &SI : 0;
9312}
9313
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009314
Chris Lattner7f239582009-10-22 00:17:26 +00009315/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9316/// PHI node (but the two may be in different blocks). See if the true/false
9317/// values (V) are live in all of the predecessor blocks of the PHI. For
9318/// example, cases like this cannot be mapped:
9319///
9320/// X = phi [ C1, BB1], [C2, BB2]
9321/// Y = add
9322/// Z = select X, Y, 0
9323///
9324/// because Y is not live in BB1/BB2.
9325///
9326static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9327 const SelectInst &SI) {
9328 // If the value is a non-instruction value like a constant or argument, it
9329 // can always be mapped.
9330 const Instruction *I = dyn_cast<Instruction>(V);
9331 if (I == 0) return true;
9332
9333 // If V is a PHI node defined in the same block as the condition PHI, we can
9334 // map the arguments.
9335 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9336
9337 if (const PHINode *VP = dyn_cast<PHINode>(I))
9338 if (VP->getParent() == CondPHI->getParent())
9339 return true;
9340
9341 // Otherwise, if the PHI and select are defined in the same block and if V is
9342 // defined in a different block, then we can transform it.
9343 if (SI.getParent() == CondPHI->getParent() &&
9344 I->getParent() != CondPHI->getParent())
9345 return true;
9346
9347 // Otherwise we have a 'hard' case and we can't tell without doing more
9348 // detailed dominator based analysis, punt.
9349 return false;
9350}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009351
Chris Lattner3d69f462004-03-12 05:52:32 +00009352Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009353 Value *CondVal = SI.getCondition();
9354 Value *TrueVal = SI.getTrueValue();
9355 Value *FalseVal = SI.getFalseValue();
9356
9357 // select true, X, Y -> X
9358 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009359 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009360 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009361
9362 // select C, X, X -> X
9363 if (TrueVal == FalseVal)
9364 return ReplaceInstUsesWith(SI, TrueVal);
9365
Chris Lattnere87597f2004-10-16 18:11:37 +00009366 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9367 return ReplaceInstUsesWith(SI, FalseVal);
9368 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9369 return ReplaceInstUsesWith(SI, TrueVal);
9370 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9371 if (isa<Constant>(TrueVal))
9372 return ReplaceInstUsesWith(SI, TrueVal);
9373 else
9374 return ReplaceInstUsesWith(SI, FalseVal);
9375 }
9376
Owen Anderson1d0be152009-08-13 21:58:54 +00009377 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009378 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009379 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009380 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009381 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009382 } else {
9383 // Change: A = select B, false, C --> A = and !B, C
9384 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009385 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009386 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009387 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009388 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009389 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009390 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009391 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009392 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009393 } else {
9394 // Change: A = select B, C, true --> A = or !B, C
9395 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009396 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009397 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009398 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009399 }
9400 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009401
9402 // select a, b, a -> a&b
9403 // select a, a, b -> a|b
9404 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009405 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009406 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009407 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009408 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009409
Chris Lattner2eefe512004-04-09 19:05:30 +00009410 // Selecting between two integer constants?
9411 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9412 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009413 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009414 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009415 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009416 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009417 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009418 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009419 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009420 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009421 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009422 }
Chris Lattner457dd822004-06-09 07:59:58 +00009423
Reid Spencere4d87aa2006-12-23 06:05:41 +00009424 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009425 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009426 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009427 // non-constant value, eliminate this whole mess. This corresponds to
9428 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009429 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009430 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009431 cast<Constant>(IC->getOperand(1))->isNullValue())
9432 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9433 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009434 isa<ConstantInt>(ICA->getOperand(1)) &&
9435 (ICA->getOperand(1) == TrueValC ||
9436 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009437 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9438 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009439 // know whether we have a icmp_ne or icmp_eq and whether the
9440 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009441 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009442 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009443 Value *V = ICA;
9444 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009445 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009446 Instruction::Xor, V, ICA->getOperand(1)), SI);
9447 return ReplaceInstUsesWith(SI, V);
9448 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009449 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009450 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009451
9452 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009453 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9454 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009455 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009456 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9457 // This is not safe in general for floating point:
9458 // consider X== -0, Y== +0.
9459 // It becomes safe if either operand is a nonzero constant.
9460 ConstantFP *CFPt, *CFPf;
9461 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9462 !CFPt->getValueAPF().isZero()) ||
9463 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9464 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009465 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009466 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009467 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009468 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009469 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009470 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009471
Reid Spencere4d87aa2006-12-23 06:05:41 +00009472 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009473 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009474 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9475 // This is not safe in general for floating point:
9476 // consider X== -0, Y== +0.
9477 // It becomes safe if either operand is a nonzero constant.
9478 ConstantFP *CFPt, *CFPf;
9479 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9480 !CFPt->getValueAPF().isZero()) ||
9481 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9482 !CFPf->getValueAPF().isZero()))
9483 return ReplaceInstUsesWith(SI, FalseVal);
9484 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009485 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009486 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9487 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009488 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009489 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009490 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009491 }
9492
9493 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009494 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9495 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9496 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009497
Chris Lattner87875da2005-01-13 22:52:24 +00009498 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9499 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9500 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009501 Instruction *AddOp = 0, *SubOp = 0;
9502
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009503 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9504 if (TI->getOpcode() == FI->getOpcode())
9505 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9506 return IV;
9507
9508 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9509 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009510 if ((TI->getOpcode() == Instruction::Sub &&
9511 FI->getOpcode() == Instruction::Add) ||
9512 (TI->getOpcode() == Instruction::FSub &&
9513 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009514 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009515 } else if ((FI->getOpcode() == Instruction::Sub &&
9516 TI->getOpcode() == Instruction::Add) ||
9517 (FI->getOpcode() == Instruction::FSub &&
9518 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009519 AddOp = TI; SubOp = FI;
9520 }
9521
9522 if (AddOp) {
9523 Value *OtherAddOp = 0;
9524 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9525 OtherAddOp = AddOp->getOperand(1);
9526 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9527 OtherAddOp = AddOp->getOperand(0);
9528 }
9529
9530 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009531 // So at this point we know we have (Y -> OtherAddOp):
9532 // select C, (add X, Y), (sub X, Z)
9533 Value *NegVal; // Compute -Z
9534 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009535 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009536 } else {
9537 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009538 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009539 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009540 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009541
9542 Value *NewTrueOp = OtherAddOp;
9543 Value *NewFalseOp = NegVal;
9544 if (AddOp != TI)
9545 std::swap(NewTrueOp, NewFalseOp);
9546 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009547 SelectInst::Create(CondVal, NewTrueOp,
9548 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009549
9550 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009551 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009552 }
9553 }
9554 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009555
Chris Lattnere576b912004-04-09 23:46:01 +00009556 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009557 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009558 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9559 if (FoldI)
9560 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009561 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009562
Chris Lattner7f239582009-10-22 00:17:26 +00009563 // See if we can fold the select into a phi node if the condition is a select.
9564 if (isa<PHINode>(SI.getCondition()))
9565 // The true/false values have to be live in the PHI predecessor's blocks.
9566 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9567 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9568 if (Instruction *NV = FoldOpIntoPhi(SI))
9569 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00009570
Chris Lattnera1df33c2005-04-24 07:30:14 +00009571 if (BinaryOperator::isNot(CondVal)) {
9572 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9573 SI.setOperand(1, FalseVal);
9574 SI.setOperand(2, TrueVal);
9575 return &SI;
9576 }
9577
Chris Lattner3d69f462004-03-12 05:52:32 +00009578 return 0;
9579}
9580
Dan Gohmaneee962e2008-04-10 18:43:06 +00009581/// EnforceKnownAlignment - If the specified pointer points to an object that
9582/// we control, modify the object's alignment to PrefAlign. This isn't
9583/// often possible though. If alignment is important, a more reliable approach
9584/// is to simply align all global variables and allocation instructions to
9585/// their preferred alignment from the beginning.
9586///
9587static unsigned EnforceKnownAlignment(Value *V,
9588 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009589
Dan Gohmaneee962e2008-04-10 18:43:06 +00009590 User *U = dyn_cast<User>(V);
9591 if (!U) return Align;
9592
Dan Gohmanca178902009-07-17 20:47:02 +00009593 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009594 default: break;
9595 case Instruction::BitCast:
9596 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9597 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009598 // If all indexes are zero, it is just the alignment of the base pointer.
9599 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009600 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009601 if (!isa<Constant>(*i) ||
9602 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009603 AllZeroOperands = false;
9604 break;
9605 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009606
9607 if (AllZeroOperands) {
9608 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009609 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009610 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009611 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009612 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009613 }
9614
9615 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9616 // If there is a large requested alignment and we can, bump up the alignment
9617 // of the global.
9618 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009619 if (GV->getAlignment() >= PrefAlign)
9620 Align = GV->getAlignment();
9621 else {
9622 GV->setAlignment(PrefAlign);
9623 Align = PrefAlign;
9624 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009625 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009626 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9627 // If there is a requested alignment and if this is an alloca, round up.
9628 if (AI->getAlignment() >= PrefAlign)
9629 Align = AI->getAlignment();
9630 else {
9631 AI->setAlignment(PrefAlign);
9632 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009633 }
9634 }
9635
9636 return Align;
9637}
9638
9639/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9640/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9641/// and it is more than the alignment of the ultimate object, see if we can
9642/// increase the alignment of the ultimate object, making this check succeed.
9643unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9644 unsigned PrefAlign) {
9645 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9646 sizeof(PrefAlign) * CHAR_BIT;
9647 APInt Mask = APInt::getAllOnesValue(BitWidth);
9648 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9649 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9650 unsigned TrailZ = KnownZero.countTrailingOnes();
9651 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9652
9653 if (PrefAlign > Align)
9654 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9655
9656 // We don't need to make any adjustment.
9657 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009658}
9659
Chris Lattnerf497b022008-01-13 23:50:23 +00009660Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009661 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009662 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009663 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009664 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009665
9666 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009667 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009668 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009669 return MI;
9670 }
9671
9672 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9673 // load/store.
9674 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9675 if (MemOpLength == 0) return 0;
9676
Chris Lattner37ac6082008-01-14 00:28:35 +00009677 // Source and destination pointer types are always "i8*" for intrinsic. See
9678 // if the size is something we can handle with a single primitive load/store.
9679 // A single load+store correctly handles overlapping memory in the memmove
9680 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009681 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009682 if (Size == 0) return MI; // Delete this mem transfer.
9683
9684 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009685 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009686
Chris Lattner37ac6082008-01-14 00:28:35 +00009687 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009688 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009689 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009690
9691 // Memcpy forces the use of i8* for the source and destination. That means
9692 // that if you're using memcpy to move one double around, you'll get a cast
9693 // from double* to i8*. We'd much rather use a double load+store rather than
9694 // an i64 load+store, here because this improves the odds that the source or
9695 // dest address will be promotable. See if we can find a better type than the
9696 // integer datatype.
9697 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9698 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009699 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009700 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9701 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009702 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009703 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9704 if (STy->getNumElements() == 1)
9705 SrcETy = STy->getElementType(0);
9706 else
9707 break;
9708 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9709 if (ATy->getNumElements() == 1)
9710 SrcETy = ATy->getElementType();
9711 else
9712 break;
9713 } else
9714 break;
9715 }
9716
Dan Gohman8f8e2692008-05-23 01:52:21 +00009717 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009718 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009719 }
9720 }
9721
9722
Chris Lattnerf497b022008-01-13 23:50:23 +00009723 // If the memcpy/memmove provides better alignment info than we can
9724 // infer, use it.
9725 SrcAlign = std::max(SrcAlign, CopyAlign);
9726 DstAlign = std::max(DstAlign, CopyAlign);
9727
Chris Lattner08142f22009-08-30 19:47:22 +00009728 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9729 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009730 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9731 InsertNewInstBefore(L, *MI);
9732 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9733
9734 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009735 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009736 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009737}
Chris Lattner3d69f462004-03-12 05:52:32 +00009738
Chris Lattner69ea9d22008-04-30 06:39:11 +00009739Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9740 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009741 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009742 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009743 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009744 return MI;
9745 }
9746
9747 // Extract the length and alignment and fill if they are constant.
9748 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9749 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009750 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009751 return 0;
9752 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009753 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009754
9755 // If the length is zero, this is a no-op
9756 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9757
9758 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9759 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009760 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009761
9762 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009763 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009764
9765 // Alignment 0 is identity for alignment 1 for memset, but not store.
9766 if (Alignment == 0) Alignment = 1;
9767
9768 // Extract the fill value and store.
9769 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009770 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009771 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009772
9773 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009774 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009775 return MI;
9776 }
9777
9778 return 0;
9779}
9780
9781
Chris Lattner8b0ea312006-01-13 20:11:04 +00009782/// visitCallInst - CallInst simplification. This mostly only handles folding
9783/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9784/// the heavy lifting.
9785///
Chris Lattner9fe38862003-06-19 17:00:31 +00009786Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00009787 if (isFreeCall(&CI))
9788 return visitFree(CI);
9789
Chris Lattneraab6ec42009-05-13 17:39:14 +00009790 // If the caller function is nounwind, mark the call as nounwind, even if the
9791 // callee isn't.
9792 if (CI.getParent()->getParent()->doesNotThrow() &&
9793 !CI.doesNotThrow()) {
9794 CI.setDoesNotThrow();
9795 return &CI;
9796 }
9797
Chris Lattner8b0ea312006-01-13 20:11:04 +00009798 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9799 if (!II) return visitCallSite(&CI);
9800
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009801 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9802 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009803 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009804 bool Changed = false;
9805
9806 // memmove/cpy/set of zero bytes is a noop.
9807 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9808 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9809
Chris Lattner35b9e482004-10-12 04:52:52 +00009810 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009811 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009812 // Replace the instruction with just byte operations. We would
9813 // transform other cases to loads/stores, but we don't know if
9814 // alignment is sufficient.
9815 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009816 }
9817
Chris Lattner35b9e482004-10-12 04:52:52 +00009818 // If we have a memmove and the source operation is a constant global,
9819 // then the source and dest pointers can't alias, so we can change this
9820 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009821 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009822 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9823 if (GVSrc->isConstant()) {
9824 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009825 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9826 const Type *Tys[1];
9827 Tys[0] = CI.getOperand(3)->getType();
9828 CI.setOperand(0,
9829 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009830 Changed = true;
9831 }
Chris Lattnera935db82008-05-28 05:30:41 +00009832
9833 // memmove(x,x,size) -> noop.
9834 if (MMI->getSource() == MMI->getDest())
9835 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009836 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009837
Chris Lattner95a959d2006-03-06 20:18:44 +00009838 // If we can determine a pointer alignment that is bigger than currently
9839 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009840 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009841 if (Instruction *I = SimplifyMemTransfer(MI))
9842 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009843 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9844 if (Instruction *I = SimplifyMemSet(MSI))
9845 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009846 }
9847
Chris Lattner8b0ea312006-01-13 20:11:04 +00009848 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009849 }
9850
9851 switch (II->getIntrinsicID()) {
9852 default: break;
9853 case Intrinsic::bswap:
9854 // bswap(bswap(x)) -> x
9855 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9856 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9857 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9858 break;
9859 case Intrinsic::ppc_altivec_lvx:
9860 case Intrinsic::ppc_altivec_lvxl:
9861 case Intrinsic::x86_sse_loadu_ps:
9862 case Intrinsic::x86_sse2_loadu_pd:
9863 case Intrinsic::x86_sse2_loadu_dq:
9864 // Turn PPC lvx -> load if the pointer is known aligned.
9865 // Turn X86 loadups -> load if the pointer is known aligned.
9866 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009867 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9868 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009869 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009870 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009871 break;
9872 case Intrinsic::ppc_altivec_stvx:
9873 case Intrinsic::ppc_altivec_stvxl:
9874 // Turn stvx -> store if the pointer is known aligned.
9875 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9876 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009877 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009878 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009879 return new StoreInst(II->getOperand(1), Ptr);
9880 }
9881 break;
9882 case Intrinsic::x86_sse_storeu_ps:
9883 case Intrinsic::x86_sse2_storeu_pd:
9884 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009885 // Turn X86 storeu -> store if the pointer is known aligned.
9886 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9887 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009888 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009889 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009890 return new StoreInst(II->getOperand(2), Ptr);
9891 }
9892 break;
9893
9894 case Intrinsic::x86_sse_cvttss2si: {
9895 // These intrinsics only demands the 0th element of its input vector. If
9896 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009897 unsigned VWidth =
9898 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9899 APInt DemandedElts(VWidth, 1);
9900 APInt UndefElts(VWidth, 0);
9901 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009902 UndefElts)) {
9903 II->setOperand(1, V);
9904 return II;
9905 }
9906 break;
9907 }
9908
9909 case Intrinsic::ppc_altivec_vperm:
9910 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9911 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9912 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009913
Chris Lattner0521e3c2008-06-18 04:33:20 +00009914 // Check that all of the elements are integer constants or undefs.
9915 bool AllEltsOk = true;
9916 for (unsigned i = 0; i != 16; ++i) {
9917 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9918 !isa<UndefValue>(Mask->getOperand(i))) {
9919 AllEltsOk = false;
9920 break;
9921 }
9922 }
9923
9924 if (AllEltsOk) {
9925 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009926 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9927 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009928 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009929
Chris Lattner0521e3c2008-06-18 04:33:20 +00009930 // Only extract each element once.
9931 Value *ExtractedElts[32];
9932 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9933
Chris Lattnere2ed0572006-04-06 19:19:17 +00009934 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009935 if (isa<UndefValue>(Mask->getOperand(i)))
9936 continue;
9937 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9938 Idx &= 31; // Match the hardware behavior.
9939
9940 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009941 ExtractedElts[Idx] =
9942 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9943 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9944 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009945 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009946
Chris Lattner0521e3c2008-06-18 04:33:20 +00009947 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009948 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9949 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9950 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009951 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009952 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009953 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009954 }
9955 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009956
Chris Lattner0521e3c2008-06-18 04:33:20 +00009957 case Intrinsic::stackrestore: {
9958 // If the save is right next to the restore, remove the restore. This can
9959 // happen when variable allocas are DCE'd.
9960 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9961 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9962 BasicBlock::iterator BI = SS;
9963 if (&*++BI == II)
9964 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009965 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009966 }
9967
9968 // Scan down this block to see if there is another stack restore in the
9969 // same block without an intervening call/alloca.
9970 BasicBlock::iterator BI = II;
9971 TerminatorInst *TI = II->getParent()->getTerminator();
9972 bool CannotRemove = false;
9973 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009974 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009975 CannotRemove = true;
9976 break;
9977 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009978 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9979 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9980 // If there is a stackrestore below this one, remove this one.
9981 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9982 return EraseInstFromFunction(CI);
9983 // Otherwise, ignore the intrinsic.
9984 } else {
9985 // If we found a non-intrinsic call, we can't remove the stack
9986 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009987 CannotRemove = true;
9988 break;
9989 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009990 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009991 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009992
9993 // If the stack restore is in a return/unwind block and if there are no
9994 // allocas or calls between the restore and the return, nuke the restore.
9995 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9996 return EraseInstFromFunction(CI);
9997 break;
9998 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009999 }
10000
Chris Lattner8b0ea312006-01-13 20:11:04 +000010001 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010002}
10003
10004// InvokeInst simplification
10005//
10006Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010007 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010008}
10009
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010010/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10011/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010012static bool isSafeToEliminateVarargsCast(const CallSite CS,
10013 const CastInst * const CI,
10014 const TargetData * const TD,
10015 const int ix) {
10016 if (!CI->isLosslessCast())
10017 return false;
10018
10019 // The size of ByVal arguments is derived from the type, so we
10020 // can't change to a type with a different size. If the size were
10021 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010022 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010023 return true;
10024
10025 const Type* SrcTy =
10026 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10027 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10028 if (!SrcTy->isSized() || !DstTy->isSized())
10029 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010030 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010031 return false;
10032 return true;
10033}
10034
Chris Lattnera44d8a22003-10-07 22:32:43 +000010035// visitCallSite - Improvements for call and invoke instructions.
10036//
10037Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010038 bool Changed = false;
10039
10040 // If the callee is a constexpr cast of a function, attempt to move the cast
10041 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010042 if (transformConstExprCastCall(CS)) return 0;
10043
Chris Lattner6c266db2003-10-07 22:54:13 +000010044 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010045
Chris Lattner08b22ec2005-05-13 07:09:09 +000010046 if (Function *CalleeF = dyn_cast<Function>(Callee))
10047 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10048 Instruction *OldCall = CS.getInstruction();
10049 // If the call and callee calling conventions don't match, this call must
10050 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010051 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010052 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010053 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010054 // If OldCall dues not return void then replaceAllUsesWith undef.
10055 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010056 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010057 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010058 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10059 return EraseInstFromFunction(*OldCall);
10060 return 0;
10061 }
10062
Chris Lattner17be6352004-10-18 02:59:09 +000010063 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10064 // This instruction is not reachable, just remove it. We insert a store to
10065 // undef so that we know that this code is not reachable, despite the fact
10066 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010067 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010068 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010069 CS.getInstruction());
10070
Devang Patel228ebd02009-10-13 22:56:32 +000010071 // If CS dues not return void then replaceAllUsesWith undef.
10072 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010073 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010074 CS.getInstruction()->
10075 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010076
10077 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10078 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010079 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010080 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010081 }
Chris Lattner17be6352004-10-18 02:59:09 +000010082 return EraseInstFromFunction(*CS.getInstruction());
10083 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010084
Duncan Sandscdb6d922007-09-17 10:26:40 +000010085 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10086 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10087 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10088 return transformCallThroughTrampoline(CS);
10089
Chris Lattner6c266db2003-10-07 22:54:13 +000010090 const PointerType *PTy = cast<PointerType>(Callee->getType());
10091 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10092 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010093 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010094 // See if we can optimize any arguments passed through the varargs area of
10095 // the call.
10096 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010097 E = CS.arg_end(); I != E; ++I, ++ix) {
10098 CastInst *CI = dyn_cast<CastInst>(*I);
10099 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10100 *I = CI->getOperand(0);
10101 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010102 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010103 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010104 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010105
Duncan Sandsf0c33542007-12-19 21:13:37 +000010106 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010107 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010108 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010109 Changed = true;
10110 }
10111
Chris Lattner6c266db2003-10-07 22:54:13 +000010112 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010113}
10114
Chris Lattner9fe38862003-06-19 17:00:31 +000010115// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10116// attempt to move the cast to the arguments of the call/invoke.
10117//
10118bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10119 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10120 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010121 if (CE->getOpcode() != Instruction::BitCast ||
10122 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010123 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010124 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010125 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010126 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010127
10128 // Okay, this is a cast from a function to a different type. Unless doing so
10129 // would cause a type conversion of one of our arguments, change this call to
10130 // be a direct call with arguments casted to the appropriate types.
10131 //
10132 const FunctionType *FT = Callee->getFunctionType();
10133 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010134 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010135
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010136 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010137 return false; // TODO: Handle multiple return values.
10138
Chris Lattnerf78616b2004-01-14 06:06:08 +000010139 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010140 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010141 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010142 // Conversion is ok if changing from one pointer type to another or from
10143 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010144 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010145 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010146 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010147 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010148 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010149
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010150 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010151 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010152 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010153 return false; // Cannot transform this return value.
10154
Chris Lattner58d74912008-03-12 17:45:29 +000010155 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010156 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010157 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010158 return false; // Attribute not compatible with transformed value.
10159 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010160
Chris Lattnerf78616b2004-01-14 06:06:08 +000010161 // If the callsite is an invoke instruction, and the return value is used by
10162 // a PHI node in a successor, we cannot change the return type of the call
10163 // because there is no place to put the cast instruction (without breaking
10164 // the critical edge). Bail out in this case.
10165 if (!Caller->use_empty())
10166 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10167 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10168 UI != E; ++UI)
10169 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10170 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010171 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010172 return false;
10173 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010174
10175 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10176 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010177
Chris Lattner9fe38862003-06-19 17:00:31 +000010178 CallSite::arg_iterator AI = CS.arg_begin();
10179 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10180 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010181 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010182
10183 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010184 return false; // Cannot transform this parameter value.
10185
Devang Patel19c87462008-09-26 22:53:05 +000010186 if (CallerPAL.getParamAttributes(i + 1)
10187 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010188 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010189
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010190 // Converting from one pointer type to another or between a pointer and an
10191 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010192 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010193 (TD && ((isa<PointerType>(ParamTy) ||
10194 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10195 (isa<PointerType>(ActTy) ||
10196 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010197 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010198 }
10199
10200 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010201 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010202 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010203
Chris Lattner58d74912008-03-12 17:45:29 +000010204 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10205 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010206 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010207 // won't be dropping them. Check that these extra arguments have attributes
10208 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010209 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10210 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010211 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010212 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010213 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010214 return false;
10215 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010216
Chris Lattner9fe38862003-06-19 17:00:31 +000010217 // Okay, we decided that this is a safe thing to do: go ahead and start
10218 // inserting cast instructions as necessary...
10219 std::vector<Value*> Args;
10220 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010221 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010222 attrVec.reserve(NumCommonArgs);
10223
10224 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010225 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010226
10227 // If the return value is not being used, the type may not be compatible
10228 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010229 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010230
10231 // Add the new return attributes.
10232 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010233 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010234
10235 AI = CS.arg_begin();
10236 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10237 const Type *ParamTy = FT->getParamType(i);
10238 if ((*AI)->getType() == ParamTy) {
10239 Args.push_back(*AI);
10240 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010241 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010242 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010243 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010244 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010245
10246 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010247 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010248 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010249 }
10250
10251 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010252 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010253 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010254 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010255
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010256 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010257 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010258 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010259 errs() << "WARNING: While resolving call to function '"
10260 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010261 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010262 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010263 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10264 const Type *PTy = getPromotedType((*AI)->getType());
10265 if (PTy != (*AI)->getType()) {
10266 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010267 Instruction::CastOps opcode =
10268 CastInst::getCastOpcode(*AI, false, PTy, false);
10269 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010270 } else {
10271 Args.push_back(*AI);
10272 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010273
Duncan Sandse1e520f2008-01-13 08:02:44 +000010274 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010275 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010276 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010277 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010278 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010279 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010280
Devang Patel19c87462008-09-26 22:53:05 +000010281 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10282 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10283
Devang Patel9674d152009-10-14 17:29:00 +000010284 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010285 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010286
Eric Christophera66297a2009-07-25 02:45:27 +000010287 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10288 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010289
Chris Lattner9fe38862003-06-19 17:00:31 +000010290 Instruction *NC;
10291 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010292 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010293 Args.begin(), Args.end(),
10294 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010295 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010296 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010297 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010298 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10299 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010300 CallInst *CI = cast<CallInst>(Caller);
10301 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010302 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010303 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010304 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010305 }
10306
Chris Lattner6934a042007-02-11 01:23:03 +000010307 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010308 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010309 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010310 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010311 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010312 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010313 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010314
10315 // If this is an invoke instruction, we should insert it after the first
10316 // non-phi, instruction in the normal successor block.
10317 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010318 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010319 InsertNewInstBefore(NC, *I);
10320 } else {
10321 // Otherwise, it's a call, just insert cast right after the call instr
10322 InsertNewInstBefore(NC, *Caller);
10323 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010324 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010325 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010326 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010327 }
10328 }
10329
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010330
Chris Lattner931f8f32009-08-31 05:17:58 +000010331 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010332 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010333
10334 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010335 return true;
10336}
10337
Duncan Sandscdb6d922007-09-17 10:26:40 +000010338// transformCallThroughTrampoline - Turn a call to a function created by the
10339// init_trampoline intrinsic into a direct call to the underlying function.
10340//
10341Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10342 Value *Callee = CS.getCalledValue();
10343 const PointerType *PTy = cast<PointerType>(Callee->getType());
10344 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010345 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010346
10347 // If the call already has the 'nest' attribute somewhere then give up -
10348 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010349 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010350 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010351
10352 IntrinsicInst *Tramp =
10353 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10354
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010355 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010356 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10357 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10358
Devang Patel05988662008-09-25 21:00:45 +000010359 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010360 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010361 unsigned NestIdx = 1;
10362 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010363 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010364
10365 // Look for a parameter marked with the 'nest' attribute.
10366 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10367 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010368 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010369 // Record the parameter type and any other attributes.
10370 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010371 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010372 break;
10373 }
10374
10375 if (NestTy) {
10376 Instruction *Caller = CS.getInstruction();
10377 std::vector<Value*> NewArgs;
10378 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10379
Devang Patel05988662008-09-25 21:00:45 +000010380 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010381 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010382
Duncan Sandscdb6d922007-09-17 10:26:40 +000010383 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010384 // mean appending it. Likewise for attributes.
10385
Devang Patel19c87462008-09-26 22:53:05 +000010386 // Add any result attributes.
10387 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010388 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010389
Duncan Sandscdb6d922007-09-17 10:26:40 +000010390 {
10391 unsigned Idx = 1;
10392 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10393 do {
10394 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010395 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010396 Value *NestVal = Tramp->getOperand(3);
10397 if (NestVal->getType() != NestTy)
10398 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10399 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010400 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010401 }
10402
10403 if (I == E)
10404 break;
10405
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010406 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010407 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010408 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010409 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010410 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010411
10412 ++Idx, ++I;
10413 } while (1);
10414 }
10415
Devang Patel19c87462008-09-26 22:53:05 +000010416 // Add any function attributes.
10417 if (Attributes Attr = Attrs.getFnAttributes())
10418 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10419
Duncan Sandscdb6d922007-09-17 10:26:40 +000010420 // The trampoline may have been bitcast to a bogus type (FTy).
10421 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010422 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010423
Duncan Sandscdb6d922007-09-17 10:26:40 +000010424 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010425 NewTypes.reserve(FTy->getNumParams()+1);
10426
Duncan Sandscdb6d922007-09-17 10:26:40 +000010427 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010428 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010429 {
10430 unsigned Idx = 1;
10431 FunctionType::param_iterator I = FTy->param_begin(),
10432 E = FTy->param_end();
10433
10434 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010435 if (Idx == NestIdx)
10436 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010437 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010438
10439 if (I == E)
10440 break;
10441
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010442 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010443 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010444
10445 ++Idx, ++I;
10446 } while (1);
10447 }
10448
10449 // Replace the trampoline call with a direct call. Let the generic
10450 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010451 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010452 FTy->isVarArg());
10453 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010454 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010455 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010456 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010457 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10458 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010459
10460 Instruction *NewCaller;
10461 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010462 NewCaller = InvokeInst::Create(NewCallee,
10463 II->getNormalDest(), II->getUnwindDest(),
10464 NewArgs.begin(), NewArgs.end(),
10465 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010466 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010467 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010468 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010469 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10470 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010471 if (cast<CallInst>(Caller)->isTailCall())
10472 cast<CallInst>(NewCaller)->setTailCall();
10473 cast<CallInst>(NewCaller)->
10474 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010475 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010476 }
Devang Patel9674d152009-10-14 17:29:00 +000010477 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010478 Caller->replaceAllUsesWith(NewCaller);
10479 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010480 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010481 return 0;
10482 }
10483 }
10484
10485 // Replace the trampoline call with a direct call. Since there is no 'nest'
10486 // parameter, there is no need to adjust the argument list. Let the generic
10487 // code sort out any function type mismatches.
10488 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010489 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010490 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010491 CS.setCalledFunction(NewCallee);
10492 return CS.getInstruction();
10493}
10494
Dan Gohman9ad29202009-09-16 16:50:24 +000010495/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10496/// 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 +000010497/// and a single binop.
10498Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10499 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010500 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010501 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010502 Value *LHSVal = FirstInst->getOperand(0);
10503 Value *RHSVal = FirstInst->getOperand(1);
10504
10505 const Type *LHSType = LHSVal->getType();
10506 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010507
Dan Gohman9ad29202009-09-16 16:50:24 +000010508 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010509 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010510 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010511 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010512 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010513 // types or GEP's with different index types.
10514 I->getOperand(0)->getType() != LHSType ||
10515 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010516 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010517
10518 // If they are CmpInst instructions, check their predicates
10519 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10520 if (cast<CmpInst>(I)->getPredicate() !=
10521 cast<CmpInst>(FirstInst)->getPredicate())
10522 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010523
10524 // Keep track of which operand needs a phi node.
10525 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10526 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010527 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010528
10529 // If both LHS and RHS would need a PHI, don't do this transformation,
10530 // because it would increase the number of PHIs entering the block,
10531 // which leads to higher register pressure. This is especially
10532 // bad when the PHIs are in the header of a loop.
10533 if (!LHSVal && !RHSVal)
10534 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010535
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010536 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010537
Chris Lattner7da52b22006-11-01 04:51:18 +000010538 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010539 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010540 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010541 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010542 NewLHS = PHINode::Create(LHSType,
10543 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010544 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10545 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010546 InsertNewInstBefore(NewLHS, PN);
10547 LHSVal = NewLHS;
10548 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010549
10550 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010551 NewRHS = PHINode::Create(RHSType,
10552 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010553 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10554 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010555 InsertNewInstBefore(NewRHS, PN);
10556 RHSVal = NewRHS;
10557 }
10558
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010559 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010560 if (NewLHS || NewRHS) {
10561 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10562 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10563 if (NewLHS) {
10564 Value *NewInLHS = InInst->getOperand(0);
10565 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10566 }
10567 if (NewRHS) {
10568 Value *NewInRHS = InInst->getOperand(1);
10569 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10570 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010571 }
10572 }
10573
Chris Lattner7da52b22006-11-01 04:51:18 +000010574 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010575 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010576 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010577 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010578 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010579}
10580
Chris Lattner05f18922008-12-01 02:34:36 +000010581Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10582 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10583
10584 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10585 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010586 // This is true if all GEP bases are allocas and if all indices into them are
10587 // constants.
10588 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010589
10590 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010591 // more than one phi, which leads to higher register pressure. This is
10592 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010593 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010594
Dan Gohman9ad29202009-09-16 16:50:24 +000010595 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010596 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10597 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10598 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10599 GEP->getNumOperands() != FirstInst->getNumOperands())
10600 return 0;
10601
Chris Lattner36d3e322009-02-21 00:46:50 +000010602 // Keep track of whether or not all GEPs are of alloca pointers.
10603 if (AllBasePointersAreAllocas &&
10604 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10605 !GEP->hasAllConstantIndices()))
10606 AllBasePointersAreAllocas = false;
10607
Chris Lattner05f18922008-12-01 02:34:36 +000010608 // Compare the operand lists.
10609 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10610 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10611 continue;
10612
10613 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10614 // if one of the PHIs has a constant for the index. The index may be
10615 // substantially cheaper to compute for the constants, so making it a
10616 // variable index could pessimize the path. This also handles the case
10617 // for struct indices, which must always be constant.
10618 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10619 isa<ConstantInt>(GEP->getOperand(op)))
10620 return 0;
10621
10622 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10623 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010624
10625 // If we already needed a PHI for an earlier operand, and another operand
10626 // also requires a PHI, we'd be introducing more PHIs than we're
10627 // eliminating, which increases register pressure on entry to the PHI's
10628 // block.
10629 if (NeededPhi)
10630 return 0;
10631
Chris Lattner05f18922008-12-01 02:34:36 +000010632 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010633 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010634 }
10635 }
10636
Chris Lattner36d3e322009-02-21 00:46:50 +000010637 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010638 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010639 // offset calculation, but all the predecessors will have to materialize the
10640 // stack address into a register anyway. We'd actually rather *clone* the
10641 // load up into the predecessors so that we have a load of a gep of an alloca,
10642 // which can usually all be folded into the load.
10643 if (AllBasePointersAreAllocas)
10644 return 0;
10645
Chris Lattner05f18922008-12-01 02:34:36 +000010646 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10647 // that is variable.
10648 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10649
10650 bool HasAnyPHIs = false;
10651 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10652 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10653 Value *FirstOp = FirstInst->getOperand(i);
10654 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10655 FirstOp->getName()+".pn");
10656 InsertNewInstBefore(NewPN, PN);
10657
10658 NewPN->reserveOperandSpace(e);
10659 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10660 OperandPhis[i] = NewPN;
10661 FixedOperands[i] = NewPN;
10662 HasAnyPHIs = true;
10663 }
10664
10665
10666 // Add all operands to the new PHIs.
10667 if (HasAnyPHIs) {
10668 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10669 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10670 BasicBlock *InBB = PN.getIncomingBlock(i);
10671
10672 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10673 if (PHINode *OpPhi = OperandPhis[op])
10674 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10675 }
10676 }
10677
10678 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010679 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10680 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10681 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010682 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10683 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010684}
10685
10686
Chris Lattner21550882009-02-23 05:56:17 +000010687/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10688/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010689/// obvious the value of the load is not changed from the point of the load to
10690/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010691///
10692/// Finally, it is safe, but not profitable, to sink a load targetting a
10693/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10694/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010695static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010696 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10697
10698 for (++BBI; BBI != E; ++BBI)
10699 if (BBI->mayWriteToMemory())
10700 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010701
10702 // Check for non-address taken alloca. If not address-taken already, it isn't
10703 // profitable to do this xform.
10704 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10705 bool isAddressTaken = false;
10706 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10707 UI != E; ++UI) {
10708 if (isa<LoadInst>(UI)) continue;
10709 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10710 // If storing TO the alloca, then the address isn't taken.
10711 if (SI->getOperand(1) == AI) continue;
10712 }
10713 isAddressTaken = true;
10714 break;
10715 }
10716
Chris Lattner36d3e322009-02-21 00:46:50 +000010717 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010718 return false;
10719 }
10720
Chris Lattner36d3e322009-02-21 00:46:50 +000010721 // If this load is a load from a GEP with a constant offset from an alloca,
10722 // then we don't want to sink it. In its present form, it will be
10723 // load [constant stack offset]. Sinking it will cause us to have to
10724 // materialize the stack addresses in each predecessor in a register only to
10725 // do a shared load from register in the successor.
10726 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10727 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10728 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10729 return false;
10730
Chris Lattner76c73142006-11-01 07:13:54 +000010731 return true;
10732}
10733
Chris Lattner9fe38862003-06-19 17:00:31 +000010734
Chris Lattnerbac32862004-11-14 19:13:23 +000010735// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10736// operator and they all are only used by the PHI, PHI together their
10737// inputs, and do the operation once, to the result of the PHI.
10738Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10739 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10740
10741 // Scan the instruction, looking for input operations that can be folded away.
10742 // If all input operands to the phi are the same instruction (e.g. a cast from
10743 // the same type or "+42") we can pull the operation through the PHI, reducing
10744 // code size and simplifying code.
10745 Constant *ConstantOp = 0;
10746 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010747 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010748 if (isa<CastInst>(FirstInst)) {
10749 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010750 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010751 // Can fold binop, compare or shift here if the RHS is a constant,
10752 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010753 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010754 if (ConstantOp == 0)
10755 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010756 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10757 isVolatile = LI->isVolatile();
10758 // We can't sink the load if the loaded value could be modified between the
10759 // load and the PHI.
10760 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010761 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010762 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010763
10764 // If the PHI is of volatile loads and the load block has multiple
10765 // successors, sinking it would remove a load of the volatile value from
10766 // the path through the other successor.
10767 if (isVolatile &&
10768 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10769 return 0;
10770
Chris Lattner9c080502006-11-01 07:43:41 +000010771 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010772 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010773 } else {
10774 return 0; // Cannot fold this operation.
10775 }
10776
10777 // Check to see if all arguments are the same operation.
10778 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10779 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10780 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010781 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010782 return 0;
10783 if (CastSrcTy) {
10784 if (I->getOperand(0)->getType() != CastSrcTy)
10785 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010786 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010787 // We can't sink the load if the loaded value could be modified between
10788 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010789 if (LI->isVolatile() != isVolatile ||
10790 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010791 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010792 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010793
Chris Lattner71042962008-07-08 17:18:32 +000010794 // If the PHI is of volatile loads and the load block has multiple
10795 // successors, sinking it would remove a load of the volatile value from
10796 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010797 if (isVolatile &&
10798 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10799 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010800
Chris Lattnerbac32862004-11-14 19:13:23 +000010801 } else if (I->getOperand(1) != ConstantOp) {
10802 return 0;
10803 }
10804 }
10805
10806 // Okay, they are all the same operation. Create a new PHI node of the
10807 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010808 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10809 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010810 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010811
10812 Value *InVal = FirstInst->getOperand(0);
10813 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010814
10815 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010816 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10817 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10818 if (NewInVal != InVal)
10819 InVal = 0;
10820 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10821 }
10822
10823 Value *PhiVal;
10824 if (InVal) {
10825 // The new PHI unions all of the same values together. This is really
10826 // common, so we handle it intelligently here for compile-time speed.
10827 PhiVal = InVal;
10828 delete NewPN;
10829 } else {
10830 InsertNewInstBefore(NewPN, PN);
10831 PhiVal = NewPN;
10832 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010833
Chris Lattnerbac32862004-11-14 19:13:23 +000010834 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010835 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010836 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010837 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010838 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010839 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010840 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010841 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010842 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10843
10844 // If this was a volatile load that we are merging, make sure to loop through
10845 // and mark all the input loads as non-volatile. If we don't do this, we will
10846 // insert a new volatile load and the old ones will not be deletable.
10847 if (isVolatile)
10848 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10849 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10850
10851 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010852}
Chris Lattnera1be5662002-05-02 17:06:02 +000010853
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010854/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10855/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010856static bool DeadPHICycle(PHINode *PN,
10857 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010858 if (PN->use_empty()) return true;
10859 if (!PN->hasOneUse()) return false;
10860
10861 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010862 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010863 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010864
10865 // Don't scan crazily complex things.
10866 if (PotentiallyDeadPHIs.size() == 16)
10867 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010868
10869 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10870 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010871
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010872 return false;
10873}
10874
Chris Lattnercf5008a2007-11-06 21:52:06 +000010875/// PHIsEqualValue - Return true if this phi node is always equal to
10876/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10877/// z = some value; x = phi (y, z); y = phi (x, z)
10878static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10879 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10880 // See if we already saw this PHI node.
10881 if (!ValueEqualPHIs.insert(PN))
10882 return true;
10883
10884 // Don't scan crazily complex things.
10885 if (ValueEqualPHIs.size() == 16)
10886 return false;
10887
10888 // Scan the operands to see if they are either phi nodes or are equal to
10889 // the value.
10890 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10891 Value *Op = PN->getIncomingValue(i);
10892 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10893 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10894 return false;
10895 } else if (Op != NonPhiInVal)
10896 return false;
10897 }
10898
10899 return true;
10900}
10901
10902
Chris Lattner473945d2002-05-06 18:06:38 +000010903// PHINode simplification
10904//
Chris Lattner7e708292002-06-25 16:13:24 +000010905Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010906 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010907 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010908
Owen Anderson7e057142006-07-10 22:03:18 +000010909 if (Value *V = PN.hasConstantValue())
10910 return ReplaceInstUsesWith(PN, V);
10911
Owen Anderson7e057142006-07-10 22:03:18 +000010912 // If all PHI operands are the same operation, pull them through the PHI,
10913 // reducing code size.
10914 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010915 isa<Instruction>(PN.getIncomingValue(1)) &&
10916 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10917 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10918 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10919 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010920 PN.getIncomingValue(0)->hasOneUse())
10921 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10922 return Result;
10923
10924 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10925 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10926 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010927 if (PN.hasOneUse()) {
10928 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10929 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010930 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010931 PotentiallyDeadPHIs.insert(&PN);
10932 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010933 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010934 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010935
10936 // If this phi has a single use, and if that use just computes a value for
10937 // the next iteration of a loop, delete the phi. This occurs with unused
10938 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10939 // common case here is good because the only other things that catch this
10940 // are induction variable analysis (sometimes) and ADCE, which is only run
10941 // late.
10942 if (PHIUser->hasOneUse() &&
10943 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10944 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010945 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010946 }
10947 }
Owen Anderson7e057142006-07-10 22:03:18 +000010948
Chris Lattnercf5008a2007-11-06 21:52:06 +000010949 // We sometimes end up with phi cycles that non-obviously end up being the
10950 // same value, for example:
10951 // z = some value; x = phi (y, z); y = phi (x, z)
10952 // where the phi nodes don't necessarily need to be in the same block. Do a
10953 // quick check to see if the PHI node only contains a single non-phi value, if
10954 // so, scan to see if the phi cycle is actually equal to that value.
10955 {
10956 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10957 // Scan for the first non-phi operand.
10958 while (InValNo != NumOperandVals &&
10959 isa<PHINode>(PN.getIncomingValue(InValNo)))
10960 ++InValNo;
10961
10962 if (InValNo != NumOperandVals) {
10963 Value *NonPhiInVal = PN.getOperand(InValNo);
10964
10965 // Scan the rest of the operands to see if there are any conflicts, if so
10966 // there is no need to recursively scan other phis.
10967 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10968 Value *OpVal = PN.getIncomingValue(InValNo);
10969 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10970 break;
10971 }
10972
10973 // If we scanned over all operands, then we have one unique value plus
10974 // phi values. Scan PHI nodes to see if they all merge in each other or
10975 // the value.
10976 if (InValNo == NumOperandVals) {
10977 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10978 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10979 return ReplaceInstUsesWith(PN, NonPhiInVal);
10980 }
10981 }
10982 }
Chris Lattner60921c92003-12-19 05:58:40 +000010983 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010984}
10985
Chris Lattner7e708292002-06-25 16:13:24 +000010986Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010987 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000010988 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010989 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010990 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010991
Chris Lattnere87597f2004-10-16 18:11:37 +000010992 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010993 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010994
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010995 bool HasZeroPointerIndex = false;
10996 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10997 HasZeroPointerIndex = C->isNullValue();
10998
10999 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011000 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011001
Chris Lattner28977af2004-04-05 01:30:19 +000011002 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011003 if (TD) {
11004 bool MadeChange = false;
11005 unsigned PtrSize = TD->getPointerSizeInBits();
11006
11007 gep_type_iterator GTI = gep_type_begin(GEP);
11008 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11009 I != E; ++I, ++GTI) {
11010 if (!isa<SequentialType>(*GTI)) continue;
11011
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011012 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011013 // to what we need. If narrower, sign-extend it to what we need. This
11014 // explicit cast can make subsequent optimizations more obvious.
11015 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000011016 if (OpBits == PtrSize)
11017 continue;
11018
Chris Lattner2345d1d2009-08-30 20:01:10 +000011019 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011020 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011021 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011022 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011023 }
Chris Lattner28977af2004-04-05 01:30:19 +000011024
Chris Lattner90ac28c2002-08-02 19:29:35 +000011025 // Combine Indices - If the source pointer to this getelementptr instruction
11026 // is a getelementptr instruction, combine the indices of the two
11027 // getelementptr instructions into a single instruction.
11028 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011029 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011030 // Note that if our source is a gep chain itself that we wait for that
11031 // chain to be resolved before we perform this transformation. This
11032 // avoids us creating a TON of code in some cases.
11033 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011034 if (GetElementPtrInst *SrcGEP =
11035 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11036 if (SrcGEP->getNumOperands() == 2)
11037 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011038
Chris Lattner72588fc2007-02-15 22:48:32 +000011039 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011040
11041 // Find out whether the last index in the source GEP is a sequential idx.
11042 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011043 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11044 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011045 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011046
Chris Lattner90ac28c2002-08-02 19:29:35 +000011047 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011048 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011049 // Replace: gep (gep %P, long B), long A, ...
11050 // With: T = long A+B; gep %P, T, ...
11051 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011052 Value *Sum;
11053 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11054 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011055 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011056 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011057 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011058 Sum = SO1;
11059 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011060 // If they aren't the same type, then the input hasn't been processed
11061 // by the loop above yet (which canonicalizes sequential index types to
11062 // intptr_t). Just avoid transforming this until the input has been
11063 // normalized.
11064 if (SO1->getType() != GO1->getType())
11065 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011066 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000011067 }
Chris Lattner620ce142004-05-07 22:09:22 +000011068
Chris Lattnerab984842009-08-30 05:30:55 +000011069 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011070 if (Src->getNumOperands() == 2) {
11071 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011072 GEP.setOperand(1, Sum);
11073 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011074 }
Chris Lattnerab984842009-08-30 05:30:55 +000011075 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011076 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011077 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011078 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011079 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011080 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011081 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011082 Indices.append(Src->op_begin()+1, Src->op_end());
11083 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011084 }
11085
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011086 if (!Indices.empty())
11087 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11088 Src->isInBounds()) ?
11089 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11090 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011091 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011092 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011093 }
11094
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011095 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11096 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011097 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011098
Chris Lattner2de23192009-08-30 20:38:21 +000011099 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11100 // want to change the gep until the bitcasts are eliminated.
11101 if (getBitCastOperand(X)) {
11102 Worklist.AddValue(PtrOp);
11103 return 0;
11104 }
11105
Chris Lattner963f4ba2009-08-30 20:36:46 +000011106 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11107 // into : GEP [10 x i8]* X, i32 0, ...
11108 //
11109 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11110 // into : GEP i8* X, ...
11111 //
11112 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011113 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011114 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11115 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011116 if (const ArrayType *CATy =
11117 dyn_cast<ArrayType>(CPTy->getElementType())) {
11118 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11119 if (CATy->getElementType() == XTy->getElementType()) {
11120 // -> GEP i8* X, ...
11121 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011122 return cast<GEPOperator>(&GEP)->isInBounds() ?
11123 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11124 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011125 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11126 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011127 }
11128
11129 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011130 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011131 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011132 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011133 // At this point, we know that the cast source type is a pointer
11134 // to an array of the same type as the destination pointer
11135 // array. Because the array type is never stepped over (there
11136 // is a leading zero) we can fold the cast into this GEP.
11137 GEP.setOperand(0, X);
11138 return &GEP;
11139 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011140 }
11141 }
Chris Lattnereed48272005-09-13 00:40:14 +000011142 } else if (GEP.getNumOperands() == 2) {
11143 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011144 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11145 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011146 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11147 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011148 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011149 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11150 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011151 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011152 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011153 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011154 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11155 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011156 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011157 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011158 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011159 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011160
11161 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011162 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011163 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011164 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011165
Owen Anderson1d0be152009-08-13 21:58:54 +000011166 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011167 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011168 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011169
11170 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11171 // allow either a mul, shift, or constant here.
11172 Value *NewIdx = 0;
11173 ConstantInt *Scale = 0;
11174 if (ArrayEltSize == 1) {
11175 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011176 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011177 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011178 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011179 Scale = CI;
11180 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11181 if (Inst->getOpcode() == Instruction::Shl &&
11182 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011183 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11184 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011185 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011186 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011187 NewIdx = Inst->getOperand(0);
11188 } else if (Inst->getOpcode() == Instruction::Mul &&
11189 isa<ConstantInt>(Inst->getOperand(1))) {
11190 Scale = cast<ConstantInt>(Inst->getOperand(1));
11191 NewIdx = Inst->getOperand(0);
11192 }
11193 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011194
Chris Lattner7835cdd2005-09-13 18:36:04 +000011195 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011196 // out, perform the transformation. Note, we don't know whether Scale is
11197 // signed or not. We'll use unsigned version of division/modulo
11198 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011199 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011200 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011201 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011202 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011203 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011204 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11205 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011206 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011207 }
11208
11209 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011210 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011211 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011212 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011213 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11214 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11215 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011216 // The NewGEP must be pointer typed, so must the old one -> BitCast
11217 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011218 }
11219 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011220 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011221 }
Chris Lattner58407792009-01-09 04:53:57 +000011222
Chris Lattner46cd5a12009-01-09 05:44:56 +000011223 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011224 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011225 /// Y = gep X, <...constant indices...>
11226 /// into a gep of the original struct. This is important for SROA and alias
11227 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011228 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011229 if (TD &&
11230 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011231 // Determine how much the GEP moves the pointer. We are guaranteed to get
11232 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011233 ConstantInt *OffsetV =
11234 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011235 int64_t Offset = OffsetV->getSExtValue();
11236
11237 // If this GEP instruction doesn't move the pointer, just replace the GEP
11238 // with a bitcast of the real input to the dest type.
11239 if (Offset == 0) {
11240 // If the bitcast is of an allocation, and the allocation will be
11241 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000011242 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000011243 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011244 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11245 if (Instruction *I = visitBitCast(*BCI)) {
11246 if (I != BCI) {
11247 I->takeName(BCI);
11248 BCI->getParent()->getInstList().insert(BCI, I);
11249 ReplaceInstUsesWith(*BCI, I);
11250 }
11251 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011252 }
Chris Lattner58407792009-01-09 04:53:57 +000011253 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011254 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011255 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011256
11257 // Otherwise, if the offset is non-zero, we need to find out if there is a
11258 // field at Offset in 'A's type. If so, we can pull the cast through the
11259 // GEP.
11260 SmallVector<Value*, 8> NewIndices;
11261 const Type *InTy =
11262 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011263 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011264 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11265 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11266 NewIndices.end()) :
11267 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11268 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011269
11270 if (NGEP->getType() == GEP.getType())
11271 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011272 NGEP->takeName(&GEP);
11273 return new BitCastInst(NGEP, GEP.getType());
11274 }
Chris Lattner58407792009-01-09 04:53:57 +000011275 }
11276 }
11277
Chris Lattner8a2a3112001-12-14 16:52:21 +000011278 return 0;
11279}
11280
Victor Hernandez7b929da2009-10-23 21:09:37 +000011281Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattner0864acf2002-11-04 16:18:53 +000011282 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011283 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011284 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11285 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011286 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000011287 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000011288 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011289 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011290
Chris Lattner0864acf2002-11-04 16:18:53 +000011291 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011292 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011293 //
11294 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000011295 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011296
11297 // Now that I is pointing to the first non-allocation-inst in the block,
11298 // insert our getelementptr instruction...
11299 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011300 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011301 Value *Idx[2];
11302 Idx[0] = NullIdx;
11303 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011304 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11305 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011306
11307 // Now make everything use the getelementptr instead of the original
11308 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011309 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011310 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011311 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011312 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011313 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011314
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011315 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011316 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011317 // Note that we only do this for alloca's, because malloc should allocate
11318 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011319 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011320 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011321
11322 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11323 if (AI.getAlignment() == 0)
11324 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11325 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011326
Chris Lattner0864acf2002-11-04 16:18:53 +000011327 return 0;
11328}
11329
Victor Hernandez66284e02009-10-24 04:23:03 +000011330Instruction *InstCombiner::visitFree(Instruction &FI) {
11331 Value *Op = FI.getOperand(1);
11332
11333 // free undef -> unreachable.
11334 if (isa<UndefValue>(Op)) {
11335 // Insert a new store to null because we cannot modify the CFG here.
11336 new StoreInst(ConstantInt::getTrue(*Context),
11337 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11338 return EraseInstFromFunction(FI);
11339 }
11340
11341 // If we have 'free null' delete the instruction. This can happen in stl code
11342 // when lots of inlining happens.
11343 if (isa<ConstantPointerNull>(Op))
11344 return EraseInstFromFunction(FI);
11345
Victor Hernandez046e78c2009-10-26 23:43:48 +000011346 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000011347 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000011348 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11349 if (Op->hasOneUse() && CI->hasOneUse()) {
11350 EraseInstFromFunction(FI);
11351 EraseInstFromFunction(*CI);
11352 return EraseInstFromFunction(*cast<Instruction>(Op));
11353 }
11354 } else {
11355 // Op is a call to malloc
11356 if (Op->hasOneUse()) {
11357 EraseInstFromFunction(FI);
11358 return EraseInstFromFunction(*cast<Instruction>(Op));
11359 }
11360 }
Dan Gohman7f712a12009-10-27 00:11:02 +000011361 }
Victor Hernandez66284e02009-10-24 04:23:03 +000011362
11363 return 0;
11364}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011365
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011366/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011367static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011368 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011369 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011370 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011371 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011372
Mon P Wang6753f952009-02-07 22:19:29 +000011373 const PointerType *DestTy = cast<PointerType>(CI->getType());
11374 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011375 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011376
11377 // If the address spaces don't match, don't eliminate the cast.
11378 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11379 return 0;
11380
Chris Lattnerb89e0712004-07-13 01:49:43 +000011381 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011382
Reid Spencer42230162007-01-22 05:51:25 +000011383 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011384 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011385 // If the source is an array, the code below will not succeed. Check to
11386 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11387 // constants.
11388 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11389 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11390 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011391 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000011392 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11393 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000011394 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011395 SrcTy = cast<PointerType>(CastOp->getType());
11396 SrcPTy = SrcTy->getElementType();
11397 }
11398
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011399 if (IC.getTargetData() &&
11400 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011401 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011402 // Do not allow turning this into a load of an integer, which is then
11403 // casted to a pointer, this pessimizes pointer analysis a lot.
11404 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011405 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11406 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011407
Chris Lattnerf9527852005-01-31 04:50:46 +000011408 // Okay, we are casting from one integer or pointer type to another of
11409 // the same size. Instead of casting the pointer before the load, cast
11410 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011411 Value *NewLoad =
11412 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011413 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011414 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011415 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011416 }
11417 }
11418 return 0;
11419}
11420
Chris Lattner833b8a42003-06-26 05:06:25 +000011421Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11422 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011423
Dan Gohman9941f742007-07-20 16:34:21 +000011424 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011425 if (TD) {
11426 unsigned KnownAlign =
11427 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11428 if (KnownAlign >
11429 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11430 LI.getAlignment()))
11431 LI.setAlignment(KnownAlign);
11432 }
Dan Gohman9941f742007-07-20 16:34:21 +000011433
Chris Lattner963f4ba2009-08-30 20:36:46 +000011434 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011435 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011436 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011437 return Res;
11438
11439 // None of the following transforms are legal for volatile loads.
11440 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011441
Dan Gohman2276a7b2008-10-15 23:19:35 +000011442 // Do really simple store-to-load forwarding and load CSE, to catch cases
11443 // where there are several consequtive memory accesses to the same location,
11444 // separated by a few arithmetic operations.
11445 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011446 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11447 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011448
Chris Lattner878e4942009-10-22 06:25:11 +000011449 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000011450 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11451 const Value *GEPI0 = GEPI->getOperand(0);
11452 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011453 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011454 // Insert a new store to null instruction before the load to indicate
11455 // that this code is not reachable. We do this instead of inserting
11456 // an unreachable instruction directly because we cannot modify the
11457 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011458 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011459 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011460 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011461 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011462 }
Chris Lattner37366c12005-05-01 04:24:53 +000011463
Chris Lattner878e4942009-10-22 06:25:11 +000011464 // load null/undef -> unreachable
11465 // TODO: Consider a target hook for valid address spaces for this xform.
11466 if (isa<UndefValue>(Op) ||
11467 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11468 // Insert a new store to null instruction before the load to indicate that
11469 // this code is not reachable. We do this instead of inserting an
11470 // unreachable instruction directly because we cannot modify the CFG.
11471 new StoreInst(UndefValue::get(LI.getType()),
11472 Constant::getNullValue(Op->getType()), &LI);
11473 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011474 }
Chris Lattner878e4942009-10-22 06:25:11 +000011475
11476 // Instcombine load (constantexpr_cast global) -> cast (load global)
11477 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11478 if (CE->isCast())
11479 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11480 return Res;
11481
Chris Lattner37366c12005-05-01 04:24:53 +000011482 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011483 // Change select and PHI nodes to select values instead of addresses: this
11484 // helps alias analysis out a lot, allows many others simplifications, and
11485 // exposes redundancy in the code.
11486 //
11487 // Note that we cannot do the transformation unless we know that the
11488 // introduced loads cannot trap! Something like this is valid as long as
11489 // the condition is always false: load (select bool %C, int* null, int* %G),
11490 // but it would not be valid if we transformed it to load from null
11491 // unconditionally.
11492 //
11493 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11494 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011495 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11496 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011497 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11498 SI->getOperand(1)->getName()+".val");
11499 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11500 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011501 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011502 }
11503
Chris Lattner684fe212004-09-23 15:46:00 +000011504 // load (select (cond, null, P)) -> load P
11505 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11506 if (C->isNullValue()) {
11507 LI.setOperand(0, SI->getOperand(2));
11508 return &LI;
11509 }
11510
11511 // load (select (cond, P, null)) -> load P
11512 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11513 if (C->isNullValue()) {
11514 LI.setOperand(0, SI->getOperand(1));
11515 return &LI;
11516 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011517 }
11518 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011519 return 0;
11520}
11521
Reid Spencer55af2b52007-01-19 21:20:31 +000011522/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011523/// when possible. This makes it generally easy to do alias analysis and/or
11524/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011525static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11526 User *CI = cast<User>(SI.getOperand(1));
11527 Value *CastOp = CI->getOperand(0);
11528
11529 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011530 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11531 if (SrcTy == 0) return 0;
11532
11533 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011534
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011535 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11536 return 0;
11537
Chris Lattner3914f722009-01-24 01:00:13 +000011538 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11539 /// to its first element. This allows us to handle things like:
11540 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11541 /// on 32-bit hosts.
11542 SmallVector<Value*, 4> NewGEPIndices;
11543
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011544 // If the source is an array, the code below will not succeed. Check to
11545 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11546 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011547 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11548 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011549 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011550 NewGEPIndices.push_back(Zero);
11551
11552 while (1) {
11553 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011554 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011555 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011556 NewGEPIndices.push_back(Zero);
11557 SrcPTy = STy->getElementType(0);
11558 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11559 NewGEPIndices.push_back(Zero);
11560 SrcPTy = ATy->getElementType();
11561 } else {
11562 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011563 }
Chris Lattner3914f722009-01-24 01:00:13 +000011564 }
11565
Owen Andersondebcb012009-07-29 22:17:13 +000011566 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011567 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011568
11569 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11570 return 0;
11571
Chris Lattner71759c42009-01-16 20:12:52 +000011572 // If the pointers point into different address spaces or if they point to
11573 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011574 if (!IC.getTargetData() ||
11575 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011576 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011577 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11578 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011579 return 0;
11580
11581 // Okay, we are casting from one integer or pointer type to another of
11582 // the same size. Instead of casting the pointer before
11583 // the store, cast the value to be stored.
11584 Value *NewCast;
11585 Value *SIOp0 = SI.getOperand(0);
11586 Instruction::CastOps opcode = Instruction::BitCast;
11587 const Type* CastSrcTy = SIOp0->getType();
11588 const Type* CastDstTy = SrcPTy;
11589 if (isa<PointerType>(CastDstTy)) {
11590 if (CastSrcTy->isInteger())
11591 opcode = Instruction::IntToPtr;
11592 } else if (isa<IntegerType>(CastDstTy)) {
11593 if (isa<PointerType>(SIOp0->getType()))
11594 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011595 }
Chris Lattner3914f722009-01-24 01:00:13 +000011596
11597 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11598 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011599 if (!NewGEPIndices.empty())
11600 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11601 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011602
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011603 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11604 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011605 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011606}
11607
Chris Lattner4aebaee2008-11-27 08:56:30 +000011608/// equivalentAddressValues - Test if A and B will obviously have the same
11609/// value. This includes recognizing that %t0 and %t1 will have the same
11610/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011611/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011612/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011613/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011614/// %t2 = load i32* %t1
11615///
11616static bool equivalentAddressValues(Value *A, Value *B) {
11617 // Test if the values are trivially equivalent.
11618 if (A == B) return true;
11619
11620 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011621 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11622 // its only used to compare two uses within the same basic block, which
11623 // means that they'll always either have the same value or one of them
11624 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011625 if (isa<BinaryOperator>(A) ||
11626 isa<CastInst>(A) ||
11627 isa<PHINode>(A) ||
11628 isa<GetElementPtrInst>(A))
11629 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011630 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011631 return true;
11632
11633 // Otherwise they may not be equivalent.
11634 return false;
11635}
11636
Dale Johannesen4945c652009-03-03 21:26:39 +000011637// If this instruction has two uses, one of which is a llvm.dbg.declare,
11638// return the llvm.dbg.declare.
11639DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11640 if (!V->hasNUses(2))
11641 return 0;
11642 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11643 UI != E; ++UI) {
11644 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11645 return DI;
11646 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11647 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11648 return DI;
11649 }
11650 }
11651 return 0;
11652}
11653
Chris Lattner2f503e62005-01-31 05:36:43 +000011654Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11655 Value *Val = SI.getOperand(0);
11656 Value *Ptr = SI.getOperand(1);
11657
11658 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011659 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011660 ++NumCombined;
11661 return 0;
11662 }
Chris Lattner836692d2007-01-15 06:51:56 +000011663
11664 // If the RHS is an alloca with a single use, zapify the store, making the
11665 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011666 // If the RHS is an alloca with a two uses, the other one being a
11667 // llvm.dbg.declare, zapify the store and the declare, making the
11668 // alloca dead. We must do this to prevent declare's from affecting
11669 // codegen.
11670 if (!SI.isVolatile()) {
11671 if (Ptr->hasOneUse()) {
11672 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011673 EraseInstFromFunction(SI);
11674 ++NumCombined;
11675 return 0;
11676 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011677 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11678 if (isa<AllocaInst>(GEP->getOperand(0))) {
11679 if (GEP->getOperand(0)->hasOneUse()) {
11680 EraseInstFromFunction(SI);
11681 ++NumCombined;
11682 return 0;
11683 }
11684 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11685 EraseInstFromFunction(*DI);
11686 EraseInstFromFunction(SI);
11687 ++NumCombined;
11688 return 0;
11689 }
11690 }
11691 }
11692 }
11693 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11694 EraseInstFromFunction(*DI);
11695 EraseInstFromFunction(SI);
11696 ++NumCombined;
11697 return 0;
11698 }
Chris Lattner836692d2007-01-15 06:51:56 +000011699 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011700
Dan Gohman9941f742007-07-20 16:34:21 +000011701 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011702 if (TD) {
11703 unsigned KnownAlign =
11704 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11705 if (KnownAlign >
11706 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11707 SI.getAlignment()))
11708 SI.setAlignment(KnownAlign);
11709 }
Dan Gohman9941f742007-07-20 16:34:21 +000011710
Dale Johannesenacb51a32009-03-03 01:43:03 +000011711 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011712 // stores to the same location, separated by a few arithmetic operations. This
11713 // situation often occurs with bitfield accesses.
11714 BasicBlock::iterator BBI = &SI;
11715 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11716 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011717 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011718 // Don't count debug info directives, lest they affect codegen,
11719 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11720 // It is necessary for correctness to skip those that feed into a
11721 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011722 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011723 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011724 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011725 continue;
11726 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011727
11728 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11729 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011730 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11731 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011732 ++NumDeadStore;
11733 ++BBI;
11734 EraseInstFromFunction(*PrevSI);
11735 continue;
11736 }
11737 break;
11738 }
11739
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011740 // If this is a load, we have to stop. However, if the loaded value is from
11741 // the pointer we're loading and is producing the pointer we're storing,
11742 // then *this* store is dead (X = load P; store X -> P).
11743 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011744 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11745 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011746 EraseInstFromFunction(SI);
11747 ++NumCombined;
11748 return 0;
11749 }
11750 // Otherwise, this is a load from some other location. Stores before it
11751 // may not be dead.
11752 break;
11753 }
11754
Chris Lattner9ca96412006-02-08 03:25:32 +000011755 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011756 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011757 break;
11758 }
11759
11760
11761 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011762
11763 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011764 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011765 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011766 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011767 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011768 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011769 ++NumCombined;
11770 }
11771 return 0; // Do not modify these!
11772 }
11773
11774 // store undef, Ptr -> noop
11775 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011776 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011777 ++NumCombined;
11778 return 0;
11779 }
11780
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011781 // If the pointer destination is a cast, see if we can fold the cast into the
11782 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011783 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011784 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11785 return Res;
11786 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011787 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011788 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11789 return Res;
11790
Chris Lattner408902b2005-09-12 23:23:25 +000011791
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011792 // If this store is the last instruction in the basic block (possibly
11793 // excepting debug info instructions and the pointer bitcasts that feed
11794 // into them), and if the block ends with an unconditional branch, try
11795 // to move it to the successor block.
11796 BBI = &SI;
11797 do {
11798 ++BBI;
11799 } while (isa<DbgInfoIntrinsic>(BBI) ||
11800 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011801 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011802 if (BI->isUnconditional())
11803 if (SimplifyStoreAtEndOfBlock(SI))
11804 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011805
Chris Lattner2f503e62005-01-31 05:36:43 +000011806 return 0;
11807}
11808
Chris Lattner3284d1f2007-04-15 00:07:55 +000011809/// SimplifyStoreAtEndOfBlock - Turn things like:
11810/// if () { *P = v1; } else { *P = v2 }
11811/// into a phi node with a store in the successor.
11812///
Chris Lattner31755a02007-04-15 01:02:18 +000011813/// Simplify things like:
11814/// *P = v1; if () { *P = v2; }
11815/// into a phi node with a store in the successor.
11816///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011817bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11818 BasicBlock *StoreBB = SI.getParent();
11819
11820 // Check to see if the successor block has exactly two incoming edges. If
11821 // so, see if the other predecessor contains a store to the same location.
11822 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011823 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011824
11825 // Determine whether Dest has exactly two predecessors and, if so, compute
11826 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011827 pred_iterator PI = pred_begin(DestBB);
11828 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011829 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011830 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011831 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011832 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011833 return false;
11834
11835 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011836 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011837 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011838 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011839 }
Chris Lattner31755a02007-04-15 01:02:18 +000011840 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011841 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011842
11843 // Bail out if all the relevant blocks aren't distinct (this can happen,
11844 // for example, if SI is in an infinite loop)
11845 if (StoreBB == DestBB || OtherBB == DestBB)
11846 return false;
11847
Chris Lattner31755a02007-04-15 01:02:18 +000011848 // Verify that the other block ends in a branch and is not otherwise empty.
11849 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011850 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011851 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011852 return false;
11853
Chris Lattner31755a02007-04-15 01:02:18 +000011854 // If the other block ends in an unconditional branch, check for the 'if then
11855 // else' case. there is an instruction before the branch.
11856 StoreInst *OtherStore = 0;
11857 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011858 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011859 // Skip over debugging info.
11860 while (isa<DbgInfoIntrinsic>(BBI) ||
11861 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11862 if (BBI==OtherBB->begin())
11863 return false;
11864 --BBI;
11865 }
11866 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011867 OtherStore = dyn_cast<StoreInst>(BBI);
11868 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11869 return false;
11870 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011871 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011872 // destinations is StoreBB, then we have the if/then case.
11873 if (OtherBr->getSuccessor(0) != StoreBB &&
11874 OtherBr->getSuccessor(1) != StoreBB)
11875 return false;
11876
11877 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011878 // if/then triangle. See if there is a store to the same ptr as SI that
11879 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011880 for (;; --BBI) {
11881 // Check to see if we find the matching store.
11882 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11883 if (OtherStore->getOperand(1) != SI.getOperand(1))
11884 return false;
11885 break;
11886 }
Eli Friedman6903a242008-06-13 22:02:12 +000011887 // If we find something that may be using or overwriting the stored
11888 // value, or if we run out of instructions, we can't do the xform.
11889 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011890 BBI == OtherBB->begin())
11891 return false;
11892 }
11893
11894 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011895 // make sure nothing reads or overwrites the stored value in
11896 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011897 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11898 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011899 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011900 return false;
11901 }
11902 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011903
Chris Lattner31755a02007-04-15 01:02:18 +000011904 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011905 Value *MergedVal = OtherStore->getOperand(0);
11906 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011907 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011908 PN->reserveOperandSpace(2);
11909 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011910 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11911 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011912 }
11913
11914 // Advance to a place where it is safe to insert the new store and
11915 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011916 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011917 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11918 OtherStore->isVolatile()), *BBI);
11919
11920 // Nuke the old stores.
11921 EraseInstFromFunction(SI);
11922 EraseInstFromFunction(*OtherStore);
11923 ++NumCombined;
11924 return true;
11925}
11926
Chris Lattner2f503e62005-01-31 05:36:43 +000011927
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011928Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11929 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011930 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011931 BasicBlock *TrueDest;
11932 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011933 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011934 !isa<Constant>(X)) {
11935 // Swap Destinations and condition...
11936 BI.setCondition(X);
11937 BI.setSuccessor(0, FalseDest);
11938 BI.setSuccessor(1, TrueDest);
11939 return &BI;
11940 }
11941
Reid Spencere4d87aa2006-12-23 06:05:41 +000011942 // Cannonicalize fcmp_one -> fcmp_oeq
11943 FCmpInst::Predicate FPred; Value *Y;
11944 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011945 TrueDest, FalseDest)) &&
11946 BI.getCondition()->hasOneUse())
11947 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11948 FPred == FCmpInst::FCMP_OGE) {
11949 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11950 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11951
11952 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011953 BI.setSuccessor(0, FalseDest);
11954 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011955 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011956 return &BI;
11957 }
11958
11959 // Cannonicalize icmp_ne -> icmp_eq
11960 ICmpInst::Predicate IPred;
11961 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011962 TrueDest, FalseDest)) &&
11963 BI.getCondition()->hasOneUse())
11964 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11965 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11966 IPred == ICmpInst::ICMP_SGE) {
11967 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11968 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11969 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011970 BI.setSuccessor(0, FalseDest);
11971 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011972 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011973 return &BI;
11974 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011975
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011976 return 0;
11977}
Chris Lattner0864acf2002-11-04 16:18:53 +000011978
Chris Lattner46238a62004-07-03 00:26:11 +000011979Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11980 Value *Cond = SI.getCondition();
11981 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11982 if (I->getOpcode() == Instruction::Add)
11983 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11984 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11985 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000011986 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000011987 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011988 AddRHS));
11989 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000011990 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011991 return &SI;
11992 }
11993 }
11994 return 0;
11995}
11996
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011997Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011998 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011999
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012000 if (!EV.hasIndices())
12001 return ReplaceInstUsesWith(EV, Agg);
12002
12003 if (Constant *C = dyn_cast<Constant>(Agg)) {
12004 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012005 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012006
12007 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012008 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012009
12010 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12011 // Extract the element indexed by the first index out of the constant
12012 Value *V = C->getOperand(*EV.idx_begin());
12013 if (EV.getNumIndices() > 1)
12014 // Extract the remaining indices out of the constant indexed by the
12015 // first index
12016 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12017 else
12018 return ReplaceInstUsesWith(EV, V);
12019 }
12020 return 0; // Can't handle other constants
12021 }
12022 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12023 // We're extracting from an insertvalue instruction, compare the indices
12024 const unsigned *exti, *exte, *insi, *inse;
12025 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12026 exte = EV.idx_end(), inse = IV->idx_end();
12027 exti != exte && insi != inse;
12028 ++exti, ++insi) {
12029 if (*insi != *exti)
12030 // The insert and extract both reference distinctly different elements.
12031 // This means the extract is not influenced by the insert, and we can
12032 // replace the aggregate operand of the extract with the aggregate
12033 // operand of the insert. i.e., replace
12034 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12035 // %E = extractvalue { i32, { i32 } } %I, 0
12036 // with
12037 // %E = extractvalue { i32, { i32 } } %A, 0
12038 return ExtractValueInst::Create(IV->getAggregateOperand(),
12039 EV.idx_begin(), EV.idx_end());
12040 }
12041 if (exti == exte && insi == inse)
12042 // Both iterators are at the end: Index lists are identical. Replace
12043 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12044 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12045 // with "i32 42"
12046 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12047 if (exti == exte) {
12048 // The extract list is a prefix of the insert list. i.e. replace
12049 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12050 // %E = extractvalue { i32, { i32 } } %I, 1
12051 // with
12052 // %X = extractvalue { i32, { i32 } } %A, 1
12053 // %E = insertvalue { i32 } %X, i32 42, 0
12054 // by switching the order of the insert and extract (though the
12055 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012056 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12057 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012058 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12059 insi, inse);
12060 }
12061 if (insi == inse)
12062 // The insert list is a prefix of the extract list
12063 // We can simply remove the common indices from the extract and make it
12064 // operate on the inserted value instead of the insertvalue result.
12065 // i.e., replace
12066 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12067 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12068 // with
12069 // %E extractvalue { i32 } { i32 42 }, 0
12070 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12071 exti, exte);
12072 }
12073 // Can't simplify extracts from other values. Note that nested extracts are
12074 // already simplified implicitely by the above (extract ( extract (insert) )
12075 // will be translated into extract ( insert ( extract ) ) first and then just
12076 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012077 return 0;
12078}
12079
Chris Lattner220b0cf2006-03-05 00:22:33 +000012080/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12081/// is to leave as a vector operation.
12082static bool CheapToScalarize(Value *V, bool isConstant) {
12083 if (isa<ConstantAggregateZero>(V))
12084 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012085 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012086 if (isConstant) return true;
12087 // If all elts are the same, we can extract.
12088 Constant *Op0 = C->getOperand(0);
12089 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12090 if (C->getOperand(i) != Op0)
12091 return false;
12092 return true;
12093 }
12094 Instruction *I = dyn_cast<Instruction>(V);
12095 if (!I) return false;
12096
12097 // Insert element gets simplified to the inserted element or is deleted if
12098 // this is constant idx extract element and its a constant idx insertelt.
12099 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12100 isa<ConstantInt>(I->getOperand(2)))
12101 return true;
12102 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12103 return true;
12104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12105 if (BO->hasOneUse() &&
12106 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12107 CheapToScalarize(BO->getOperand(1), isConstant)))
12108 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012109 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12110 if (CI->hasOneUse() &&
12111 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12112 CheapToScalarize(CI->getOperand(1), isConstant)))
12113 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012114
12115 return false;
12116}
12117
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012118/// Read and decode a shufflevector mask.
12119///
12120/// It turns undef elements into values that are larger than the number of
12121/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012122static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12123 unsigned NElts = SVI->getType()->getNumElements();
12124 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12125 return std::vector<unsigned>(NElts, 0);
12126 if (isa<UndefValue>(SVI->getOperand(2)))
12127 return std::vector<unsigned>(NElts, 2*NElts);
12128
12129 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012130 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012131 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12132 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012133 Result.push_back(NElts*2); // undef -> 8
12134 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012135 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012136 return Result;
12137}
12138
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012139/// FindScalarElement - Given a vector and an element number, see if the scalar
12140/// value is already around as a register, for example if it were inserted then
12141/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012142static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012143 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012144 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12145 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012146 unsigned Width = PTy->getNumElements();
12147 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012148 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012149
12150 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012151 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012152 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012153 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012154 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012155 return CP->getOperand(EltNo);
12156 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12157 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012158 if (!isa<ConstantInt>(III->getOperand(2)))
12159 return 0;
12160 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012161
12162 // If this is an insert to the element we are looking for, return the
12163 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012164 if (EltNo == IIElt)
12165 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012166
12167 // Otherwise, the insertelement doesn't modify the value, recurse on its
12168 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012169 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012170 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012171 unsigned LHSWidth =
12172 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012173 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012174 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012175 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012176 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012177 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012178 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012179 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012180 }
12181
12182 // Otherwise, we don't know.
12183 return 0;
12184}
12185
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012186Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012187 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012188 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012189 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012190
Dan Gohman07a96762007-07-16 14:29:03 +000012191 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012192 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012193 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012194
Reid Spencer9d6565a2007-02-15 02:26:10 +000012195 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012196 // If vector val is constant with all elements the same, replace EI with
12197 // that element. When the elements are not identical, we cannot replace yet
12198 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012199 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012200 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012201 if (C->getOperand(i) != op0) {
12202 op0 = 0;
12203 break;
12204 }
12205 if (op0)
12206 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012207 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012208
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012209 // If extracting a specified index from the vector, see if we can recursively
12210 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012211 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012212 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012213 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012214
12215 // If this is extracting an invalid index, turn this into undef, to avoid
12216 // crashing the code below.
12217 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012218 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012219
Chris Lattner867b99f2006-10-05 06:55:50 +000012220 // This instruction only demands the single element from the input vector.
12221 // If the input vector has a single use, simplify it based on this use
12222 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012223 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012224 APInt UndefElts(VectorWidth, 0);
12225 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012226 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012227 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012228 EI.setOperand(0, V);
12229 return &EI;
12230 }
12231 }
12232
Owen Andersond672ecb2009-07-03 00:17:18 +000012233 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012234 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012235
12236 // If the this extractelement is directly using a bitcast from a vector of
12237 // the same number of elements, see if we can find the source element from
12238 // it. In this case, we will end up needing to bitcast the scalars.
12239 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12240 if (const VectorType *VT =
12241 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12242 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012243 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12244 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012245 return new BitCastInst(Elt, EI.getType());
12246 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012247 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012248
Chris Lattner73fa49d2006-05-25 22:53:38 +000012249 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012250 // Push extractelement into predecessor operation if legal and
12251 // profitable to do so
12252 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12253 if (I->hasOneUse() &&
12254 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12255 Value *newEI0 =
12256 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12257 EI.getName()+".lhs");
12258 Value *newEI1 =
12259 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12260 EI.getName()+".rhs");
12261 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012262 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012263 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012264 // Extracting the inserted element?
12265 if (IE->getOperand(2) == EI.getOperand(1))
12266 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12267 // If the inserted and extracted elements are constants, they must not
12268 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012269 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012270 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012271 EI.setOperand(0, IE->getOperand(0));
12272 return &EI;
12273 }
12274 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12275 // If this is extracting an element from a shufflevector, figure out where
12276 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012277 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12278 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012279 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012280 unsigned LHSWidth =
12281 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12282
12283 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012284 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012285 else if (SrcIdx < LHSWidth*2) {
12286 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012287 Src = SVI->getOperand(1);
12288 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012289 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012290 }
Eric Christophera3500da2009-07-25 02:28:41 +000012291 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012292 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12293 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012294 }
12295 }
Eli Friedman2451a642009-07-18 23:06:53 +000012296 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012297 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012298 return 0;
12299}
12300
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012301/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12302/// elements from either LHS or RHS, return the shuffle mask and true.
12303/// Otherwise, return false.
12304static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012305 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012306 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012307 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12308 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012309 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012310
12311 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012312 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012313 return true;
12314 } else if (V == LHS) {
12315 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012316 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012317 return true;
12318 } else if (V == RHS) {
12319 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012320 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012321 return true;
12322 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12323 // If this is an insert of an extract from some other vector, include it.
12324 Value *VecOp = IEI->getOperand(0);
12325 Value *ScalarOp = IEI->getOperand(1);
12326 Value *IdxOp = IEI->getOperand(2);
12327
Chris Lattnerd929f062006-04-27 21:14:21 +000012328 if (!isa<ConstantInt>(IdxOp))
12329 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012330 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012331
12332 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12333 // Okay, we can handle this if the vector we are insertinting into is
12334 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012335 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012336 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012337 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012338 return true;
12339 }
12340 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12341 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012342 EI->getOperand(0)->getType() == V->getType()) {
12343 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012344 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012345
12346 // This must be extracting from either LHS or RHS.
12347 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12348 // Okay, we can handle this if the vector we are insertinting into is
12349 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012350 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012351 // If so, update the mask to reflect the inserted value.
12352 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012353 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012354 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012355 } else {
12356 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012357 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012358 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012359
12360 }
12361 return true;
12362 }
12363 }
12364 }
12365 }
12366 }
12367 // TODO: Handle shufflevector here!
12368
12369 return false;
12370}
12371
12372/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12373/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12374/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012375static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012376 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012377 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012378 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012379 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012380 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012381
12382 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012383 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012384 return V;
12385 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012386 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012387 return V;
12388 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12389 // If this is an insert of an extract from some other vector, include it.
12390 Value *VecOp = IEI->getOperand(0);
12391 Value *ScalarOp = IEI->getOperand(1);
12392 Value *IdxOp = IEI->getOperand(2);
12393
12394 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12395 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12396 EI->getOperand(0)->getType() == V->getType()) {
12397 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012398 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12399 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012400
12401 // Either the extracted from or inserted into vector must be RHSVec,
12402 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012403 if (EI->getOperand(0) == RHS || RHS == 0) {
12404 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012405 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012406 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012407 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012408 return V;
12409 }
12410
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012411 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012412 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12413 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012414 // Everything but the extracted element is replaced with the RHS.
12415 for (unsigned i = 0; i != NumElts; ++i) {
12416 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012417 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012418 }
12419 return V;
12420 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012421
12422 // If this insertelement is a chain that comes from exactly these two
12423 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012424 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12425 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012426 return EI->getOperand(0);
12427
Chris Lattnerefb47352006-04-15 01:39:45 +000012428 }
12429 }
12430 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012431 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012432
12433 // Otherwise, can't do anything fancy. Return an identity vector.
12434 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012435 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012436 return V;
12437}
12438
12439Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12440 Value *VecOp = IE.getOperand(0);
12441 Value *ScalarOp = IE.getOperand(1);
12442 Value *IdxOp = IE.getOperand(2);
12443
Chris Lattner599ded12007-04-09 01:11:16 +000012444 // Inserting an undef or into an undefined place, remove this.
12445 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12446 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012447
Chris Lattnerefb47352006-04-15 01:39:45 +000012448 // If the inserted element was extracted from some other vector, and if the
12449 // indexes are constant, try to turn this into a shufflevector operation.
12450 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12451 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12452 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012453 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012454 unsigned ExtractedIdx =
12455 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012456 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012457
12458 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12459 return ReplaceInstUsesWith(IE, VecOp);
12460
12461 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012462 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012463
12464 // If we are extracting a value from a vector, then inserting it right
12465 // back into the same place, just use the input vector.
12466 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12467 return ReplaceInstUsesWith(IE, VecOp);
12468
Chris Lattnerefb47352006-04-15 01:39:45 +000012469 // If this insertelement isn't used by some other insertelement, turn it
12470 // (and any insertelements it points to), into one big shuffle.
12471 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12472 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012473 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012474 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012475 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012476 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012477 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012478 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012479 }
12480 }
12481 }
12482
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012483 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12484 APInt UndefElts(VWidth, 0);
12485 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12486 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12487 return &IE;
12488
Chris Lattnerefb47352006-04-15 01:39:45 +000012489 return 0;
12490}
12491
12492
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012493Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12494 Value *LHS = SVI.getOperand(0);
12495 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012496 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012497
12498 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012499
Chris Lattner867b99f2006-10-05 06:55:50 +000012500 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012501 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012502 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012503
Dan Gohman488fbfc2008-09-09 18:11:14 +000012504 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012505
12506 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12507 return 0;
12508
Evan Cheng388df622009-02-03 10:05:09 +000012509 APInt UndefElts(VWidth, 0);
12510 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12511 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012512 LHS = SVI.getOperand(0);
12513 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012514 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012515 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012516
Chris Lattner863bcff2006-05-25 23:48:38 +000012517 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12518 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12519 if (LHS == RHS || isa<UndefValue>(LHS)) {
12520 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012521 // shuffle(undef,undef,mask) -> undef.
12522 return ReplaceInstUsesWith(SVI, LHS);
12523 }
12524
Chris Lattner863bcff2006-05-25 23:48:38 +000012525 // Remap any references to RHS to use LHS.
12526 std::vector<Constant*> Elts;
12527 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012528 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012529 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012530 else {
12531 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012532 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012533 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012534 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012535 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012536 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012537 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012538 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012539 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012540 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012541 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012542 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012543 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012544 LHS = SVI.getOperand(0);
12545 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012546 MadeChange = true;
12547 }
12548
Chris Lattner7b2e27922006-05-26 00:29:06 +000012549 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012550 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012551
Chris Lattner863bcff2006-05-25 23:48:38 +000012552 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12553 if (Mask[i] >= e*2) continue; // Ignore undef values.
12554 // Is this an identity shuffle of the LHS value?
12555 isLHSID &= (Mask[i] == i);
12556
12557 // Is this an identity shuffle of the RHS value?
12558 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012559 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012560
Chris Lattner863bcff2006-05-25 23:48:38 +000012561 // Eliminate identity shuffles.
12562 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12563 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012564
Chris Lattner7b2e27922006-05-26 00:29:06 +000012565 // If the LHS is a shufflevector itself, see if we can combine it with this
12566 // one without producing an unusual shuffle. Here we are really conservative:
12567 // we are absolutely afraid of producing a shuffle mask not in the input
12568 // program, because the code gen may not be smart enough to turn a merged
12569 // shuffle into two specific shuffles: it may produce worse code. As such,
12570 // we only merge two shuffles if the result is one of the two input shuffle
12571 // masks. In this case, merging the shuffles just removes one instruction,
12572 // which we know is safe. This is good for things like turning:
12573 // (splat(splat)) -> splat.
12574 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12575 if (isa<UndefValue>(RHS)) {
12576 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12577
12578 std::vector<unsigned> NewMask;
12579 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12580 if (Mask[i] >= 2*e)
12581 NewMask.push_back(2*e);
12582 else
12583 NewMask.push_back(LHSMask[Mask[i]]);
12584
12585 // If the result mask is equal to the src shuffle or this shuffle mask, do
12586 // the replacement.
12587 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012588 unsigned LHSInNElts =
12589 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012590 std::vector<Constant*> Elts;
12591 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012592 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012593 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012594 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012595 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012596 }
12597 }
12598 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12599 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012600 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012601 }
12602 }
12603 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012604
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012605 return MadeChange ? &SVI : 0;
12606}
12607
12608
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012609
Chris Lattnerea1c4542004-12-08 23:43:58 +000012610
12611/// TryToSinkInstruction - Try to move the specified instruction from its
12612/// current block into the beginning of DestBlock, which can only happen if it's
12613/// safe to move the instruction past all of the instructions between it and the
12614/// end of its block.
12615static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12616 assert(I->hasOneUse() && "Invariants didn't hold!");
12617
Chris Lattner108e9022005-10-27 17:13:11 +000012618 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012619 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012620 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012621
Chris Lattnerea1c4542004-12-08 23:43:58 +000012622 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012623 if (isa<AllocaInst>(I) && I->getParent() ==
12624 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012625 return false;
12626
Chris Lattner96a52a62004-12-09 07:14:34 +000012627 // We can only sink load instructions if there is nothing between the load and
12628 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012629 if (I->mayReadFromMemory()) {
12630 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012631 Scan != E; ++Scan)
12632 if (Scan->mayWriteToMemory())
12633 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012634 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012635
Dan Gohman02dea8b2008-05-23 21:05:58 +000012636 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012637
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012638 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012639 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012640 ++NumSunkInst;
12641 return true;
12642}
12643
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012644
12645/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12646/// all reachable code to the worklist.
12647///
12648/// This has a couple of tricks to make the code faster and more powerful. In
12649/// particular, we constant fold and DCE instructions as we go, to avoid adding
12650/// them to the worklist (this significantly speeds up instcombine on code where
12651/// many instructions are dead or constant). Additionally, if we find a branch
12652/// whose condition is a known constant, we only visit the reachable successors.
12653///
Chris Lattner2ee743b2009-10-15 04:59:28 +000012654static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012655 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012656 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012657 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000012658 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000012659 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012660 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000012661
12662 std::vector<Instruction*> InstrsForInstCombineWorklist;
12663 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012664
Chris Lattner2ee743b2009-10-15 04:59:28 +000012665 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12666
Chris Lattner2c7718a2007-03-23 19:17:18 +000012667 while (!Worklist.empty()) {
12668 BB = Worklist.back();
12669 Worklist.pop_back();
12670
12671 // We have now visited this block! If we've already been here, ignore it.
12672 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012673
Chris Lattner2c7718a2007-03-23 19:17:18 +000012674 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12675 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012676
Chris Lattner2c7718a2007-03-23 19:17:18 +000012677 // DCE instruction if trivially dead.
12678 if (isInstructionTriviallyDead(Inst)) {
12679 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012680 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012681 Inst->eraseFromParent();
12682 continue;
12683 }
12684
12685 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012686 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
12687 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12688 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12689 << *Inst << '\n');
12690 Inst->replaceAllUsesWith(C);
12691 ++NumConstProp;
12692 Inst->eraseFromParent();
12693 continue;
12694 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000012695
12696
12697
12698 if (TD) {
12699 // See if we can constant fold its operands.
12700 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12701 i != e; ++i) {
12702 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12703 if (CE == 0) continue;
12704
12705 // If we already folded this constant, don't try again.
12706 if (!FoldedConstants.insert(CE))
12707 continue;
12708
12709 Constant *NewC =
12710 ConstantFoldConstantExpression(CE, BB->getContext(), TD);
12711 if (NewC && NewC != CE) {
12712 *i = NewC;
12713 MadeIRChange = true;
12714 }
12715 }
12716 }
12717
Devang Patel7fe1dec2008-11-19 18:56:50 +000012718
Chris Lattner67f7d542009-10-12 03:58:40 +000012719 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012720 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012721
12722 // Recursively visit successors. If this is a branch or switch on a
12723 // constant, only visit the reachable successor.
12724 TerminatorInst *TI = BB->getTerminator();
12725 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12726 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12727 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012728 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012729 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012730 continue;
12731 }
12732 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12733 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12734 // See if this is an explicit destination.
12735 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12736 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012737 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012738 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012739 continue;
12740 }
12741
12742 // Otherwise it is the default destination.
12743 Worklist.push_back(SI->getSuccessor(0));
12744 continue;
12745 }
12746 }
12747
12748 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12749 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012750 }
Chris Lattner67f7d542009-10-12 03:58:40 +000012751
12752 // Once we've found all of the instructions to add to instcombine's worklist,
12753 // add them in reverse order. This way instcombine will visit from the top
12754 // of the function down. This jives well with the way that it adds all uses
12755 // of instructions to the worklist after doing a transformation, thus avoiding
12756 // some N^2 behavior in pathological cases.
12757 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12758 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000012759
12760 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012761}
12762
Chris Lattnerec9c3582007-03-03 02:04:50 +000012763bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012764 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012765
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012766 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12767 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012768
Chris Lattnerb3d59702005-07-07 20:40:38 +000012769 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012770 // Do a depth-first traversal of the function, populate the worklist with
12771 // the reachable instructions. Ignore blocks that are not reachable. Keep
12772 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012773 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000012774 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012775
Chris Lattnerb3d59702005-07-07 20:40:38 +000012776 // Do a quick scan over the function. If we find any blocks that are
12777 // unreachable, remove any instructions inside of them. This prevents
12778 // the instcombine code from having to deal with some bad special cases.
12779 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12780 if (!Visited.count(BB)) {
12781 Instruction *Term = BB->getTerminator();
12782 while (Term != BB->begin()) { // Remove instrs bottom-up
12783 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012784
Chris Lattnerbdff5482009-08-23 04:37:46 +000012785 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012786 // A debug intrinsic shouldn't force another iteration if we weren't
12787 // going to do one without it.
12788 if (!isa<DbgInfoIntrinsic>(I)) {
12789 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012790 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000012791 }
Devang Patel228ebd02009-10-13 22:56:32 +000012792
Devang Patel228ebd02009-10-13 22:56:32 +000012793 // If I is not void type then replaceAllUsesWith undef.
12794 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000012795 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000012796 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012797 I->eraseFromParent();
12798 }
12799 }
12800 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012801
Chris Lattner873ff012009-08-30 05:55:36 +000012802 while (!Worklist.isEmpty()) {
12803 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012804 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012805
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012806 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012807 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012808 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012809 EraseInstFromFunction(*I);
12810 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012811 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012812 continue;
12813 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012814
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012815 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012816 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
12817 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12818 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012819
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012820 // Add operands to the worklist.
12821 ReplaceInstUsesWith(*I, C);
12822 ++NumConstProp;
12823 EraseInstFromFunction(*I);
12824 MadeIRChange = true;
12825 continue;
12826 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012827
Chris Lattnerea1c4542004-12-08 23:43:58 +000012828 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012829 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012830 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000012831 Instruction *UserInst = cast<Instruction>(I->use_back());
12832 BasicBlock *UserParent;
12833
12834 // Get the block the use occurs in.
12835 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12836 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12837 else
12838 UserParent = UserInst->getParent();
12839
Chris Lattnerea1c4542004-12-08 23:43:58 +000012840 if (UserParent != BB) {
12841 bool UserIsSuccessor = false;
12842 // See if the user is one of our successors.
12843 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12844 if (*SI == UserParent) {
12845 UserIsSuccessor = true;
12846 break;
12847 }
12848
12849 // If the user is one of our immediate successors, and if that successor
12850 // only has us as a predecessors (we'd have to split the critical edge
12851 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000012852 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012853 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012854 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012855 }
12856 }
12857
Chris Lattner74381062009-08-30 07:44:24 +000012858 // Now that we have an instruction, try combining it to simplify it.
12859 Builder->SetInsertPoint(I->getParent(), I);
12860
Reid Spencera9b81012007-03-26 17:44:01 +000012861#ifndef NDEBUG
12862 std::string OrigI;
12863#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012864 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000012865 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12866
Chris Lattner90ac28c2002-08-02 19:29:35 +000012867 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012868 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012869 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012870 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012871 DEBUG(errs() << "IC: Old = " << *I << '\n'
12872 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012873
Chris Lattnerf523d062004-06-09 05:08:07 +000012874 // Everything uses the new instruction now.
12875 I->replaceAllUsesWith(Result);
12876
12877 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012878 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012879 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012880
Chris Lattner6934a042007-02-11 01:23:03 +000012881 // Move the name to the new instruction first.
12882 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012883
12884 // Insert the new instruction into the basic block...
12885 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012886 BasicBlock::iterator InsertPos = I;
12887
12888 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12889 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12890 ++InsertPos;
12891
12892 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012893
Chris Lattner7a1e9242009-08-30 06:13:40 +000012894 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012895 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012896#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012897 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12898 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012899#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012900
Chris Lattner90ac28c2002-08-02 19:29:35 +000012901 // If the instruction was modified, it's possible that it is now dead.
12902 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012903 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012904 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012905 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012906 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012907 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012908 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012909 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012910 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012911 }
12912 }
12913
Chris Lattner873ff012009-08-30 05:55:36 +000012914 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012915 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012916}
12917
Chris Lattnerec9c3582007-03-03 02:04:50 +000012918
12919bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012920 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012921 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012922 TD = getAnalysisIfAvailable<TargetData>();
12923
Chris Lattner74381062009-08-30 07:44:24 +000012924
12925 /// Builder - This is an IRBuilder that automatically inserts new
12926 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012927 IRBuilder<true, TargetFolder, InstCombineIRInserter>
12928 TheBuilder(F.getContext(), TargetFolder(TD, F.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +000012929 InstCombineIRInserter(Worklist));
12930 Builder = &TheBuilder;
12931
Chris Lattnerec9c3582007-03-03 02:04:50 +000012932 bool EverMadeChange = false;
12933
12934 // Iterate while there is work to do.
12935 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012936 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012937 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012938
12939 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012940 return EverMadeChange;
12941}
12942
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012943FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012944 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012945}