blob: 8366cd6855d5ab76087257416843b79645ed05bb [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 Hernandez83d63912009-09-18 22:35:49 +000045#include "llvm/Analysis/MallocHelper.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);
Chris Lattner0864acf2002-11-04 16:18:53 +0000287 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000288 Instruction *visitFreeInst(FreeInst &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);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000428 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &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
Dan Gohman186a6362009-08-12 16:04:34 +0000633static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000634 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000635 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000636
637 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000638 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000639 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000640 return 0;
641}
642
Chris Lattnerc8802d22003-03-11 00:12:48 +0000643// dyn_castFoldableMul - If this value is a multiply that can be folded into
644// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000645// non-constant operand of the multiply, and set CST to point to the multiplier.
646// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000647//
Dan Gohman186a6362009-08-12 16:04:34 +0000648static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000649 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000650 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000651 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000652 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000653 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000654 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000655 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000656 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000657 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000658 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000659 CST = ConstantInt::get(V->getType()->getContext(),
660 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000661 return I->getOperand(0);
662 }
663 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000664 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000665}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000666
Reid Spencer7177c3a2007-03-25 05:33:51 +0000667/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000668static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000669 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000670 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000671}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000672/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000673static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000674 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000675 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000676}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000677/// MultiplyOverflows - True if the multiply can not be expressed in an int
678/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000679static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000680 uint32_t W = C1->getBitWidth();
681 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
682 if (sign) {
683 LHSExt.sext(W * 2);
684 RHSExt.sext(W * 2);
685 } else {
686 LHSExt.zext(W * 2);
687 RHSExt.zext(W * 2);
688 }
689
690 APInt MulExt = LHSExt * RHSExt;
691
692 if (sign) {
693 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
694 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
695 return MulExt.slt(Min) || MulExt.sgt(Max);
696 } else
697 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
698}
Chris Lattner955f3312004-09-28 21:48:02 +0000699
Reid Spencere7816b52007-03-08 01:52:58 +0000700
Chris Lattner255d8912006-02-11 09:31:47 +0000701/// ShrinkDemandedConstant - Check to see if the specified operand of the
702/// specified instruction is a constant integer. If so, check to see if there
703/// are any bits set in the constant that are not demanded. If so, shrink the
704/// constant and return true.
705static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000706 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000707 assert(I && "No instruction?");
708 assert(OpNo < I->getNumOperands() && "Operand index too large");
709
710 // If the operand is not a constant integer, nothing to do.
711 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
712 if (!OpC) return false;
713
714 // If there are no bits set that aren't demanded, nothing to do.
715 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
716 if ((~Demanded & OpC->getValue()) == 0)
717 return false;
718
719 // This instruction is producing bits that are not demanded. Shrink the RHS.
720 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000721 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000722 return true;
723}
724
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000725// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
726// set of known zero and one bits, compute the maximum and minimum values that
727// could have the specified known zero and known one bits, returning them in
728// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000729static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000730 const APInt& KnownOne,
731 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000732 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
733 KnownZero.getBitWidth() == Min.getBitWidth() &&
734 KnownZero.getBitWidth() == Max.getBitWidth() &&
735 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000736 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000737
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000738 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
739 // bit if it is unknown.
740 Min = KnownOne;
741 Max = KnownOne|UnknownBits;
742
Dan Gohman1c8491e2009-04-25 17:12:48 +0000743 if (UnknownBits.isNegative()) { // Sign bit is unknown
744 Min.set(Min.getBitWidth()-1);
745 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000746 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000747}
748
749// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
750// a set of known zero and one bits, compute the maximum and minimum values that
751// could have the specified known zero and known one bits, returning them in
752// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000753static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000754 const APInt &KnownOne,
755 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000756 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
757 KnownZero.getBitWidth() == Min.getBitWidth() &&
758 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000759 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000760 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000761
762 // The minimum value is when the unknown bits are all zeros.
763 Min = KnownOne;
764 // The maximum value is when the unknown bits are all ones.
765 Max = KnownOne|UnknownBits;
766}
Chris Lattner255d8912006-02-11 09:31:47 +0000767
Chris Lattner886ab6c2009-01-31 08:15:18 +0000768/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
769/// SimplifyDemandedBits knows about. See if the instruction has any
770/// properties that allow us to simplify its operands.
771bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000772 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000773 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
774 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
775
776 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
777 KnownZero, KnownOne, 0);
778 if (V == 0) return false;
779 if (V == &Inst) return true;
780 ReplaceInstUsesWith(Inst, V);
781 return true;
782}
783
784/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
785/// specified instruction operand if possible, updating it in place. It returns
786/// true if it made any change and false otherwise.
787bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
788 APInt &KnownZero, APInt &KnownOne,
789 unsigned Depth) {
790 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
791 KnownZero, KnownOne, Depth);
792 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000793 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000794 return true;
795}
796
797
798/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
799/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000800/// that only the bits set in DemandedMask of the result of V are ever used
801/// downstream. Consequently, depending on the mask and V, it may be possible
802/// to replace V with a constant or one of its operands. In such cases, this
803/// function does the replacement and returns true. In all other cases, it
804/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000805/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000806/// to be zero in the expression. These are provided to potentially allow the
807/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
808/// the expression. KnownOne and KnownZero always follow the invariant that
809/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
810/// the bits in KnownOne and KnownZero may only be accurate for those bits set
811/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
812/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000813///
814/// This returns null if it did not change anything and it permits no
815/// simplification. This returns V itself if it did some simplification of V's
816/// operands based on the information about what bits are demanded. This returns
817/// some other non-null value if it found out that V is equal to another value
818/// in the context where the specified bits are demanded, but not for all users.
819Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
820 APInt &KnownZero, APInt &KnownOne,
821 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000822 assert(V != 0 && "Null pointer of Value???");
823 assert(Depth <= 6 && "Limit Search Depth");
824 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000825 const Type *VTy = V->getType();
826 assert((TD || !isa<PointerType>(VTy)) &&
827 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000828 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
829 (!VTy->isIntOrIntVector() ||
830 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000831 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000832 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000833 "Value *V, DemandedMask, KnownZero and KnownOne "
834 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000835 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
836 // We know all of the bits for a constant!
837 KnownOne = CI->getValue() & DemandedMask;
838 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000839 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000840 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000841 if (isa<ConstantPointerNull>(V)) {
842 // We know all of the bits for a constant!
843 KnownOne.clear();
844 KnownZero = DemandedMask;
845 return 0;
846 }
847
Chris Lattner08d2cc72009-01-31 07:26:06 +0000848 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000849 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000850 if (DemandedMask == 0) { // Not demanding any bits from V.
851 if (isa<UndefValue>(V))
852 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000853 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000854 }
855
Chris Lattner4598c942009-01-31 08:24:16 +0000856 if (Depth == 6) // Limit search depth.
857 return 0;
858
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000859 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
860 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
861
Dan Gohman1c8491e2009-04-25 17:12:48 +0000862 Instruction *I = dyn_cast<Instruction>(V);
863 if (!I) {
864 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
865 return 0; // Only analyze instructions.
866 }
867
Chris Lattner4598c942009-01-31 08:24:16 +0000868 // If there are multiple uses of this value and we aren't at the root, then
869 // we can't do any simplifications of the operands, because DemandedMask
870 // only reflects the bits demanded by *one* of the users.
871 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000872 // Despite the fact that we can't simplify this instruction in all User's
873 // context, we can at least compute the knownzero/knownone bits, and we can
874 // do simplifications that apply to *just* the one user if we know that
875 // this instruction has a simpler value in that context.
876 if (I->getOpcode() == Instruction::And) {
877 // If either the LHS or the RHS are Zero, the result is zero.
878 ComputeMaskedBits(I->getOperand(1), DemandedMask,
879 RHSKnownZero, RHSKnownOne, Depth+1);
880 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
881 LHSKnownZero, LHSKnownOne, Depth+1);
882
883 // If all of the demanded bits are known 1 on one side, return the other.
884 // These bits cannot contribute to the result of the 'and' in this
885 // context.
886 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
887 (DemandedMask & ~LHSKnownZero))
888 return I->getOperand(0);
889 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
890 (DemandedMask & ~RHSKnownZero))
891 return I->getOperand(1);
892
893 // If all of the demanded bits in the inputs are known zeros, return zero.
894 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000895 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000896
897 } else if (I->getOpcode() == Instruction::Or) {
898 // We can simplify (X|Y) -> X or Y in the user's context if we know that
899 // only bits from X or Y are demanded.
900
901 // If either the LHS or the RHS are One, the result is One.
902 ComputeMaskedBits(I->getOperand(1), DemandedMask,
903 RHSKnownZero, RHSKnownOne, Depth+1);
904 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
905 LHSKnownZero, LHSKnownOne, Depth+1);
906
907 // If all of the demanded bits are known zero on one side, return the
908 // other. These bits cannot contribute to the result of the 'or' in this
909 // context.
910 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
911 (DemandedMask & ~LHSKnownOne))
912 return I->getOperand(0);
913 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
914 (DemandedMask & ~RHSKnownOne))
915 return I->getOperand(1);
916
917 // If all of the potentially set bits on one side are known to be set on
918 // the other side, just use the 'other' side.
919 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
920 (DemandedMask & (~RHSKnownZero)))
921 return I->getOperand(0);
922 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
923 (DemandedMask & (~LHSKnownZero)))
924 return I->getOperand(1);
925 }
926
Chris Lattner4598c942009-01-31 08:24:16 +0000927 // Compute the KnownZero/KnownOne bits to simplify things downstream.
928 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
929 return 0;
930 }
931
932 // If this is the root being simplified, allow it to have multiple uses,
933 // just set the DemandedMask to all bits so that we can try to simplify the
934 // operands. This allows visitTruncInst (for example) to simplify the
935 // operand of a trunc without duplicating all the logic below.
936 if (Depth == 0 && !V->hasOneUse())
937 DemandedMask = APInt::getAllOnesValue(BitWidth);
938
Reid Spencer8cb68342007-03-12 17:25:59 +0000939 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000940 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000941 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000942 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000943 case Instruction::And:
944 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000945 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
946 RHSKnownZero, RHSKnownOne, Depth+1) ||
947 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000948 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000949 return I;
950 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
951 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000952
953 // If all of the demanded bits are known 1 on one side, return the other.
954 // These bits cannot contribute to the result of the 'and'.
955 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
956 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000957 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000958 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
959 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000960 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000961
962 // If all of the demanded bits in the inputs are known zeros, return zero.
963 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000964 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000965
966 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000967 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000968 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000969
970 // Output known-1 bits are only known if set in both the LHS & RHS.
971 RHSKnownOne &= LHSKnownOne;
972 // Output known-0 are known to be clear if zero in either the LHS | RHS.
973 RHSKnownZero |= LHSKnownZero;
974 break;
975 case Instruction::Or:
976 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000977 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
978 RHSKnownZero, RHSKnownOne, Depth+1) ||
979 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000980 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000981 return I;
982 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
983 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000984
985 // If all of the demanded bits are known zero on one side, return the other.
986 // These bits cannot contribute to the result of the 'or'.
987 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
988 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000989 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000990 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
991 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000992 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000993
994 // If all of the potentially set bits on one side are known to be set on
995 // the other side, just use the 'other' side.
996 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
997 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000998 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000999 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1000 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001001 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001002
1003 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001004 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001005 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001006
1007 // Output known-0 bits are only known if clear in both the LHS & RHS.
1008 RHSKnownZero &= LHSKnownZero;
1009 // Output known-1 are known to be set if set in either the LHS | RHS.
1010 RHSKnownOne |= LHSKnownOne;
1011 break;
1012 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001013 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1014 RHSKnownZero, RHSKnownOne, Depth+1) ||
1015 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001016 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001017 return I;
1018 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1019 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001020
1021 // If all of the demanded bits are known zero on one side, return the other.
1022 // These bits cannot contribute to the result of the 'xor'.
1023 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001024 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001025 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001026 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001027
1028 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1029 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1030 (RHSKnownOne & LHSKnownOne);
1031 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1032 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1033 (RHSKnownOne & LHSKnownZero);
1034
1035 // If all of the demanded bits are known to be zero on one side or the
1036 // other, turn this into an *inclusive* or.
1037 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001038 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1039 Instruction *Or =
1040 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1041 I->getName());
1042 return InsertNewInstBefore(Or, *I);
1043 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001044
1045 // If all of the demanded bits on one side are known, and all of the set
1046 // bits on that side are also known to be set on the other side, turn this
1047 // into an AND, as we know the bits will be cleared.
1048 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1049 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1050 // all known
1051 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001052 Constant *AndC = Constant::getIntegerValue(VTy,
1053 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001054 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001055 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001057 }
1058 }
1059
1060 // If the RHS is a constant, see if we can simplify it.
1061 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001062 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001063 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001064
Chris Lattnerd0883142009-10-11 22:22:13 +00001065 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1066 // are flipping are known to be set, then the xor is just resetting those
1067 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1068 // simplifying both of them.
1069 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1070 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1071 isa<ConstantInt>(I->getOperand(1)) &&
1072 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1073 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1074 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1075 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1076 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1077
1078 Constant *AndC =
1079 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1080 Instruction *NewAnd =
1081 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1082 InsertNewInstBefore(NewAnd, *I);
1083
1084 Constant *XorC =
1085 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1086 Instruction *NewXor =
1087 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1088 return InsertNewInstBefore(NewXor, *I);
1089 }
1090
1091
Reid Spencer8cb68342007-03-12 17:25:59 +00001092 RHSKnownZero = KnownZeroOut;
1093 RHSKnownOne = KnownOneOut;
1094 break;
1095 }
1096 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001097 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1098 RHSKnownZero, RHSKnownOne, Depth+1) ||
1099 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001100 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001101 return I;
1102 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1103 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001104
1105 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001106 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1107 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001108 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001109
1110 // Only known if known in both the LHS and RHS.
1111 RHSKnownOne &= LHSKnownOne;
1112 RHSKnownZero &= LHSKnownZero;
1113 break;
1114 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001115 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001116 DemandedMask.zext(truncBf);
1117 RHSKnownZero.zext(truncBf);
1118 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001119 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001120 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001121 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001122 DemandedMask.trunc(BitWidth);
1123 RHSKnownZero.trunc(BitWidth);
1124 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001125 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001126 break;
1127 }
1128 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001129 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001130 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001131
1132 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1133 if (const VectorType *SrcVTy =
1134 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1135 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1136 // Don't touch a bitcast between vectors of different element counts.
1137 return false;
1138 } else
1139 // Don't touch a scalar-to-vector bitcast.
1140 return false;
1141 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1142 // Don't touch a vector-to-scalar bitcast.
1143 return false;
1144
Chris Lattner886ab6c2009-01-31 08:15:18 +00001145 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001146 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001147 return I;
1148 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001149 break;
1150 case Instruction::ZExt: {
1151 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001152 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001153
Zhou Shengd48653a2007-03-29 04:45:55 +00001154 DemandedMask.trunc(SrcBitWidth);
1155 RHSKnownZero.trunc(SrcBitWidth);
1156 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001157 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001158 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001159 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001160 DemandedMask.zext(BitWidth);
1161 RHSKnownZero.zext(BitWidth);
1162 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001163 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001164 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001165 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001166 break;
1167 }
1168 case Instruction::SExt: {
1169 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001170 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001171
Reid Spencer8cb68342007-03-12 17:25:59 +00001172 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001173 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001174
Zhou Sheng01542f32007-03-29 02:26:30 +00001175 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001176 // If any of the sign extended bits are demanded, we know that the sign
1177 // bit is demanded.
1178 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001179 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001180
Zhou Shengd48653a2007-03-29 04:45:55 +00001181 InputDemandedBits.trunc(SrcBitWidth);
1182 RHSKnownZero.trunc(SrcBitWidth);
1183 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001184 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001185 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001186 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001187 InputDemandedBits.zext(BitWidth);
1188 RHSKnownZero.zext(BitWidth);
1189 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001190 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001191
1192 // If the sign bit of the input is known set or clear, then we know the
1193 // top bits of the result.
1194
1195 // If the input sign bit is known zero, or if the NewBits are not demanded
1196 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001197 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001198 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001199 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1200 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001201 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001202 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001203 }
1204 break;
1205 }
1206 case Instruction::Add: {
1207 // Figure out what the input bits are. If the top bits of the and result
1208 // are not demanded, then the add doesn't demand them from its input
1209 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001210 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001211
1212 // If there is a constant on the RHS, there are a variety of xformations
1213 // we can do.
1214 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1215 // If null, this should be simplified elsewhere. Some of the xforms here
1216 // won't work if the RHS is zero.
1217 if (RHS->isZero())
1218 break;
1219
1220 // If the top bit of the output is demanded, demand everything from the
1221 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001222 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001223
1224 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001225 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001226 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001227 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001228
1229 // If the RHS of the add has bits set that can't affect the input, reduce
1230 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001231 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001232 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001233
1234 // Avoid excess work.
1235 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1236 break;
1237
1238 // Turn it into OR if input bits are zero.
1239 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1240 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001241 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001242 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001243 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001244 }
1245
1246 // We can say something about the output known-zero and known-one bits,
1247 // depending on potential carries from the input constant and the
1248 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1249 // bits set and the RHS constant is 0x01001, then we know we have a known
1250 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1251
1252 // To compute this, we first compute the potential carry bits. These are
1253 // the bits which may be modified. I'm not aware of a better way to do
1254 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001255 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001256 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001257
1258 // Now that we know which bits have carries, compute the known-1/0 sets.
1259
1260 // Bits are known one if they are known zero in one operand and one in the
1261 // other, and there is no input carry.
1262 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1263 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1264
1265 // Bits are known zero if they are known zero in both operands and there
1266 // is no input carry.
1267 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1268 } else {
1269 // If the high-bits of this ADD are not demanded, then it does not demand
1270 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001271 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001272 // Right fill the mask of bits for this ADD to demand the most
1273 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001274 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001275 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1276 LHSKnownZero, LHSKnownOne, Depth+1) ||
1277 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001278 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001279 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001280 }
1281 }
1282 break;
1283 }
1284 case Instruction::Sub:
1285 // If the high-bits of this SUB are not demanded, then it does not demand
1286 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001287 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 // Right fill the mask of bits for this SUB to demand the most
1289 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001290 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001291 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001292 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1293 LHSKnownZero, LHSKnownOne, Depth+1) ||
1294 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001296 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001297 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001298 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1299 // the known zeros and ones.
1300 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001301 break;
1302 case Instruction::Shl:
1303 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001304 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001305 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001306 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001307 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001308 return I;
1309 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 RHSKnownZero <<= ShiftAmt;
1311 RHSKnownOne <<= ShiftAmt;
1312 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001313 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001314 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001315 }
1316 break;
1317 case Instruction::LShr:
1318 // For a logical shift right
1319 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001320 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001321
Reid Spencer8cb68342007-03-12 17:25:59 +00001322 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001323 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001324 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001325 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001326 return I;
1327 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001328 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1329 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001330 if (ShiftAmt) {
1331 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001332 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001333 RHSKnownZero |= HighBits; // high bits known zero.
1334 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001335 }
1336 break;
1337 case Instruction::AShr:
1338 // If this is an arithmetic shift right and only the low-bit is set, we can
1339 // always convert this into a logical shr, even if the shift amount is
1340 // variable. The low bit of the shift cannot be an input sign bit unless
1341 // the shift amount is >= the size of the datatype, which is undefined.
1342 if (DemandedMask == 1) {
1343 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001344 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001345 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001346 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001347 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001348
1349 // If the sign bit is the only bit demanded by this ashr, then there is no
1350 // need to do it, the shift doesn't change the high bit.
1351 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001352 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001353
1354 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001355 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001356
Reid Spencer8cb68342007-03-12 17:25:59 +00001357 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001358 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001359 // If any of the "high bits" are demanded, we should set the sign bit as
1360 // demanded.
1361 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1362 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001363 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001364 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001365 return I;
1366 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001367 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001368 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001369 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1370 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1371
1372 // Handle the sign bits.
1373 APInt SignBit(APInt::getSignBit(BitWidth));
1374 // Adjust to where it is now in the mask.
1375 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1376
1377 // If the input sign bit is known to be zero, or if none of the top bits
1378 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001379 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001380 (HighBits & ~DemandedMask) == HighBits) {
1381 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001382 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001383 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001384 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001385 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1386 RHSKnownOne |= HighBits;
1387 }
1388 }
1389 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001390 case Instruction::SRem:
1391 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001392 APInt RA = Rem->getValue().abs();
1393 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001394 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001395 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001396
Nick Lewycky8e394322008-11-02 02:41:50 +00001397 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001398 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001399 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001400 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001401 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001402
1403 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1404 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001405
1406 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001407
Chris Lattner886ab6c2009-01-31 08:15:18 +00001408 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001409 }
1410 }
1411 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001412 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001413 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1414 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001415 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1416 KnownZero2, KnownOne2, Depth+1) ||
1417 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001418 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001419 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001420
Chris Lattner455e9ab2009-01-21 18:09:24 +00001421 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001422 Leaders = std::max(Leaders,
1423 KnownZero2.countLeadingOnes());
1424 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001425 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001426 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001427 case Instruction::Call:
1428 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1429 switch (II->getIntrinsicID()) {
1430 default: break;
1431 case Intrinsic::bswap: {
1432 // If the only bits demanded come from one byte of the bswap result,
1433 // just shift the input byte into position to eliminate the bswap.
1434 unsigned NLZ = DemandedMask.countLeadingZeros();
1435 unsigned NTZ = DemandedMask.countTrailingZeros();
1436
1437 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1438 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1439 // have 14 leading zeros, round to 8.
1440 NLZ &= ~7;
1441 NTZ &= ~7;
1442 // If we need exactly one byte, we can do this transformation.
1443 if (BitWidth-NLZ-NTZ == 8) {
1444 unsigned ResultBit = NTZ;
1445 unsigned InputBit = BitWidth-NTZ-8;
1446
1447 // Replace this with either a left or right shift to get the byte into
1448 // the right place.
1449 Instruction *NewVal;
1450 if (InputBit > ResultBit)
1451 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001452 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001453 else
1454 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001455 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001456 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001457 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001458 }
1459
1460 // TODO: Could compute known zero/one bits based on the input.
1461 break;
1462 }
1463 }
1464 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001465 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001466 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001467 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001468
1469 // If the client is only demanding bits that we know, return the known
1470 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001471 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1472 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001473 return false;
1474}
1475
Chris Lattner867b99f2006-10-05 06:55:50 +00001476
Mon P Wangaeb06d22008-11-10 04:46:22 +00001477/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001478/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001479/// actually used by the caller. This method analyzes which elements of the
1480/// operand are undef and returns that information in UndefElts.
1481///
1482/// If the information about demanded elements can be used to simplify the
1483/// operation, the operation is simplified, then the resultant value is
1484/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001485Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1486 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001487 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001488 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001489 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001490 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001491
1492 if (isa<UndefValue>(V)) {
1493 // If the entire vector is undefined, just return this info.
1494 UndefElts = EltMask;
1495 return 0;
1496 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1497 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001498 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001499 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001500
Chris Lattner867b99f2006-10-05 06:55:50 +00001501 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001502 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1503 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001504 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001505
1506 std::vector<Constant*> Elts;
1507 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001508 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001509 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001510 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001511 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1512 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001513 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001514 } else { // Otherwise, defined.
1515 Elts.push_back(CP->getOperand(i));
1516 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001517
Chris Lattner867b99f2006-10-05 06:55:50 +00001518 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001519 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001520 return NewCP != CP ? NewCP : 0;
1521 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001522 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001523 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001524
1525 // Check if this is identity. If so, return 0 since we are not simplifying
1526 // anything.
1527 if (DemandedElts == ((1ULL << VWidth) -1))
1528 return 0;
1529
Reid Spencer9d6565a2007-02-15 02:26:10 +00001530 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001531 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001532 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001533 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001534 for (unsigned i = 0; i != VWidth; ++i) {
1535 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1536 Elts.push_back(Elt);
1537 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001538 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001539 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001540 }
1541
Dan Gohman488fbfc2008-09-09 18:11:14 +00001542 // Limit search depth.
1543 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001544 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001545
1546 // If multiple users are using the root value, procede with
1547 // simplification conservatively assuming that all elements
1548 // are needed.
1549 if (!V->hasOneUse()) {
1550 // Quit if we find multiple users of a non-root value though.
1551 // They'll be handled when it's their turn to be visited by
1552 // the main instcombine process.
1553 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001554 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001555 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001556
1557 // Conservatively assume that all elements are needed.
1558 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001559 }
1560
1561 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001562 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001563
1564 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001565 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001566 Value *TmpV;
1567 switch (I->getOpcode()) {
1568 default: break;
1569
1570 case Instruction::InsertElement: {
1571 // If this is a variable index, we don't know which element it overwrites.
1572 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001573 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001574 if (Idx == 0) {
1575 // Note that we can't propagate undef elt info, because we don't know
1576 // which elt is getting updated.
1577 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1578 UndefElts2, Depth+1);
1579 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1580 break;
1581 }
1582
1583 // If this is inserting an element that isn't demanded, remove this
1584 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001585 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001586 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1587 Worklist.Add(I);
1588 return I->getOperand(0);
1589 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001590
1591 // Otherwise, the element inserted overwrites whatever was there, so the
1592 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001593 APInt DemandedElts2 = DemandedElts;
1594 DemandedElts2.clear(IdxNo);
1595 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001596 UndefElts, Depth+1);
1597 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1598
1599 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001600 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001601 break;
1602 }
1603 case Instruction::ShuffleVector: {
1604 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001605 uint64_t LHSVWidth =
1606 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001607 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001608 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001609 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001610 unsigned MaskVal = Shuffle->getMaskValue(i);
1611 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001612 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001613 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001614 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001615 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001616 else
Evan Cheng388df622009-02-03 10:05:09 +00001617 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001618 }
1619 }
1620 }
1621
Nate Begeman7b254672009-02-11 22:36:25 +00001622 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001623 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001624 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001625 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1626
Nate Begeman7b254672009-02-11 22:36:25 +00001627 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001628 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1629 UndefElts3, Depth+1);
1630 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1631
1632 bool NewUndefElts = false;
1633 for (unsigned i = 0; i < VWidth; i++) {
1634 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001635 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001636 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001637 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001638 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001639 NewUndefElts = true;
1640 UndefElts.set(i);
1641 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001642 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001643 if (UndefElts3[MaskVal - LHSVWidth]) {
1644 NewUndefElts = true;
1645 UndefElts.set(i);
1646 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001647 }
1648 }
1649
1650 if (NewUndefElts) {
1651 // Add additional discovered undefs.
1652 std::vector<Constant*> Elts;
1653 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001654 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001655 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001656 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001657 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001658 Shuffle->getMaskValue(i)));
1659 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001660 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001661 MadeChange = true;
1662 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001663 break;
1664 }
Chris Lattner69878332007-04-14 22:29:23 +00001665 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001666 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001667 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1668 if (!VTy) break;
1669 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001670 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001671 unsigned Ratio;
1672
1673 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001674 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001675 // elements as are demanded of us.
1676 Ratio = 1;
1677 InputDemandedElts = DemandedElts;
1678 } else if (VWidth > InVWidth) {
1679 // Untested so far.
1680 break;
1681
1682 // If there are more elements in the result than there are in the source,
1683 // then an input element is live if any of the corresponding output
1684 // elements are live.
1685 Ratio = VWidth/InVWidth;
1686 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001687 if (DemandedElts[OutIdx])
1688 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001689 }
1690 } else {
1691 // Untested so far.
1692 break;
1693
1694 // If there are more elements in the source than there are in the result,
1695 // then an input element is live if the corresponding output element is
1696 // live.
1697 Ratio = InVWidth/VWidth;
1698 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001699 if (DemandedElts[InIdx/Ratio])
1700 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001701 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001702
Chris Lattner69878332007-04-14 22:29:23 +00001703 // div/rem demand all inputs, because they don't want divide by zero.
1704 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1705 UndefElts2, Depth+1);
1706 if (TmpV) {
1707 I->setOperand(0, TmpV);
1708 MadeChange = true;
1709 }
1710
1711 UndefElts = UndefElts2;
1712 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001713 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001714 // If there are more elements in the result than there are in the source,
1715 // then an output element is undef if the corresponding input element is
1716 // undef.
1717 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001718 if (UndefElts2[OutIdx/Ratio])
1719 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001720 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001721 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001722 // If there are more elements in the source than there are in the result,
1723 // then a result element is undef if all of the corresponding input
1724 // elements are undef.
1725 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1726 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001727 if (!UndefElts2[InIdx]) // Not undef?
1728 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001729 }
1730 break;
1731 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001732 case Instruction::And:
1733 case Instruction::Or:
1734 case Instruction::Xor:
1735 case Instruction::Add:
1736 case Instruction::Sub:
1737 case Instruction::Mul:
1738 // div/rem demand all inputs, because they don't want divide by zero.
1739 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1740 UndefElts, Depth+1);
1741 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1742 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1743 UndefElts2, Depth+1);
1744 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1745
1746 // Output elements are undefined if both are undefined. Consider things
1747 // like undef&0. The result is known zero, not undef.
1748 UndefElts &= UndefElts2;
1749 break;
1750
1751 case Instruction::Call: {
1752 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1753 if (!II) break;
1754 switch (II->getIntrinsicID()) {
1755 default: break;
1756
1757 // Binary vector operations that work column-wise. A dest element is a
1758 // function of the corresponding input elements from the two inputs.
1759 case Intrinsic::x86_sse_sub_ss:
1760 case Intrinsic::x86_sse_mul_ss:
1761 case Intrinsic::x86_sse_min_ss:
1762 case Intrinsic::x86_sse_max_ss:
1763 case Intrinsic::x86_sse2_sub_sd:
1764 case Intrinsic::x86_sse2_mul_sd:
1765 case Intrinsic::x86_sse2_min_sd:
1766 case Intrinsic::x86_sse2_max_sd:
1767 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1768 UndefElts, Depth+1);
1769 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1770 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1771 UndefElts2, Depth+1);
1772 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1773
1774 // If only the low elt is demanded and this is a scalarizable intrinsic,
1775 // scalarize it now.
1776 if (DemandedElts == 1) {
1777 switch (II->getIntrinsicID()) {
1778 default: break;
1779 case Intrinsic::x86_sse_sub_ss:
1780 case Intrinsic::x86_sse_mul_ss:
1781 case Intrinsic::x86_sse2_sub_sd:
1782 case Intrinsic::x86_sse2_mul_sd:
1783 // TODO: Lower MIN/MAX/ABS/etc
1784 Value *LHS = II->getOperand(1);
1785 Value *RHS = II->getOperand(2);
1786 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001787 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001788 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001789 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001790 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001791
1792 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001793 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001794 case Intrinsic::x86_sse_sub_ss:
1795 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001796 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001797 II->getName()), *II);
1798 break;
1799 case Intrinsic::x86_sse_mul_ss:
1800 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001801 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001802 II->getName()), *II);
1803 break;
1804 }
1805
1806 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001807 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001808 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001809 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001810 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001811 return New;
1812 }
1813 }
1814
1815 // Output elements are undefined if both are undefined. Consider things
1816 // like undef&0. The result is known zero, not undef.
1817 UndefElts &= UndefElts2;
1818 break;
1819 }
1820 break;
1821 }
1822 }
1823 return MadeChange ? I : 0;
1824}
1825
Dan Gohman45b4e482008-05-19 22:14:15 +00001826
Chris Lattner564a7272003-08-13 19:01:45 +00001827/// AssociativeOpt - Perform an optimization on an associative operator. This
1828/// function is designed to check a chain of associative operators for a
1829/// potential to apply a certain optimization. Since the optimization may be
1830/// applicable if the expression was reassociated, this checks the chain, then
1831/// reassociates the expression as necessary to expose the optimization
1832/// opportunity. This makes use of a special Functor, which must define
1833/// 'shouldApply' and 'apply' methods.
1834///
1835template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001836static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001837 unsigned Opcode = Root.getOpcode();
1838 Value *LHS = Root.getOperand(0);
1839
1840 // Quick check, see if the immediate LHS matches...
1841 if (F.shouldApply(LHS))
1842 return F.apply(Root);
1843
1844 // Otherwise, if the LHS is not of the same opcode as the root, return.
1845 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001846 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001847 // Should we apply this transform to the RHS?
1848 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1849
1850 // If not to the RHS, check to see if we should apply to the LHS...
1851 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1852 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1853 ShouldApply = true;
1854 }
1855
1856 // If the functor wants to apply the optimization to the RHS of LHSI,
1857 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1858 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001859 // Now all of the instructions are in the current basic block, go ahead
1860 // and perform the reassociation.
1861 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1862
1863 // First move the selected RHS to the LHS of the root...
1864 Root.setOperand(0, LHSI->getOperand(1));
1865
1866 // Make what used to be the LHS of the root be the user of the root...
1867 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001868 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001869 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001870 return 0;
1871 }
Chris Lattner65725312004-04-16 18:08:07 +00001872 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001873 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001874 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001875 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001876 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001877
1878 // Now propagate the ExtraOperand down the chain of instructions until we
1879 // get to LHSI.
1880 while (TmpLHSI != LHSI) {
1881 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001882 // Move the instruction to immediately before the chain we are
1883 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001884 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001885 ARI = NextLHSI;
1886
Chris Lattner564a7272003-08-13 19:01:45 +00001887 Value *NextOp = NextLHSI->getOperand(1);
1888 NextLHSI->setOperand(1, ExtraOperand);
1889 TmpLHSI = NextLHSI;
1890 ExtraOperand = NextOp;
1891 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001892
Chris Lattner564a7272003-08-13 19:01:45 +00001893 // Now that the instructions are reassociated, have the functor perform
1894 // the transformation...
1895 return F.apply(Root);
1896 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001897
Chris Lattner564a7272003-08-13 19:01:45 +00001898 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1899 }
1900 return 0;
1901}
1902
Dan Gohman844731a2008-05-13 00:00:25 +00001903namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001904
Nick Lewycky02d639f2008-05-23 04:34:58 +00001905// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001906struct AddRHS {
1907 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001908 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001909 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1910 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001911 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001912 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001913 }
1914};
1915
1916// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1917// iff C1&C2 == 0
1918struct AddMaskingAnd {
1919 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001920 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001921 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001922 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001923 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001924 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001925 }
1926 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001927 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001928 }
1929};
1930
Dan Gohman844731a2008-05-13 00:00:25 +00001931}
1932
Chris Lattner6e7ba452005-01-01 16:22:27 +00001933static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001934 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001935 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001936 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001937
Chris Lattner2eefe512004-04-09 19:05:30 +00001938 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001939 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1940 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001941
Chris Lattner2eefe512004-04-09 19:05:30 +00001942 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1943 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001944 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1945 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001946 }
1947
1948 Value *Op0 = SO, *Op1 = ConstOperand;
1949 if (!ConstIsRHS)
1950 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001951
Chris Lattner6e7ba452005-01-01 16:22:27 +00001952 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001953 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1954 SO->getName()+".op");
1955 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1956 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1957 SO->getName()+".cmp");
1958 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1959 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1960 SO->getName()+".cmp");
1961 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001962}
1963
1964// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1965// constant as the other operand, try to fold the binary operator into the
1966// select arguments. This also works for Cast instructions, which obviously do
1967// not have a second operand.
1968static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1969 InstCombiner *IC) {
1970 // Don't modify shared select instructions
1971 if (!SI->hasOneUse()) return 0;
1972 Value *TV = SI->getOperand(1);
1973 Value *FV = SI->getOperand(2);
1974
1975 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001976 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001977 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001978
Chris Lattner6e7ba452005-01-01 16:22:27 +00001979 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1980 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1981
Gabor Greif051a9502008-04-06 20:25:17 +00001982 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1983 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001984 }
1985 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001986}
1987
Chris Lattner4e998b22004-09-29 05:07:12 +00001988
Chris Lattner5d1704d2009-09-27 19:57:57 +00001989/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1990/// has a PHI node as operand #0, see if we can fold the instruction into the
1991/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00001992///
1993/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1994/// that would normally be unprofitable because they strongly encourage jump
1995/// threading.
1996Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1997 bool AllowAggressive) {
1998 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00001999 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002000 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002001 if (NumPHIValues == 0 ||
2002 // We normally only transform phis with a single use, unless we're trying
2003 // hard to make jump threading happen.
2004 (!PN->hasOneUse() && !AllowAggressive))
2005 return 0;
2006
2007
Chris Lattner5d1704d2009-09-27 19:57:57 +00002008 // Check to see if all of the operands of the PHI are simple constants
2009 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002010 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2011 // bail out. We don't do arbitrary constant expressions here because moving
2012 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002013 BasicBlock *NonConstBB = 0;
2014 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002015 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2016 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002017 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002018 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002019 NonConstBB = PN->getIncomingBlock(i);
2020
2021 // If the incoming non-constant value is in I's block, we have an infinite
2022 // loop.
2023 if (NonConstBB == I.getParent())
2024 return 0;
2025 }
2026
2027 // If there is exactly one non-constant value, we can insert a copy of the
2028 // operation in that block. However, if this is a critical edge, we would be
2029 // inserting the computation one some other paths (e.g. inside a loop). Only
2030 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002031 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002032 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2033 if (!BI || !BI->isUnconditional()) return 0;
2034 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002035
2036 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002037 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002038 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002039 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002040 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002041
2042 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002043 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2044 // We only currently try to fold the condition of a select when it is a phi,
2045 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002046 Value *TrueV = SI->getTrueValue();
2047 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002048 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002049 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002050 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002051 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2052 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002053 Value *InV = 0;
2054 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002055 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002056 } else {
2057 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002058 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2059 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002060 "phitmp", NonConstBB->getTerminator());
2061 Worklist.Add(cast<Instruction>(InV));
2062 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002063 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002064 }
2065 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002066 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002067 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002068 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002069 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002070 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002071 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002072 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002073 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002074 } else {
2075 assert(PN->getIncomingBlock(i) == NonConstBB);
2076 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002077 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002078 PN->getIncomingValue(i), C, "phitmp",
2079 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002080 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002081 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002082 CI->getPredicate(),
2083 PN->getIncomingValue(i), C, "phitmp",
2084 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002085 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002086 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002087
Chris Lattner7a1e9242009-08-30 06:13:40 +00002088 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002089 }
2090 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002091 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002092 } else {
2093 CastInst *CI = cast<CastInst>(&I);
2094 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002095 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002096 Value *InV;
2097 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002098 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002099 } else {
2100 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002101 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002102 I.getType(), "phitmp",
2103 NonConstBB->getTerminator());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002104 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002105 }
2106 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002107 }
2108 }
2109 return ReplaceInstUsesWith(I, NewPN);
2110}
2111
Chris Lattner2454a2e2008-01-29 06:52:45 +00002112
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002113/// WillNotOverflowSignedAdd - Return true if we can prove that:
2114/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2115/// This basically requires proving that the add in the original type would not
2116/// overflow to change the sign bit or have a carry out.
2117bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2118 // There are different heuristics we can use for this. Here are some simple
2119 // ones.
2120
2121 // Add has the property that adding any two 2's complement numbers can only
2122 // have one carry bit which can change a sign. As such, if LHS and RHS each
2123 // have at least two sign bits, we know that the addition of the two values will
2124 // sign extend fine.
2125 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2126 return true;
2127
2128
2129 // If one of the operands only has one non-zero bit, and if the other operand
2130 // has a known-zero bit in a more significant place than it (not including the
2131 // sign bit) the ripple may go up to and fill the zero, but won't change the
2132 // sign. For example, (X & ~4) + 1.
2133
2134 // TODO: Implement.
2135
2136 return false;
2137}
2138
Chris Lattner2454a2e2008-01-29 06:52:45 +00002139
Chris Lattner7e708292002-06-25 16:13:24 +00002140Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002141 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002142 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002143
Chris Lattner66331a42004-04-10 22:01:55 +00002144 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002145 // X + undef -> undef
2146 if (isa<UndefValue>(RHS))
2147 return ReplaceInstUsesWith(I, RHS);
2148
Chris Lattner66331a42004-04-10 22:01:55 +00002149 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002150 if (RHSC->isNullValue())
2151 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002152
Chris Lattner66331a42004-04-10 22:01:55 +00002153 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002154 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002155 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002156 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002157 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002158 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002159
2160 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2161 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002162 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002163 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002164
Eli Friedman709b33d2009-07-13 22:27:52 +00002165 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002166 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002167 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002168 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002169 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002170
2171 if (isa<PHINode>(LHS))
2172 if (Instruction *NV = FoldOpIntoPhi(I))
2173 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002174
Chris Lattner4f637d42006-01-06 17:59:59 +00002175 ConstantInt *XorRHS = 0;
2176 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002177 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002178 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002179 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002180 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002181
Zhou Sheng4351c642007-04-02 08:20:41 +00002182 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002183 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2184 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002185 do {
2186 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002187 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2188 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002189 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2190 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002191 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002192 if (!MaskedValueIsZero(XorLHS,
2193 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002194 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002195 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002196 }
2197 }
2198 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002199 C0080Val = APIntOps::lshr(C0080Val, Size);
2200 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2201 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002202
Reid Spencer35c38852007-03-28 01:36:16 +00002203 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002204 // with funny bit widths then this switch statement should be removed. It
2205 // is just here to get the size of the "middle" type back up to something
2206 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002207 const Type *MiddleType = 0;
2208 switch (Size) {
2209 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002210 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2211 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2212 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002213 }
2214 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002215 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002216 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002217 }
2218 }
Chris Lattner66331a42004-04-10 22:01:55 +00002219 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002220
Owen Anderson1d0be152009-08-13 21:58:54 +00002221 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002222 return BinaryOperator::CreateXor(LHS, RHS);
2223
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002224 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002225 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002226 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002227 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002228
2229 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2230 if (RHSI->getOpcode() == Instruction::Sub)
2231 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2232 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2233 }
2234 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2235 if (LHSI->getOpcode() == Instruction::Sub)
2236 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2237 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2238 }
Robert Bocchino71698282004-07-27 21:02:21 +00002239 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002240
Chris Lattner5c4afb92002-05-08 22:46:53 +00002241 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002242 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002243 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002244 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002245 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002246 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002247 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002248 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002249 }
2250
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002251 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002252 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002253
2254 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002255 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002256 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002257 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002258
Misha Brukmanfd939082005-04-21 23:48:37 +00002259
Chris Lattner50af16a2004-11-13 19:50:12 +00002260 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002261 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002262 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002263 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002264
2265 // X*C1 + X*C2 --> X * (C1+C2)
2266 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002267 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002268 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002269 }
2270
2271 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002272 if (dyn_castFoldableMul(RHS, C2) == LHS)
2273 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002274
Chris Lattnere617c9e2007-01-05 02:17:46 +00002275 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002276 if (dyn_castNotVal(LHS) == RHS ||
2277 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002278 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002279
Chris Lattnerad3448c2003-02-18 19:57:07 +00002280
Chris Lattner564a7272003-08-13 19:01:45 +00002281 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002282 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2283 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002284 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002285
2286 // A+B --> A|B iff A and B have no bits set in common.
2287 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2288 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2289 APInt LHSKnownOne(IT->getBitWidth(), 0);
2290 APInt LHSKnownZero(IT->getBitWidth(), 0);
2291 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2292 if (LHSKnownZero != 0) {
2293 APInt RHSKnownOne(IT->getBitWidth(), 0);
2294 APInt RHSKnownZero(IT->getBitWidth(), 0);
2295 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2296
2297 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002298 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002299 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002300 }
2301 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002302
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002303 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002304 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002305 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002306 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2307 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002308 if (W != Y) {
2309 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002310 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002311 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002312 std::swap(W, X);
2313 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002314 std::swap(Y, Z);
2315 std::swap(W, X);
2316 }
2317 }
2318
2319 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002320 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002321 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002322 }
2323 }
2324 }
2325
Chris Lattner6b032052003-10-02 15:11:26 +00002326 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002327 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002328 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002329 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002330
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002331 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002332 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002333 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002334 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002335 if (Anded == CRHS) {
2336 // See if all bits from the first bit set in the Add RHS up are included
2337 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002338 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002339
2340 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002341 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002342
2343 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002344 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002345
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002346 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2347 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002348 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002349 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002350 }
2351 }
2352 }
2353
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002354 // Try to fold constant add into select arguments.
2355 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002356 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002357 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002358 }
2359
Chris Lattner42790482007-12-20 01:56:58 +00002360 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002361 {
2362 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002363 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002364 if (!SI) {
2365 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002366 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002367 }
Chris Lattner42790482007-12-20 01:56:58 +00002368 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002369 Value *TV = SI->getTrueValue();
2370 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002371 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002372
2373 // Can we fold the add into the argument of the select?
2374 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002375 if (match(FV, m_Zero()) &&
2376 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002377 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002378 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002379 if (match(TV, m_Zero()) &&
2380 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002381 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002382 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002383 }
2384 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002385
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002386 // Check for (add (sext x), y), see if we can merge this into an
2387 // integer add followed by a sext.
2388 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2389 // (add (sext x), cst) --> (sext (add x, cst'))
2390 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2391 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002392 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002393 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002394 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002395 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2396 // Insert the new, smaller add.
Chris Lattner74381062009-08-30 07:44:24 +00002397 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2398 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002399 return new SExtInst(NewAdd, I.getType());
2400 }
2401 }
2402
2403 // (add (sext x), (sext y)) --> (sext (add int x, y))
2404 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2405 // Only do this if x/y have the same type, if at last one of them has a
2406 // single use (so we don't increase the number of sexts), and if the
2407 // integer add will not overflow.
2408 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2409 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2410 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2411 RHSConv->getOperand(0))) {
2412 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002413 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2414 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002415 return new SExtInst(NewAdd, I.getType());
2416 }
2417 }
2418 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002419
2420 return Changed ? &I : 0;
2421}
2422
2423Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2424 bool Changed = SimplifyCommutative(I);
2425 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2426
2427 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2428 // X + 0 --> X
2429 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002430 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002431 (I.getType())->getValueAPF()))
2432 return ReplaceInstUsesWith(I, LHS);
2433 }
2434
2435 if (isa<PHINode>(LHS))
2436 if (Instruction *NV = FoldOpIntoPhi(I))
2437 return NV;
2438 }
2439
2440 // -A + B --> B - A
2441 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002442 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002443 return BinaryOperator::CreateFSub(RHS, LHSV);
2444
2445 // A + -B --> A - B
2446 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002447 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002448 return BinaryOperator::CreateFSub(LHS, V);
2449
2450 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2451 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2452 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2453 return ReplaceInstUsesWith(I, LHS);
2454
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002455 // Check for (add double (sitofp x), y), see if we can merge this into an
2456 // integer add followed by a promotion.
2457 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2458 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2459 // ... if the constant fits in the integer value. This is useful for things
2460 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2461 // requires a constant pool load, and generally allows the add to be better
2462 // instcombined.
2463 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2464 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002465 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002466 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002467 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002468 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2469 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002470 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2471 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002472 return new SIToFPInst(NewAdd, I.getType());
2473 }
2474 }
2475
2476 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2477 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2478 // Only do this if x/y have the same type, if at last one of them has a
2479 // single use (so we don't increase the number of int->fp conversions),
2480 // and if the integer add will not overflow.
2481 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2482 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2483 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2484 RHSConv->getOperand(0))) {
2485 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002486 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2487 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002488 return new SIToFPInst(NewAdd, I.getType());
2489 }
2490 }
2491 }
2492
Chris Lattner7e708292002-06-25 16:13:24 +00002493 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002494}
2495
Chris Lattner7e708292002-06-25 16:13:24 +00002496Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002497 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002498
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002499 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002500 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002501
Chris Lattner233f7dc2002-08-12 21:17:25 +00002502 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002503 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002504 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002505
Chris Lattnere87597f2004-10-16 18:11:37 +00002506 if (isa<UndefValue>(Op0))
2507 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2508 if (isa<UndefValue>(Op1))
2509 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2510
Chris Lattnerd65460f2003-11-05 01:06:05 +00002511 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2512 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002513 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002514 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002515
Chris Lattnerd65460f2003-11-05 01:06:05 +00002516 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002517 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002518 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002519 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002520
Chris Lattner76b7a062007-01-15 07:02:54 +00002521 // -(X >>u 31) -> (X >>s 31)
2522 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002523 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002524 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002525 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002526 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002527 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002528 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002529 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002530 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002531 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002532 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002533 }
2534 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002535 }
2536 else if (SI->getOpcode() == Instruction::AShr) {
2537 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2538 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002539 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002540 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002541 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002542 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002543 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002544 }
2545 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002546 }
2547 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002548 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002549
2550 // Try to fold constant sub into select arguments.
2551 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002552 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002553 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002554
2555 // C - zext(bool) -> bool ? C - 1 : C
2556 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002557 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002558 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002559 }
2560
Owen Anderson1d0be152009-08-13 21:58:54 +00002561 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002562 return BinaryOperator::CreateXor(Op0, Op1);
2563
Chris Lattner43d84d62005-04-07 16:15:25 +00002564 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002565 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002566 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002567 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002568 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002569 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002570 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002571 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002572 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2573 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2574 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002575 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002576 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002577 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002578 }
2579
Chris Lattnerfd059242003-10-15 16:48:29 +00002580 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002581 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2582 // is not used by anyone else...
2583 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002584 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002585 // Swap the two operands of the subexpr...
2586 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2587 Op1I->setOperand(0, IIOp1);
2588 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002589
Chris Lattnera2881962003-02-18 19:28:33 +00002590 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002591 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002592 }
2593
2594 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2595 //
2596 if (Op1I->getOpcode() == Instruction::And &&
2597 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2598 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2599
Chris Lattner74381062009-08-30 07:44:24 +00002600 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002601 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002602 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002603
Reid Spencerac5209e2006-10-16 23:08:08 +00002604 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002605 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002606 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002607 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002608 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002609 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002610 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002611
Chris Lattnerad3448c2003-02-18 19:57:07 +00002612 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002613 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002614 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002615 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002616 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002617 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002618 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002619 }
Chris Lattner40371712002-05-09 01:29:19 +00002620 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002621 }
Chris Lattnera2881962003-02-18 19:28:33 +00002622
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002623 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2624 if (Op0I->getOpcode() == Instruction::Add) {
2625 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2626 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2627 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2628 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2629 } else if (Op0I->getOpcode() == Instruction::Sub) {
2630 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002631 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002632 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002633 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002634 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002635
Chris Lattner50af16a2004-11-13 19:50:12 +00002636 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002637 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002638 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002639 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002640
Chris Lattner50af16a2004-11-13 19:50:12 +00002641 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002642 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002643 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002644 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002645 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002646}
2647
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002648Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2649 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2650
2651 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002652 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002653 return BinaryOperator::CreateFAdd(Op0, V);
2654
2655 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2656 if (Op1I->getOpcode() == Instruction::FAdd) {
2657 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002658 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002659 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002660 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002661 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002662 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002663 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002664 }
2665
2666 return 0;
2667}
2668
Chris Lattnera0141b92007-07-15 20:42:37 +00002669/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2670/// comparison only checks the sign bit. If it only checks the sign bit, set
2671/// TrueIfSigned if the result of the comparison is true when the input value is
2672/// signed.
2673static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2674 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002675 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002676 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2677 TrueIfSigned = true;
2678 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002679 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2680 TrueIfSigned = true;
2681 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002682 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2683 TrueIfSigned = false;
2684 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002685 case ICmpInst::ICMP_UGT:
2686 // True if LHS u> RHS and RHS == high-bit-mask - 1
2687 TrueIfSigned = true;
2688 return RHS->getValue() ==
2689 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2690 case ICmpInst::ICMP_UGE:
2691 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2692 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002693 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002694 default:
2695 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002696 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002697}
2698
Chris Lattner7e708292002-06-25 16:13:24 +00002699Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002700 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002701 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002702
Chris Lattnera2498472009-10-11 21:36:10 +00002703 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002704 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002705
Chris Lattner8af304a2009-10-11 07:53:15 +00002706 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002707 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2708 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002709
2710 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002711 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002712 if (SI->getOpcode() == Instruction::Shl)
2713 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002714 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002715 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002716
Zhou Sheng843f07672007-04-19 05:39:12 +00002717 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002718 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002719 if (CI->equalsInt(1)) // X * 1 == X
2720 return ReplaceInstUsesWith(I, Op0);
2721 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002722 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002723
Zhou Sheng97b52c22007-03-29 01:57:21 +00002724 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002725 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002726 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002727 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002728 }
Chris Lattnera2498472009-10-11 21:36:10 +00002729 } else if (isa<VectorType>(Op1C->getType())) {
2730 if (Op1C->isNullValue())
2731 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002732
Chris Lattnera2498472009-10-11 21:36:10 +00002733 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002734 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002735 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002736
2737 // As above, vector X*splat(1.0) -> X in all defined cases.
2738 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002739 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2740 if (CI->equalsInt(1))
2741 return ReplaceInstUsesWith(I, Op0);
2742 }
2743 }
Chris Lattnera2881962003-02-18 19:28:33 +00002744 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002745
2746 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2747 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002748 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002749 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00002750 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2751 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002752 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002753
2754 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002755
2756 // Try to fold constant mul into select arguments.
2757 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002758 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002759 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002760
2761 if (isa<PHINode>(Op0))
2762 if (Instruction *NV = FoldOpIntoPhi(I))
2763 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002764 }
2765
Dan Gohman186a6362009-08-12 16:04:34 +00002766 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002767 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002768 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002769
Nick Lewycky0c730792008-11-21 07:33:58 +00002770 // (X / Y) * Y = X - (X % Y)
2771 // (X / Y) * -Y = (X % Y) - X
2772 {
Chris Lattnera2498472009-10-11 21:36:10 +00002773 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00002774 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2775 if (!BO ||
2776 (BO->getOpcode() != Instruction::UDiv &&
2777 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00002778 Op1C = Op0;
2779 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002780 }
Chris Lattnera2498472009-10-11 21:36:10 +00002781 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00002782 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002783 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00002784 (BO->getOpcode() == Instruction::UDiv ||
2785 BO->getOpcode() == Instruction::SDiv)) {
2786 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2787
Dan Gohmanfa94b942009-08-12 16:33:09 +00002788 // If the division is exact, X % Y is zero.
2789 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2790 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00002791 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00002792 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00002793 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00002794 }
2795
Chris Lattner74381062009-08-30 07:44:24 +00002796 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002797 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002798 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002799 else
Chris Lattner74381062009-08-30 07:44:24 +00002800 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002801 Rem->takeName(BO);
2802
Chris Lattnera2498472009-10-11 21:36:10 +00002803 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00002804 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002805 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002806 }
2807 }
2808
Chris Lattner8af304a2009-10-11 07:53:15 +00002809 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00002810 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00002811 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002812
Chris Lattner8af304a2009-10-11 07:53:15 +00002813 // X*(1 << Y) --> X << Y
2814 // (1 << Y)*X --> X << Y
2815 {
2816 Value *Y;
2817 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00002818 return BinaryOperator::CreateShl(Op1, Y);
2819 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00002820 return BinaryOperator::CreateShl(Op0, Y);
2821 }
2822
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002823 // If one of the operands of the multiply is a cast from a boolean value, then
2824 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00002825 // X * Y (where Y is 0 or 1) -> X & (0-Y)
2826 if (!isa<VectorType>(I.getType())) {
2827 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00002828 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00002829
Chris Lattnerd2c58362009-10-11 21:29:45 +00002830 Value *BoolCast = 0, *OtherOp = 0;
2831 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00002832 BoolCast = Op0, OtherOp = Op1;
2833 else if (MaskedValueIsZero(Op1, Negative2))
2834 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00002835
Chris Lattner0036e3a2009-10-11 21:22:21 +00002836 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00002837 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2838 BoolCast, "tmp");
2839 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002840 }
2841 }
2842
Chris Lattner7e708292002-06-25 16:13:24 +00002843 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002844}
2845
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002846Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2847 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002848 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002849
2850 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00002851 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2852 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002853 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2854 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2855 if (Op1F->isExactlyValue(1.0))
2856 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00002857 } else if (isa<VectorType>(Op1C->getType())) {
2858 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002859 // As above, vector X*splat(1.0) -> X in all defined cases.
2860 if (Constant *Splat = Op1V->getSplatValue()) {
2861 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2862 if (F->isExactlyValue(1.0))
2863 return ReplaceInstUsesWith(I, Op0);
2864 }
2865 }
2866 }
2867
2868 // Try to fold constant mul into select arguments.
2869 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2870 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2871 return R;
2872
2873 if (isa<PHINode>(Op0))
2874 if (Instruction *NV = FoldOpIntoPhi(I))
2875 return NV;
2876 }
2877
Dan Gohman186a6362009-08-12 16:04:34 +00002878 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002879 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002880 return BinaryOperator::CreateFMul(Op0v, Op1v);
2881
2882 return Changed ? &I : 0;
2883}
2884
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002885/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2886/// instruction.
2887bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2888 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2889
2890 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2891 int NonNullOperand = -1;
2892 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2893 if (ST->isNullValue())
2894 NonNullOperand = 2;
2895 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2896 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2897 if (ST->isNullValue())
2898 NonNullOperand = 1;
2899
2900 if (NonNullOperand == -1)
2901 return false;
2902
2903 Value *SelectCond = SI->getOperand(0);
2904
2905 // Change the div/rem to use 'Y' instead of the select.
2906 I.setOperand(1, SI->getOperand(NonNullOperand));
2907
2908 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2909 // problem. However, the select, or the condition of the select may have
2910 // multiple uses. Based on our knowledge that the operand must be non-zero,
2911 // propagate the known value for the select into other uses of it, and
2912 // propagate a known value of the condition into its other users.
2913
2914 // If the select and condition only have a single use, don't bother with this,
2915 // early exit.
2916 if (SI->use_empty() && SelectCond->hasOneUse())
2917 return true;
2918
2919 // Scan the current block backward, looking for other uses of SI.
2920 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2921
2922 while (BBI != BBFront) {
2923 --BBI;
2924 // If we found a call to a function, we can't assume it will return, so
2925 // information from below it cannot be propagated above it.
2926 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2927 break;
2928
2929 // Replace uses of the select or its condition with the known values.
2930 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2931 I != E; ++I) {
2932 if (*I == SI) {
2933 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002934 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002935 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002936 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2937 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002938 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002939 }
2940 }
2941
2942 // If we past the instruction, quit looking for it.
2943 if (&*BBI == SI)
2944 SI = 0;
2945 if (&*BBI == SelectCond)
2946 SelectCond = 0;
2947
2948 // If we ran out of things to eliminate, break out of the loop.
2949 if (SelectCond == 0 && SI == 0)
2950 break;
2951
2952 }
2953 return true;
2954}
2955
2956
Reid Spencer1628cec2006-10-26 06:15:43 +00002957/// This function implements the transforms on div instructions that work
2958/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2959/// used by the visitors to those instructions.
2960/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002961Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002962 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002963
Chris Lattner50b2ca42008-02-19 06:12:18 +00002964 // undef / X -> 0 for integer.
2965 // undef / X -> undef for FP (the undef could be a snan).
2966 if (isa<UndefValue>(Op0)) {
2967 if (Op0->getType()->isFPOrFPVector())
2968 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002969 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002970 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002971
2972 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002973 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002974 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002975
Reid Spencer1628cec2006-10-26 06:15:43 +00002976 return 0;
2977}
Misha Brukmanfd939082005-04-21 23:48:37 +00002978
Reid Spencer1628cec2006-10-26 06:15:43 +00002979/// This function implements the transforms common to both integer division
2980/// instructions (udiv and sdiv). It is called by the visitors to those integer
2981/// division instructions.
2982/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002983Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002984 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2985
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002986 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002987 if (Op0 == Op1) {
2988 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002989 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002990 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002991 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002992 }
2993
Owen Andersoneed707b2009-07-24 23:12:02 +00002994 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002995 return ReplaceInstUsesWith(I, CI);
2996 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002997
Reid Spencer1628cec2006-10-26 06:15:43 +00002998 if (Instruction *Common = commonDivTransforms(I))
2999 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003000
3001 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3002 // This does not apply for fdiv.
3003 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3004 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003005
3006 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3007 // div X, 1 == X
3008 if (RHS->equalsInt(1))
3009 return ReplaceInstUsesWith(I, Op0);
3010
3011 // (X / C1) / C2 -> X / (C1*C2)
3012 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3013 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3014 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003015 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003016 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003017 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003018 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003019 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003020 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003021 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003022
Reid Spencerbca0e382007-03-23 20:05:17 +00003023 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003024 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3025 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3026 return R;
3027 if (isa<PHINode>(Op0))
3028 if (Instruction *NV = FoldOpIntoPhi(I))
3029 return NV;
3030 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003031 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003032
Chris Lattnera2881962003-02-18 19:28:33 +00003033 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003034 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003035 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003036 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003037
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003038 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003039 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003040 return ReplaceInstUsesWith(I, Op0);
3041
Nick Lewycky895f0852008-11-27 20:21:08 +00003042 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3043 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3044 // div X, 1 == X
3045 if (X->isOne())
3046 return ReplaceInstUsesWith(I, Op0);
3047 }
3048
Reid Spencer1628cec2006-10-26 06:15:43 +00003049 return 0;
3050}
3051
3052Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3053 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3054
3055 // Handle the integer div common cases
3056 if (Instruction *Common = commonIDivTransforms(I))
3057 return Common;
3058
Reid Spencer1628cec2006-10-26 06:15:43 +00003059 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003060 // X udiv C^2 -> X >> C
3061 // Check to see if this is an unsigned division with an exact power of 2,
3062 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003063 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003064 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003065 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003066
3067 // X udiv C, where C >= signbit
3068 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003069 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003070 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003071 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003072 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003073 }
3074
3075 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003076 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003077 if (RHSI->getOpcode() == Instruction::Shl &&
3078 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003079 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003080 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003081 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003082 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003083 if (uint32_t C2 = C1.logBase2())
3084 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003085 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003086 }
3087 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003088 }
3089
Reid Spencer1628cec2006-10-26 06:15:43 +00003090 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3091 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003092 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003093 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003094 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003095 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003096 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003097 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003098 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003099 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003100 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003101 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003102
3103 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003104 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003105 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003106
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003107 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003108 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003109 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003110 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003111 return 0;
3112}
3113
Reid Spencer1628cec2006-10-26 06:15:43 +00003114Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3115 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3116
3117 // Handle the integer div common cases
3118 if (Instruction *Common = commonIDivTransforms(I))
3119 return Common;
3120
3121 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3122 // sdiv X, -1 == -X
3123 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003124 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003125
Dan Gohmanfa94b942009-08-12 16:33:09 +00003126 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003127 if (cast<SDivOperator>(&I)->isExact() &&
3128 RHS->getValue().isNonNegative() &&
3129 RHS->getValue().isPowerOf2()) {
3130 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3131 RHS->getValue().exactLogBase2());
3132 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3133 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003134
3135 // -X/C --> X/-C provided the negation doesn't overflow.
3136 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3137 if (isa<Constant>(Sub->getOperand(0)) &&
3138 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003139 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003140 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3141 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003142 }
3143
3144 // If the sign bits of both operands are zero (i.e. we can prove they are
3145 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003146 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003147 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003148 if (MaskedValueIsZero(Op0, Mask)) {
3149 if (MaskedValueIsZero(Op1, Mask)) {
3150 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3151 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3152 }
3153 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003154 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003155 ShiftedInt->getValue().isPowerOf2()) {
3156 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3157 // Safe because the only negative value (1 << Y) can take on is
3158 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3159 // the sign bit set.
3160 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3161 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003162 }
Eli Friedman8be17392009-07-18 09:53:21 +00003163 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003164
3165 return 0;
3166}
3167
3168Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3169 return commonDivTransforms(I);
3170}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003171
Reid Spencer0a783f72006-11-02 01:53:59 +00003172/// This function implements the transforms on rem instructions that work
3173/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3174/// is used by the visitors to those instructions.
3175/// @brief Transforms common to all three rem instructions
3176Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003177 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003178
Chris Lattner50b2ca42008-02-19 06:12:18 +00003179 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3180 if (I.getType()->isFPOrFPVector())
3181 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003182 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003183 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003184 if (isa<UndefValue>(Op1))
3185 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003186
3187 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003188 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3189 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003190
Reid Spencer0a783f72006-11-02 01:53:59 +00003191 return 0;
3192}
3193
3194/// This function implements the transforms common to both integer remainder
3195/// instructions (urem and srem). It is called by the visitors to those integer
3196/// remainder instructions.
3197/// @brief Common integer remainder transforms
3198Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3199 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3200
3201 if (Instruction *common = commonRemTransforms(I))
3202 return common;
3203
Dale Johannesened6af242009-01-21 00:35:19 +00003204 // 0 % X == 0 for integer, we don't need to preserve faults!
3205 if (Constant *LHS = dyn_cast<Constant>(Op0))
3206 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003207 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003208
Chris Lattner857e8cd2004-12-12 21:48:58 +00003209 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003210 // X % 0 == undef, we don't need to preserve faults!
3211 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003212 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003213
Chris Lattnera2881962003-02-18 19:28:33 +00003214 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003215 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003216
Chris Lattner97943922006-02-28 05:49:21 +00003217 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3218 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3219 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3220 return R;
3221 } else if (isa<PHINode>(Op0I)) {
3222 if (Instruction *NV = FoldOpIntoPhi(I))
3223 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003224 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003225
3226 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003227 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003228 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003229 }
Chris Lattnera2881962003-02-18 19:28:33 +00003230 }
3231
Reid Spencer0a783f72006-11-02 01:53:59 +00003232 return 0;
3233}
3234
3235Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3236 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3237
3238 if (Instruction *common = commonIRemTransforms(I))
3239 return common;
3240
3241 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3242 // X urem C^2 -> X and C
3243 // Check to see if this is an unsigned remainder with an exact power of 2,
3244 // if so, convert to a bitwise and.
3245 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003246 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003247 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003248 }
3249
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003250 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003251 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3252 if (RHSI->getOpcode() == Instruction::Shl &&
3253 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003254 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003255 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003256 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003257 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003258 }
3259 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003260 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003261
Reid Spencer0a783f72006-11-02 01:53:59 +00003262 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3263 // where C1&C2 are powers of two.
3264 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3265 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3266 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3267 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003268 if ((STO->getValue().isPowerOf2()) &&
3269 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003270 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3271 SI->getName()+".t");
3272 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3273 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003274 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003275 }
3276 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003277 }
3278
Chris Lattner3f5b8772002-05-06 16:14:14 +00003279 return 0;
3280}
3281
Reid Spencer0a783f72006-11-02 01:53:59 +00003282Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3283 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3284
Dan Gohmancff55092007-11-05 23:16:33 +00003285 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003286 if (Instruction *Common = commonIRemTransforms(I))
3287 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003288
Dan Gohman186a6362009-08-12 16:04:34 +00003289 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003290 if (!isa<Constant>(RHSNeg) ||
3291 (isa<ConstantInt>(RHSNeg) &&
3292 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003293 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003294 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003295 I.setOperand(1, RHSNeg);
3296 return &I;
3297 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003298
Dan Gohmancff55092007-11-05 23:16:33 +00003299 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003300 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003301 if (I.getType()->isInteger()) {
3302 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3303 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3304 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003305 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003306 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003307 }
3308
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003309 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003310 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3311 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003312
Nick Lewycky9dce8732008-12-20 16:48:00 +00003313 bool hasNegative = false;
3314 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3315 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3316 if (RHS->getValue().isNegative())
3317 hasNegative = true;
3318
3319 if (hasNegative) {
3320 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003321 for (unsigned i = 0; i != VWidth; ++i) {
3322 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3323 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003324 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003325 else
3326 Elts[i] = RHS;
3327 }
3328 }
3329
Owen Andersonaf7ec972009-07-28 21:19:26 +00003330 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003331 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003332 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003333 I.setOperand(1, NewRHSV);
3334 return &I;
3335 }
3336 }
3337 }
3338
Reid Spencer0a783f72006-11-02 01:53:59 +00003339 return 0;
3340}
3341
3342Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003343 return commonRemTransforms(I);
3344}
3345
Chris Lattner457dd822004-06-09 07:59:58 +00003346// isOneBitSet - Return true if there is exactly one bit set in the specified
3347// constant.
3348static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003349 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003350}
3351
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003352// isHighOnes - Return true if the constant is of the form 1+0+.
3353// This is the same as lowones(~X).
3354static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003355 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003356}
3357
Reid Spencere4d87aa2006-12-23 06:05:41 +00003358/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003359/// are carefully arranged to allow folding of expressions such as:
3360///
3361/// (A < B) | (A > B) --> (A != B)
3362///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003363/// Note that this is only valid if the first and second predicates have the
3364/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003365///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003366/// Three bits are used to represent the condition, as follows:
3367/// 0 A > B
3368/// 1 A == B
3369/// 2 A < B
3370///
3371/// <=> Value Definition
3372/// 000 0 Always false
3373/// 001 1 A > B
3374/// 010 2 A == B
3375/// 011 3 A >= B
3376/// 100 4 A < B
3377/// 101 5 A != B
3378/// 110 6 A <= B
3379/// 111 7 Always true
3380///
3381static unsigned getICmpCode(const ICmpInst *ICI) {
3382 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003383 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003384 case ICmpInst::ICMP_UGT: return 1; // 001
3385 case ICmpInst::ICMP_SGT: return 1; // 001
3386 case ICmpInst::ICMP_EQ: return 2; // 010
3387 case ICmpInst::ICMP_UGE: return 3; // 011
3388 case ICmpInst::ICMP_SGE: return 3; // 011
3389 case ICmpInst::ICMP_ULT: return 4; // 100
3390 case ICmpInst::ICMP_SLT: return 4; // 100
3391 case ICmpInst::ICMP_NE: return 5; // 101
3392 case ICmpInst::ICMP_ULE: return 6; // 110
3393 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003394 // True -> 7
3395 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003396 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003397 return 0;
3398 }
3399}
3400
Evan Cheng8db90722008-10-14 17:15:11 +00003401/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3402/// predicate into a three bit mask. It also returns whether it is an ordered
3403/// predicate by reference.
3404static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3405 isOrdered = false;
3406 switch (CC) {
3407 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3408 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003409 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3410 case FCmpInst::FCMP_UGT: return 1; // 001
3411 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3412 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003413 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3414 case FCmpInst::FCMP_UGE: return 3; // 011
3415 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3416 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003417 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3418 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003419 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3420 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003421 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003422 default:
3423 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003424 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003425 return 0;
3426 }
3427}
3428
Reid Spencere4d87aa2006-12-23 06:05:41 +00003429/// getICmpValue - This is the complement of getICmpCode, which turns an
3430/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003431/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003432/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003433static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003434 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003435 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003436 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003437 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003438 case 1:
3439 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003440 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003441 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003442 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3443 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003444 case 3:
3445 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003446 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003447 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003448 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003449 case 4:
3450 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003451 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003452 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003453 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3454 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003455 case 6:
3456 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003457 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003458 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003459 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003460 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003461 }
3462}
3463
Evan Cheng8db90722008-10-14 17:15:11 +00003464/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3465/// opcode and two operands into either a FCmp instruction. isordered is passed
3466/// in to determine which kind of predicate to use in the new fcmp instruction.
3467static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003468 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003469 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003470 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003471 case 0:
3472 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003473 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003474 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003475 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003476 case 1:
3477 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003478 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003479 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003480 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003481 case 2:
3482 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003483 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003484 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003485 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003486 case 3:
3487 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003488 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003489 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003490 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003491 case 4:
3492 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003493 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003494 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003495 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003496 case 5:
3497 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003498 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003499 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003500 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003501 case 6:
3502 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003503 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003504 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003505 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003506 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003507 }
3508}
3509
Chris Lattnerb9553d62008-11-16 04:55:20 +00003510/// PredicatesFoldable - Return true if both predicates match sign or if at
3511/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003512static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3513 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003514 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3515 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003516}
3517
3518namespace {
3519// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3520struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003521 InstCombiner &IC;
3522 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003523 ICmpInst::Predicate pred;
3524 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3525 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3526 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003527 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003528 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3529 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003530 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3531 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003532 return false;
3533 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003534 Instruction *apply(Instruction &Log) const {
3535 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3536 if (ICI->getOperand(0) != LHS) {
3537 assert(ICI->getOperand(1) == LHS);
3538 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003539 }
3540
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003541 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003542 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003543 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003544 unsigned Code;
3545 switch (Log.getOpcode()) {
3546 case Instruction::And: Code = LHSCode & RHSCode; break;
3547 case Instruction::Or: Code = LHSCode | RHSCode; break;
3548 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003549 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003550 }
3551
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003552 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3553 ICmpInst::isSignedPredicate(ICI->getPredicate());
3554
Owen Andersond672ecb2009-07-03 00:17:18 +00003555 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003556 if (Instruction *I = dyn_cast<Instruction>(RV))
3557 return I;
3558 // Otherwise, it's a constant boolean value...
3559 return IC.ReplaceInstUsesWith(Log, RV);
3560 }
3561};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003562} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003563
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003564// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3565// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003566// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003567Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003568 ConstantInt *OpRHS,
3569 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003570 BinaryOperator &TheAnd) {
3571 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003572 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003573 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003574 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003575
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003576 switch (Op->getOpcode()) {
3577 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003578 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003579 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003580 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003581 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003582 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003583 }
3584 break;
3585 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003586 if (Together == AndRHS) // (X | C) & C --> C
3587 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003588
Chris Lattner6e7ba452005-01-01 16:22:27 +00003589 if (Op->hasOneUse() && Together != OpRHS) {
3590 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003591 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003592 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003593 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003594 }
3595 break;
3596 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003597 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003598 // Adding a one to a single bit bit-field should be turned into an XOR
3599 // of the bit. First thing to check is to see if this AND is with a
3600 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003601 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003602
3603 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003604 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003605 // Ok, at this point, we know that we are masking the result of the
3606 // ADD down to exactly one bit. If the constant we are adding has
3607 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003608 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003609
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003610 // Check to see if any bits below the one bit set in AndRHSV are set.
3611 if ((AddRHS & (AndRHSV-1)) == 0) {
3612 // If not, the only thing that can effect the output of the AND is
3613 // the bit specified by AndRHSV. If that bit is set, the effect of
3614 // the XOR is to toggle the bit. If it is clear, then the ADD has
3615 // no effect.
3616 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3617 TheAnd.setOperand(0, X);
3618 return &TheAnd;
3619 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003620 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003621 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003622 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003623 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003624 }
3625 }
3626 }
3627 }
3628 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003629
3630 case Instruction::Shl: {
3631 // We know that the AND will not produce any of the bits shifted in, so if
3632 // the anded constant includes them, clear them now!
3633 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003634 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003635 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003636 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003637 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003638
Zhou Sheng290bec52007-03-29 08:15:12 +00003639 if (CI->getValue() == ShlMask) {
3640 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003641 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3642 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003643 TheAnd.setOperand(1, CI);
3644 return &TheAnd;
3645 }
3646 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003647 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003648 case Instruction::LShr:
3649 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003650 // We know that the AND will not produce any of the bits shifted in, so if
3651 // the anded constant includes them, clear them now! This only applies to
3652 // unsigned shifts, because a signed shr may bring in set bits!
3653 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003654 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003655 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003656 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003657 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003658
Zhou Sheng290bec52007-03-29 08:15:12 +00003659 if (CI->getValue() == ShrMask) {
3660 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003661 return ReplaceInstUsesWith(TheAnd, Op);
3662 } else if (CI != AndRHS) {
3663 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3664 return &TheAnd;
3665 }
3666 break;
3667 }
3668 case Instruction::AShr:
3669 // Signed shr.
3670 // See if this is shifting in some sign extension, then masking it out
3671 // with an and.
3672 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003673 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003674 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003675 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003676 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003677 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003678 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003679 // Make the argument unsigned.
3680 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003681 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003682 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003683 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003684 }
3685 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003686 }
3687 return 0;
3688}
3689
Chris Lattner8b170942002-08-09 23:47:40 +00003690
Chris Lattnera96879a2004-09-29 17:40:11 +00003691/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3692/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003693/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3694/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003695/// insert new instructions.
3696Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003697 bool isSigned, bool Inside,
3698 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003699 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003700 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003701 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003702
Chris Lattnera96879a2004-09-29 17:40:11 +00003703 if (Inside) {
3704 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003705 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003706
Reid Spencere4d87aa2006-12-23 06:05:41 +00003707 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003708 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003709 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003710 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003711 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003712 }
3713
3714 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003715 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003716 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003717 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003718 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003719 }
3720
3721 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003722 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003723
Reid Spencere4e40032007-03-21 23:19:50 +00003724 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003725 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003726 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003727 ICmpInst::Predicate pred = (isSigned ?
3728 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003729 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003730 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003731
Reid Spencere4e40032007-03-21 23:19:50 +00003732 // Emit V-Lo >u Hi-1-Lo
3733 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003734 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003735 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003736 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003737 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003738}
3739
Chris Lattner7203e152005-09-18 07:22:02 +00003740// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3741// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3742// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3743// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003744static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003745 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003746 uint32_t BitWidth = Val->getType()->getBitWidth();
3747 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003748
3749 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003750 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003751 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003752 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003753 return true;
3754}
3755
Chris Lattner7203e152005-09-18 07:22:02 +00003756/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3757/// where isSub determines whether the operator is a sub. If we can fold one of
3758/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003759///
3760/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3761/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3762/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3763///
3764/// return (A +/- B).
3765///
3766Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003767 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003768 Instruction &I) {
3769 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3770 if (!LHSI || LHSI->getNumOperands() != 2 ||
3771 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3772
3773 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3774
3775 switch (LHSI->getOpcode()) {
3776 default: return 0;
3777 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003778 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003779 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003780 if ((Mask->getValue().countLeadingZeros() +
3781 Mask->getValue().countPopulation()) ==
3782 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003783 break;
3784
3785 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3786 // part, we don't need any explicit masks to take them out of A. If that
3787 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003788 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003789 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003790 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003791 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003792 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003793 break;
3794 }
3795 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003796 return 0;
3797 case Instruction::Or:
3798 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003799 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003800 if ((Mask->getValue().countLeadingZeros() +
3801 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003802 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003803 break;
3804 return 0;
3805 }
3806
Chris Lattnerc8e77562005-09-18 04:24:45 +00003807 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003808 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3809 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003810}
3811
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003812/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3813Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3814 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003815 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003816 ConstantInt *LHSCst, *RHSCst;
3817 ICmpInst::Predicate LHSCC, RHSCC;
3818
Chris Lattnerea065fb2008-11-16 05:10:52 +00003819 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003820 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003821 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003822 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003823 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003824 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003825
3826 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3827 // where C is a power of 2
3828 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3829 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003830 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003831 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003832 }
3833
3834 // From here on, we only handle:
3835 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3836 if (Val != Val2) return 0;
3837
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003838 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3839 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3840 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3841 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3842 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3843 return 0;
3844
3845 // We can't fold (ugt x, C) & (sgt x, C2).
3846 if (!PredicatesFoldable(LHSCC, RHSCC))
3847 return 0;
3848
3849 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003850 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003851 if (ICmpInst::isSignedPredicate(LHSCC) ||
3852 (ICmpInst::isEquality(LHSCC) &&
3853 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003854 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003855 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003856 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3857
3858 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003859 std::swap(LHS, RHS);
3860 std::swap(LHSCst, RHSCst);
3861 std::swap(LHSCC, RHSCC);
3862 }
3863
3864 // At this point, we know we have have two icmp instructions
3865 // comparing a value against two constants and and'ing the result
3866 // together. Because of the above check, we know that we only have
3867 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3868 // (from the FoldICmpLogical check above), that the two constants
3869 // are not equal and that the larger constant is on the RHS
3870 assert(LHSCst != RHSCst && "Compares not folded above?");
3871
3872 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003873 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003874 case ICmpInst::ICMP_EQ:
3875 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003876 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003877 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3878 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3879 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003880 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003881 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3882 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3883 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3884 return ReplaceInstUsesWith(I, LHS);
3885 }
3886 case ICmpInst::ICMP_NE:
3887 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003888 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003889 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003890 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003891 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003892 break; // (X != 13 & X u< 15) -> no change
3893 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003894 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003895 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003896 break; // (X != 13 & X s< 15) -> no change
3897 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3898 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3899 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3900 return ReplaceInstUsesWith(I, RHS);
3901 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003902 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003903 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003904 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003905 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003906 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003907 }
3908 break; // (X != 13 & X != 15) -> no change
3909 }
3910 break;
3911 case ICmpInst::ICMP_ULT:
3912 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003913 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003914 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3915 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003916 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003917 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3918 break;
3919 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3920 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3921 return ReplaceInstUsesWith(I, LHS);
3922 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3923 break;
3924 }
3925 break;
3926 case ICmpInst::ICMP_SLT:
3927 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003928 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003929 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3930 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003931 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003932 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3933 break;
3934 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3935 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3936 return ReplaceInstUsesWith(I, LHS);
3937 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3938 break;
3939 }
3940 break;
3941 case ICmpInst::ICMP_UGT:
3942 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003943 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003944 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3945 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3946 return ReplaceInstUsesWith(I, RHS);
3947 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3948 break;
3949 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003950 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003951 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003952 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003953 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003954 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003955 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003956 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3957 break;
3958 }
3959 break;
3960 case ICmpInst::ICMP_SGT:
3961 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003962 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003963 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3964 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3965 return ReplaceInstUsesWith(I, RHS);
3966 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3967 break;
3968 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003969 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003970 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003971 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003972 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003973 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003974 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003975 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3976 break;
3977 }
3978 break;
3979 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003980
3981 return 0;
3982}
3983
Chris Lattner42d1be02009-07-23 05:14:02 +00003984Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3985 FCmpInst *RHS) {
3986
3987 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3988 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3989 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3990 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3991 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3992 // If either of the constants are nans, then the whole thing returns
3993 // false.
3994 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003995 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003996 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003997 LHS->getOperand(0), RHS->getOperand(0));
3998 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003999
4000 // Handle vector zeros. This occurs because the canonical form of
4001 // "fcmp ord x,x" is "fcmp ord x, 0".
4002 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4003 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004004 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004005 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004006 return 0;
4007 }
4008
4009 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4010 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4011 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4012
4013
4014 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4015 // Swap RHS operands to match LHS.
4016 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4017 std::swap(Op1LHS, Op1RHS);
4018 }
4019
4020 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4021 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4022 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004023 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004024
4025 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004026 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004027 if (Op0CC == FCmpInst::FCMP_TRUE)
4028 return ReplaceInstUsesWith(I, RHS);
4029 if (Op1CC == FCmpInst::FCMP_TRUE)
4030 return ReplaceInstUsesWith(I, LHS);
4031
4032 bool Op0Ordered;
4033 bool Op1Ordered;
4034 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4035 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4036 if (Op1Pred == 0) {
4037 std::swap(LHS, RHS);
4038 std::swap(Op0Pred, Op1Pred);
4039 std::swap(Op0Ordered, Op1Ordered);
4040 }
4041 if (Op0Pred == 0) {
4042 // uno && ueq -> uno && (uno || eq) -> ueq
4043 // ord && olt -> ord && (ord && lt) -> olt
4044 if (Op0Ordered == Op1Ordered)
4045 return ReplaceInstUsesWith(I, RHS);
4046
4047 // uno && oeq -> uno && (ord && eq) -> false
4048 // uno && ord -> false
4049 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004050 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004051 // ord && ueq -> ord && (uno || eq) -> oeq
4052 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4053 Op0LHS, Op0RHS, Context));
4054 }
4055 }
4056
4057 return 0;
4058}
4059
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004060
Chris Lattner7e708292002-06-25 16:13:24 +00004061Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004062 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004063 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004064
Chris Lattnere87597f2004-10-16 18:11:37 +00004065 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004066 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004067
Chris Lattner6e7ba452005-01-01 16:22:27 +00004068 // and X, X = X
4069 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004070 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004071
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004072 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004073 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004074 if (SimplifyDemandedInstructionBits(I))
4075 return &I;
4076 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004077 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004078 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004079 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004080 } else if (isa<ConstantAggregateZero>(Op1)) {
4081 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004082 }
4083 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004084
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004085 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004086 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004087 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004088
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004089 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004090 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004091 Value *Op0LHS = Op0I->getOperand(0);
4092 Value *Op0RHS = Op0I->getOperand(1);
4093 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004094 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004095 case Instruction::Xor:
4096 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004097 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004098 if (!Op0I->hasOneUse()) break;
4099
4100 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4101 // Not masking anything out for the LHS, move to RHS.
4102 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4103 Op0RHS->getName()+".masked");
4104 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4105 }
4106 if (!isa<Constant>(Op0RHS) &&
4107 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4108 // Not masking anything out for the RHS, move to LHS.
4109 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4110 Op0LHS->getName()+".masked");
4111 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004112 }
4113
Chris Lattner6e7ba452005-01-01 16:22:27 +00004114 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004115 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004116 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4117 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4118 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4119 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004120 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004121 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004122 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004123 break;
4124
4125 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004126 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4127 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4128 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4129 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004130 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004131
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004132 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4133 // has 1's for all bits that the subtraction with A might affect.
4134 if (Op0I->hasOneUse()) {
4135 uint32_t BitWidth = AndRHSMask.getBitWidth();
4136 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4137 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4138
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004139 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004140 if (!(A && A->isZero()) && // avoid infinite recursion.
4141 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004142 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004143 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4144 }
4145 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004146 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004147
4148 case Instruction::Shl:
4149 case Instruction::LShr:
4150 // (1 << x) & 1 --> zext(x == 0)
4151 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004152 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004153 Value *NewICmp =
4154 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004155 return new ZExtInst(NewICmp, I.getType());
4156 }
4157 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004158 }
4159
Chris Lattner58403262003-07-23 19:25:52 +00004160 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004161 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004162 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004163 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004164 // If this is an integer truncation or change from signed-to-unsigned, and
4165 // if the source is an and/or with immediate, transform it. This
4166 // frequently occurs for bitfield accesses.
4167 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004168 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004169 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004170 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004171 if (CastOp->getOpcode() == Instruction::And) {
4172 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004173 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4174 // This will fold the two constants together, which may allow
4175 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004176 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004177 CastOp->getOperand(0), I.getType(),
4178 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004179 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004180 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004181 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004182 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004183 } else if (CastOp->getOpcode() == Instruction::Or) {
4184 // Change: and (cast (or X, C1) to T), C2
4185 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004186 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004187 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004188 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004189 return ReplaceInstUsesWith(I, AndRHS);
4190 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004191 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004192 }
Chris Lattner06782f82003-07-23 19:36:21 +00004193 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004194
4195 // Try to fold constant and into select arguments.
4196 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004197 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004198 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004199 if (isa<PHINode>(Op0))
4200 if (Instruction *NV = FoldOpIntoPhi(I))
4201 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004202 }
4203
Dan Gohman186a6362009-08-12 16:04:34 +00004204 Value *Op0NotVal = dyn_castNotVal(Op0);
4205 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004206
Chris Lattner5b62aa72004-06-18 06:07:51 +00004207 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004208 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004209
Misha Brukmancb6267b2004-07-30 12:50:08 +00004210 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004211 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004212 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4213 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004214 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004215 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004216
4217 {
Chris Lattner003b6202007-06-15 05:58:24 +00004218 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004219 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004220 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4221 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004222
4223 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004224 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004225 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004226 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004227 }
4228 }
4229
Dan Gohman4ae51262009-08-12 16:23:25 +00004230 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004231 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4232 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004233
4234 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004235 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004236 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004237 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004238 }
4239 }
Chris Lattner64daab52006-04-01 08:03:55 +00004240
4241 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004242 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004243 if (A == Op1) { // (A^B)&A -> A&(A^B)
4244 I.swapOperands(); // Simplify below
4245 std::swap(Op0, Op1);
4246 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4247 cast<BinaryOperator>(Op0)->swapOperands();
4248 I.swapOperands(); // Simplify below
4249 std::swap(Op0, Op1);
4250 }
4251 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004252
Chris Lattner64daab52006-04-01 08:03:55 +00004253 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004254 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004255 if (B == Op0) { // B&(A^B) -> B&(B^A)
4256 cast<BinaryOperator>(Op1)->swapOperands();
4257 std::swap(A, B);
4258 }
Chris Lattner74381062009-08-30 07:44:24 +00004259 if (A == Op0) // A&(A^B) -> A & ~B
4260 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004261 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004262
4263 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004264 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4265 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004266 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004267 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4268 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004269 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004270 }
4271
Reid Spencere4d87aa2006-12-23 06:05:41 +00004272 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4273 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004274 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004275 return R;
4276
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004277 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4278 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4279 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004280 }
4281
Chris Lattner6fc205f2006-05-05 06:39:07 +00004282 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004283 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4284 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4285 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4286 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004287 if (SrcTy == Op1C->getOperand(0)->getType() &&
4288 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004289 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004290 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4291 I.getType(), TD) &&
4292 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4293 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004294 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4295 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004296 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004297 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004298 }
Chris Lattnere511b742006-11-14 07:46:50 +00004299
4300 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004301 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4302 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4303 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004304 SI0->getOperand(1) == SI1->getOperand(1) &&
4305 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004306 Value *NewOp =
4307 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4308 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004309 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004310 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004311 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004312 }
4313
Evan Cheng8db90722008-10-14 17:15:11 +00004314 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004315 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004316 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4317 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4318 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004319 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004320
Chris Lattner7e708292002-06-25 16:13:24 +00004321 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004322}
4323
Chris Lattner8c34cd22008-10-05 02:13:19 +00004324/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4325/// capable of providing pieces of a bswap. The subexpression provides pieces
4326/// of a bswap if it is proven that each of the non-zero bytes in the output of
4327/// the expression came from the corresponding "byte swapped" byte in some other
4328/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4329/// we know that the expression deposits the low byte of %X into the high byte
4330/// of the bswap result and that all other bytes are zero. This expression is
4331/// accepted, the high byte of ByteValues is set to X to indicate a correct
4332/// match.
4333///
4334/// This function returns true if the match was unsuccessful and false if so.
4335/// On entry to the function the "OverallLeftShift" is a signed integer value
4336/// indicating the number of bytes that the subexpression is later shifted. For
4337/// example, if the expression is later right shifted by 16 bits, the
4338/// OverallLeftShift value would be -2 on entry. This is used to specify which
4339/// byte of ByteValues is actually being set.
4340///
4341/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4342/// byte is masked to zero by a user. For example, in (X & 255), X will be
4343/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4344/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4345/// always in the local (OverallLeftShift) coordinate space.
4346///
4347static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4348 SmallVector<Value*, 8> &ByteValues) {
4349 if (Instruction *I = dyn_cast<Instruction>(V)) {
4350 // If this is an or instruction, it may be an inner node of the bswap.
4351 if (I->getOpcode() == Instruction::Or) {
4352 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4353 ByteValues) ||
4354 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4355 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004356 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004357
4358 // If this is a logical shift by a constant multiple of 8, recurse with
4359 // OverallLeftShift and ByteMask adjusted.
4360 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4361 unsigned ShAmt =
4362 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4363 // Ensure the shift amount is defined and of a byte value.
4364 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4365 return true;
4366
4367 unsigned ByteShift = ShAmt >> 3;
4368 if (I->getOpcode() == Instruction::Shl) {
4369 // X << 2 -> collect(X, +2)
4370 OverallLeftShift += ByteShift;
4371 ByteMask >>= ByteShift;
4372 } else {
4373 // X >>u 2 -> collect(X, -2)
4374 OverallLeftShift -= ByteShift;
4375 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004376 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004377 }
4378
4379 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4380 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4381
4382 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4383 ByteValues);
4384 }
4385
4386 // If this is a logical 'and' with a mask that clears bytes, clear the
4387 // corresponding bytes in ByteMask.
4388 if (I->getOpcode() == Instruction::And &&
4389 isa<ConstantInt>(I->getOperand(1))) {
4390 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4391 unsigned NumBytes = ByteValues.size();
4392 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4393 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4394
4395 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4396 // If this byte is masked out by a later operation, we don't care what
4397 // the and mask is.
4398 if ((ByteMask & (1 << i)) == 0)
4399 continue;
4400
4401 // If the AndMask is all zeros for this byte, clear the bit.
4402 APInt MaskB = AndMask & Byte;
4403 if (MaskB == 0) {
4404 ByteMask &= ~(1U << i);
4405 continue;
4406 }
4407
4408 // If the AndMask is not all ones for this byte, it's not a bytezap.
4409 if (MaskB != Byte)
4410 return true;
4411
4412 // Otherwise, this byte is kept.
4413 }
4414
4415 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4416 ByteValues);
4417 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004418 }
4419
Chris Lattner8c34cd22008-10-05 02:13:19 +00004420 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4421 // the input value to the bswap. Some observations: 1) if more than one byte
4422 // is demanded from this input, then it could not be successfully assembled
4423 // into a byteswap. At least one of the two bytes would not be aligned with
4424 // their ultimate destination.
4425 if (!isPowerOf2_32(ByteMask)) return true;
4426 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004427
Chris Lattner8c34cd22008-10-05 02:13:19 +00004428 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4429 // is demanded, it needs to go into byte 0 of the result. This means that the
4430 // byte needs to be shifted until it lands in the right byte bucket. The
4431 // shift amount depends on the position: if the byte is coming from the high
4432 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4433 // low part, it must be shifted left.
4434 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4435 if (InputByteNo < ByteValues.size()/2) {
4436 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4437 return true;
4438 } else {
4439 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4440 return true;
4441 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004442
4443 // If the destination byte value is already defined, the values are or'd
4444 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004445 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004446 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004447 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004448 return false;
4449}
4450
4451/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4452/// If so, insert the new bswap intrinsic and return it.
4453Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004454 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004455 if (!ITy || ITy->getBitWidth() % 16 ||
4456 // ByteMask only allows up to 32-byte values.
4457 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004458 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004459
4460 /// ByteValues - For each byte of the result, we keep track of which value
4461 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004462 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004463 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004464
4465 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004466 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4467 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004468 return 0;
4469
4470 // Check to see if all of the bytes come from the same value.
4471 Value *V = ByteValues[0];
4472 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4473
4474 // Check to make sure that all of the bytes come from the same value.
4475 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4476 if (ByteValues[i] != V)
4477 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004478 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004479 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004480 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004481 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004482}
4483
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004484/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4485/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4486/// we can simplify this expression to "cond ? C : D or B".
4487static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004488 Value *C, Value *D,
4489 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004490 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004491 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004492 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004493 return 0;
4494
Chris Lattnera6a474d2008-11-16 04:26:55 +00004495 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004496 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004497 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004498 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004499 return SelectInst::Create(Cond, C, B);
4500 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004501 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004502 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004503 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004504 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004505 return 0;
4506}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004507
Chris Lattner69d4ced2008-11-16 05:20:07 +00004508/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4509Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4510 ICmpInst *LHS, ICmpInst *RHS) {
4511 Value *Val, *Val2;
4512 ConstantInt *LHSCst, *RHSCst;
4513 ICmpInst::Predicate LHSCC, RHSCC;
4514
4515 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004516 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004517 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004518 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004519 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004520 return 0;
4521
4522 // From here on, we only handle:
4523 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4524 if (Val != Val2) return 0;
4525
4526 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4527 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4528 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4529 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4530 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4531 return 0;
4532
4533 // We can't fold (ugt x, C) | (sgt x, C2).
4534 if (!PredicatesFoldable(LHSCC, RHSCC))
4535 return 0;
4536
4537 // Ensure that the larger constant is on the RHS.
4538 bool ShouldSwap;
4539 if (ICmpInst::isSignedPredicate(LHSCC) ||
4540 (ICmpInst::isEquality(LHSCC) &&
4541 ICmpInst::isSignedPredicate(RHSCC)))
4542 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4543 else
4544 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4545
4546 if (ShouldSwap) {
4547 std::swap(LHS, RHS);
4548 std::swap(LHSCst, RHSCst);
4549 std::swap(LHSCC, RHSCC);
4550 }
4551
4552 // At this point, we know we have have two icmp instructions
4553 // comparing a value against two constants and or'ing the result
4554 // together. Because of the above check, we know that we only have
4555 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4556 // FoldICmpLogical check above), that the two constants are not
4557 // equal.
4558 assert(LHSCst != RHSCst && "Compares not folded above?");
4559
4560 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004561 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004562 case ICmpInst::ICMP_EQ:
4563 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004564 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004565 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004566 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004567 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004568 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004569 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004570 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004571 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004572 }
4573 break; // (X == 13 | X == 15) -> no change
4574 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4575 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4576 break;
4577 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4578 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4579 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4580 return ReplaceInstUsesWith(I, RHS);
4581 }
4582 break;
4583 case ICmpInst::ICMP_NE:
4584 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004585 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004586 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4587 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4588 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4589 return ReplaceInstUsesWith(I, LHS);
4590 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4591 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4592 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004593 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004594 }
4595 break;
4596 case ICmpInst::ICMP_ULT:
4597 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004598 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004599 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4600 break;
4601 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4602 // If RHSCst is [us]MAXINT, it is always false. Not handling
4603 // this can cause overflow.
4604 if (RHSCst->isMaxValue(false))
4605 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004606 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004607 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004608 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4609 break;
4610 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4611 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4612 return ReplaceInstUsesWith(I, RHS);
4613 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4614 break;
4615 }
4616 break;
4617 case ICmpInst::ICMP_SLT:
4618 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004619 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004620 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4621 break;
4622 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4623 // If RHSCst is [us]MAXINT, it is always false. Not handling
4624 // this can cause overflow.
4625 if (RHSCst->isMaxValue(true))
4626 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004627 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004628 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004629 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4630 break;
4631 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4632 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4633 return ReplaceInstUsesWith(I, RHS);
4634 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4635 break;
4636 }
4637 break;
4638 case ICmpInst::ICMP_UGT:
4639 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004640 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004641 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4642 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4643 return ReplaceInstUsesWith(I, LHS);
4644 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4645 break;
4646 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4647 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004648 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004649 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4650 break;
4651 }
4652 break;
4653 case ICmpInst::ICMP_SGT:
4654 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004655 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004656 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4657 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4658 return ReplaceInstUsesWith(I, LHS);
4659 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4660 break;
4661 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4662 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004663 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004664 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4665 break;
4666 }
4667 break;
4668 }
4669 return 0;
4670}
4671
Chris Lattner5414cc52009-07-23 05:46:22 +00004672Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4673 FCmpInst *RHS) {
4674 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4675 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4676 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4677 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4678 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4679 // If either of the constants are nans, then the whole thing returns
4680 // true.
4681 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004682 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004683
4684 // Otherwise, no need to compare the two constants, compare the
4685 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004686 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004687 LHS->getOperand(0), RHS->getOperand(0));
4688 }
4689
4690 // Handle vector zeros. This occurs because the canonical form of
4691 // "fcmp uno x,x" is "fcmp uno x, 0".
4692 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4693 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004694 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004695 LHS->getOperand(0), RHS->getOperand(0));
4696
4697 return 0;
4698 }
4699
4700 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4701 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4702 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4703
4704 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4705 // Swap RHS operands to match LHS.
4706 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4707 std::swap(Op1LHS, Op1RHS);
4708 }
4709 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4710 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4711 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004712 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004713 Op0LHS, Op0RHS);
4714 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004715 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004716 if (Op0CC == FCmpInst::FCMP_FALSE)
4717 return ReplaceInstUsesWith(I, RHS);
4718 if (Op1CC == FCmpInst::FCMP_FALSE)
4719 return ReplaceInstUsesWith(I, LHS);
4720 bool Op0Ordered;
4721 bool Op1Ordered;
4722 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4723 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4724 if (Op0Ordered == Op1Ordered) {
4725 // If both are ordered or unordered, return a new fcmp with
4726 // or'ed predicates.
4727 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4728 Op0LHS, Op0RHS, Context);
4729 if (Instruction *I = dyn_cast<Instruction>(RV))
4730 return I;
4731 // Otherwise, it's a constant boolean value...
4732 return ReplaceInstUsesWith(I, RV);
4733 }
4734 }
4735 return 0;
4736}
4737
Bill Wendlinga698a472008-12-01 08:23:25 +00004738/// FoldOrWithConstants - This helper function folds:
4739///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004740/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004741///
4742/// into:
4743///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004744/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004745///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004746/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004747Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004748 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004749 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4750 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004751
Bill Wendling286a0542008-12-02 06:24:20 +00004752 Value *V1 = 0;
4753 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004754 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004755
Bill Wendling29976b92008-12-02 06:18:11 +00004756 APInt Xor = CI1->getValue() ^ CI2->getValue();
4757 if (!Xor.isAllOnesValue()) return 0;
4758
Bill Wendling286a0542008-12-02 06:24:20 +00004759 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004760 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004761 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004762 }
4763
4764 return 0;
4765}
4766
Chris Lattner7e708292002-06-25 16:13:24 +00004767Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004768 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004769 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004770
Chris Lattner42593e62007-03-24 23:56:43 +00004771 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004772 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004773
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004774 // or X, X = X
4775 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004776 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004777
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004778 // See if we can simplify any instructions used by the instruction whose sole
4779 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004780 if (SimplifyDemandedInstructionBits(I))
4781 return &I;
4782 if (isa<VectorType>(I.getType())) {
4783 if (isa<ConstantAggregateZero>(Op1)) {
4784 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4785 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4786 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4787 return ReplaceInstUsesWith(I, I.getOperand(1));
4788 }
Chris Lattner42593e62007-03-24 23:56:43 +00004789 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004790
Chris Lattner3f5b8772002-05-06 16:14:14 +00004791 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004792 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004793 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004794 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004795 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004796 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004797 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004798 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004799 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004800 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004801 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004802
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004803 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004804 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004805 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004806 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004807 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004808 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004809 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004810 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004811
4812 // Try to fold constant and into select arguments.
4813 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004814 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004815 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004816 if (isa<PHINode>(Op0))
4817 if (Instruction *NV = FoldOpIntoPhi(I))
4818 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004819 }
4820
Chris Lattner4f637d42006-01-06 17:59:59 +00004821 Value *A = 0, *B = 0;
4822 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004823
Dan Gohman4ae51262009-08-12 16:23:25 +00004824 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004825 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4826 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004827 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004828 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4829 return ReplaceInstUsesWith(I, Op0);
4830
Chris Lattner6423d4c2006-07-10 20:25:24 +00004831 // (A | B) | C and A | (B | C) -> bswap if possible.
4832 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004833 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4834 match(Op1, m_Or(m_Value(), m_Value())) ||
4835 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4836 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004837 if (Instruction *BSwap = MatchBSwap(I))
4838 return BSwap;
4839 }
4840
Chris Lattner6e4c6492005-05-09 04:58:36 +00004841 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004842 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004843 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004844 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004845 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004846 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004847 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004848 }
4849
4850 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004851 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004852 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004853 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004854 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004855 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004856 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004857 }
4858
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004859 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004860 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004861 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4862 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004863 Value *V1 = 0, *V2 = 0, *V3 = 0;
4864 C1 = dyn_cast<ConstantInt>(C);
4865 C2 = dyn_cast<ConstantInt>(D);
4866 if (C1 && C2) { // (A & C1)|(B & C2)
4867 // If we have: ((V + N) & C1) | (V & C2)
4868 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4869 // replace with V+N.
4870 if (C1->getValue() == ~C2->getValue()) {
4871 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004872 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004873 // Add commutes, try both ways.
4874 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4875 return ReplaceInstUsesWith(I, A);
4876 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4877 return ReplaceInstUsesWith(I, A);
4878 }
4879 // Or commutes, try both ways.
4880 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004881 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004882 // Add commutes, try both ways.
4883 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4884 return ReplaceInstUsesWith(I, B);
4885 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4886 return ReplaceInstUsesWith(I, B);
4887 }
4888 }
Chris Lattner044e5332007-04-08 08:01:49 +00004889 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004890 }
4891
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004892 // Check to see if we have any common things being and'ed. If so, find the
4893 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004894 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4895 if (A == B) // (A & C)|(A & D) == A & (C|D)
4896 V1 = A, V2 = C, V3 = D;
4897 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4898 V1 = A, V2 = B, V3 = C;
4899 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4900 V1 = C, V2 = A, V3 = D;
4901 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4902 V1 = C, V2 = A, V3 = B;
4903
4904 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004905 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004906 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004907 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004908 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004909
Dan Gohman1975d032008-10-30 20:40:10 +00004910 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004911 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004912 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004913 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004914 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004915 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004916 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004917 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004918 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004919
Bill Wendlingb01865c2008-11-30 13:52:49 +00004920 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004921 if ((match(C, m_Not(m_Specific(D))) &&
4922 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004923 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004924 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004925 if ((match(A, m_Not(m_Specific(D))) &&
4926 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004927 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004928 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004929 if ((match(C, m_Not(m_Specific(B))) &&
4930 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004931 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004932 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004933 if ((match(A, m_Not(m_Specific(B))) &&
4934 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004935 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004936 }
Chris Lattnere511b742006-11-14 07:46:50 +00004937
4938 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004939 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4940 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4941 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004942 SI0->getOperand(1) == SI1->getOperand(1) &&
4943 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004944 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4945 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004946 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004947 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004948 }
4949 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004950
Bill Wendlingb3833d12008-12-01 01:07:11 +00004951 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004952 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4953 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004954 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004955 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004956 }
4957 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004958 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4959 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004960 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004961 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004962 }
4963
Dan Gohman4ae51262009-08-12 16:23:25 +00004964 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004965 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004966 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004967 } else {
4968 A = 0;
4969 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004970 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004971 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004972 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004973 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004974
Misha Brukmancb6267b2004-07-30 12:50:08 +00004975 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004976 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004977 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004978 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004979 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004980 }
Chris Lattnera2881962003-02-18 19:28:33 +00004981
Reid Spencere4d87aa2006-12-23 06:05:41 +00004982 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4983 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004984 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004985 return R;
4986
Chris Lattner69d4ced2008-11-16 05:20:07 +00004987 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4988 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4989 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004990 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004991
4992 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004993 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004994 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004995 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004996 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4997 !isa<ICmpInst>(Op1C->getOperand(0))) {
4998 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004999 if (SrcTy == Op1C->getOperand(0)->getType() &&
5000 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005001 // Only do this if the casts both really cause code to be
5002 // generated.
5003 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5004 I.getType(), TD) &&
5005 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5006 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005007 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5008 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005009 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005010 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005011 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005012 }
Chris Lattner99c65742007-10-24 05:38:08 +00005013 }
5014
5015
5016 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5017 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005018 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5019 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5020 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005021 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005022
Chris Lattner7e708292002-06-25 16:13:24 +00005023 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005024}
5025
Dan Gohman844731a2008-05-13 00:00:25 +00005026namespace {
5027
Chris Lattnerc317d392004-02-16 01:20:27 +00005028// XorSelf - Implements: X ^ X --> 0
5029struct XorSelf {
5030 Value *RHS;
5031 XorSelf(Value *rhs) : RHS(rhs) {}
5032 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5033 Instruction *apply(BinaryOperator &Xor) const {
5034 return &Xor;
5035 }
5036};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005037
Dan Gohman844731a2008-05-13 00:00:25 +00005038}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005039
Chris Lattner7e708292002-06-25 16:13:24 +00005040Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005041 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005042 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005043
Evan Chengd34af782008-03-25 20:07:13 +00005044 if (isa<UndefValue>(Op1)) {
5045 if (isa<UndefValue>(Op0))
5046 // Handle undef ^ undef -> 0 special case. This is a common
5047 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005048 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005049 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005050 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005051
Chris Lattnerc317d392004-02-16 01:20:27 +00005052 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005053 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005054 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005055 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005056 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005057
5058 // See if we can simplify any instructions used by the instruction whose sole
5059 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005060 if (SimplifyDemandedInstructionBits(I))
5061 return &I;
5062 if (isa<VectorType>(I.getType()))
5063 if (isa<ConstantAggregateZero>(Op1))
5064 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005065
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005066 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005067 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005068 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5069 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5070 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5071 if (Op0I->getOpcode() == Instruction::And ||
5072 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005073 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5074 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005075 Value *NotY =
5076 Builder->CreateNot(Op0I->getOperand(1),
5077 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005078 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005079 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005080 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005081 }
5082 }
5083 }
5084 }
5085
5086
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005087 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005088 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005089 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005090 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005091 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005092 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005093
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005094 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005095 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005096 FCI->getOperand(0), FCI->getOperand(1));
5097 }
5098
Nick Lewycky517e1f52008-05-31 19:01:33 +00005099 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5100 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5101 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5102 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5103 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005104 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5105 (RHS == ConstantExpr::getCast(Opcode,
5106 ConstantInt::getTrue(*Context),
5107 Op0C->getDestTy()))) {
5108 CI->setPredicate(CI->getInversePredicate());
5109 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005110 }
5111 }
5112 }
5113 }
5114
Reid Spencere4d87aa2006-12-23 06:05:41 +00005115 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005116 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005117 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5118 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005119 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5120 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005121 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005122 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005123 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005124
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005125 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005126 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005127 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005128 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005129 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005130 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005131 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005132 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005133 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005134 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005135 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005136 Constant *C = ConstantInt::get(*Context,
5137 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005138 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005139
Chris Lattner7c4049c2004-01-12 19:35:11 +00005140 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005141 } else if (Op0I->getOpcode() == Instruction::Or) {
5142 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005143 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005144 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005145 // Anything in both C1 and C2 is known to be zero, remove it from
5146 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005147 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5148 NewRHS = ConstantExpr::getAnd(NewRHS,
5149 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005150 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005151 I.setOperand(0, Op0I->getOperand(0));
5152 I.setOperand(1, NewRHS);
5153 return &I;
5154 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005155 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005156 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005157 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005158
5159 // Try to fold constant and into select arguments.
5160 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005161 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005162 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005163 if (isa<PHINode>(Op0))
5164 if (Instruction *NV = FoldOpIntoPhi(I))
5165 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005166 }
5167
Dan Gohman186a6362009-08-12 16:04:34 +00005168 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005169 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005170 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005171
Dan Gohman186a6362009-08-12 16:04:34 +00005172 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005173 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005174 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005175
Chris Lattner318bf792007-03-18 22:51:34 +00005176
5177 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5178 if (Op1I) {
5179 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005180 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005181 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005182 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005183 I.swapOperands();
5184 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005185 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005186 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005187 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005188 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005189 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005190 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005191 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005192 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005193 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005194 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005195 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005196 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005197 std::swap(A, B);
5198 }
Chris Lattner318bf792007-03-18 22:51:34 +00005199 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005200 I.swapOperands(); // Simplified below.
5201 std::swap(Op0, Op1);
5202 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005203 }
Chris Lattner318bf792007-03-18 22:51:34 +00005204 }
5205
5206 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5207 if (Op0I) {
5208 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005209 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005210 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005211 if (A == Op1) // (B|A)^B == (A|B)^B
5212 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005213 if (B == Op1) // (A|B)^B == A & ~B
5214 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005215 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005216 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005217 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005218 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005219 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005220 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005221 if (A == Op1) // (A&B)^A -> (B&A)^A
5222 std::swap(A, B);
5223 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005224 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005225 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005226 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005227 }
Chris Lattner318bf792007-03-18 22:51:34 +00005228 }
5229
5230 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5231 if (Op0I && Op1I && Op0I->isShift() &&
5232 Op0I->getOpcode() == Op1I->getOpcode() &&
5233 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5234 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005235 Value *NewOp =
5236 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5237 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005238 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005239 Op1I->getOperand(1));
5240 }
5241
5242 if (Op0I && Op1I) {
5243 Value *A, *B, *C, *D;
5244 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005245 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5246 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005247 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005248 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005249 }
5250 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005251 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5252 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005253 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005254 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005255 }
5256
5257 // (A & B)^(C & D)
5258 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005259 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5260 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005261 // (X & Y)^(X & Y) -> (Y^Z) & X
5262 Value *X = 0, *Y = 0, *Z = 0;
5263 if (A == C)
5264 X = A, Y = B, Z = D;
5265 else if (A == D)
5266 X = A, Y = B, Z = C;
5267 else if (B == C)
5268 X = B, Y = A, Z = D;
5269 else if (B == D)
5270 X = B, Y = A, Z = C;
5271
5272 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005273 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005274 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005275 }
5276 }
5277 }
5278
Reid Spencere4d87aa2006-12-23 06:05:41 +00005279 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5280 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005281 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005282 return R;
5283
Chris Lattner6fc205f2006-05-05 06:39:07 +00005284 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005285 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005286 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005287 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5288 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005289 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005290 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005291 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5292 I.getType(), TD) &&
5293 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5294 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005295 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5296 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005297 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005298 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005299 }
Chris Lattner99c65742007-10-24 05:38:08 +00005300 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005301
Chris Lattner7e708292002-06-25 16:13:24 +00005302 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005303}
5304
Owen Andersond672ecb2009-07-03 00:17:18 +00005305static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005306 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005307 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005308}
Chris Lattnera96879a2004-09-29 17:40:11 +00005309
Dan Gohman6de29f82009-06-15 22:12:54 +00005310static bool HasAddOverflow(ConstantInt *Result,
5311 ConstantInt *In1, ConstantInt *In2,
5312 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005313 if (IsSigned)
5314 if (In2->getValue().isNegative())
5315 return Result->getValue().sgt(In1->getValue());
5316 else
5317 return Result->getValue().slt(In1->getValue());
5318 else
5319 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005320}
5321
Dan Gohman6de29f82009-06-15 22:12:54 +00005322/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005323/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005324static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005325 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005326 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005327 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005328
Dan Gohman6de29f82009-06-15 22:12:54 +00005329 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5330 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005331 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005332 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5333 ExtractElement(In1, Idx, Context),
5334 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005335 IsSigned))
5336 return true;
5337 }
5338 return false;
5339 }
5340
5341 return HasAddOverflow(cast<ConstantInt>(Result),
5342 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5343 IsSigned);
5344}
5345
5346static bool HasSubOverflow(ConstantInt *Result,
5347 ConstantInt *In1, ConstantInt *In2,
5348 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005349 if (IsSigned)
5350 if (In2->getValue().isNegative())
5351 return Result->getValue().slt(In1->getValue());
5352 else
5353 return Result->getValue().sgt(In1->getValue());
5354 else
5355 return Result->getValue().ugt(In1->getValue());
5356}
5357
Dan Gohman6de29f82009-06-15 22:12:54 +00005358/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5359/// overflowed for this type.
5360static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005361 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005362 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005363 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005364
5365 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5366 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005367 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005368 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5369 ExtractElement(In1, Idx, Context),
5370 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005371 IsSigned))
5372 return true;
5373 }
5374 return false;
5375 }
5376
5377 return HasSubOverflow(cast<ConstantInt>(Result),
5378 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5379 IsSigned);
5380}
5381
Chris Lattner574da9b2005-01-13 20:14:25 +00005382/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5383/// code necessary to compute the offset from the base pointer (without adding
5384/// in the base pointer). Return the result as a signed integer of intptr size.
5385static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005386 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005387 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005388 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005389 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005390
5391 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005392 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005393 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005394
Gabor Greif177dd3f2008-06-12 21:37:33 +00005395 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5396 ++i, ++GTI) {
5397 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005398 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005399 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5400 if (OpC->isZero()) continue;
5401
5402 // Handle a struct index, which adds its field offset to the pointer.
5403 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5404 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5405
Chris Lattner74381062009-08-30 07:44:24 +00005406 Result = IC.Builder->CreateAdd(Result,
5407 ConstantInt::get(IntPtrTy, Size),
5408 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005409 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005410 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005411
Owen Andersoneed707b2009-07-24 23:12:02 +00005412 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005413 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005414 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5415 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005416 // Emit an add instruction.
5417 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005418 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005419 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005420 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005421 if (Op->getType() != IntPtrTy)
5422 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005423 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005424 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005425 // We'll let instcombine(mul) convert this to a shl if possible.
5426 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005427 }
5428
5429 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005430 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005431 }
5432 return Result;
5433}
5434
Chris Lattner10c0d912008-04-22 02:53:33 +00005435
Dan Gohman8f080f02009-07-17 22:16:21 +00005436/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5437/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5438/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5439/// be complex, and scales are involved. The above expression would also be
5440/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5441/// This later form is less amenable to optimization though, and we are allowed
5442/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005443///
5444/// If we can't emit an optimized form for this expression, this returns null.
5445///
5446static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5447 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005448 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005449 gep_type_iterator GTI = gep_type_begin(GEP);
5450
5451 // Check to see if this gep only has a single variable index. If so, and if
5452 // any constant indices are a multiple of its scale, then we can compute this
5453 // in terms of the scale of the variable index. For example, if the GEP
5454 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5455 // because the expression will cross zero at the same point.
5456 unsigned i, e = GEP->getNumOperands();
5457 int64_t Offset = 0;
5458 for (i = 1; i != e; ++i, ++GTI) {
5459 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5460 // Compute the aggregate offset of constant indices.
5461 if (CI->isZero()) continue;
5462
5463 // Handle a struct index, which adds its field offset to the pointer.
5464 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5465 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5466 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005467 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005468 Offset += Size*CI->getSExtValue();
5469 }
5470 } else {
5471 // Found our variable index.
5472 break;
5473 }
5474 }
5475
5476 // If there are no variable indices, we must have a constant offset, just
5477 // evaluate it the general way.
5478 if (i == e) return 0;
5479
5480 Value *VariableIdx = GEP->getOperand(i);
5481 // Determine the scale factor of the variable element. For example, this is
5482 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005483 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005484
5485 // Verify that there are no other variable indices. If so, emit the hard way.
5486 for (++i, ++GTI; i != e; ++i, ++GTI) {
5487 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5488 if (!CI) return 0;
5489
5490 // Compute the aggregate offset of constant indices.
5491 if (CI->isZero()) continue;
5492
5493 // Handle a struct index, which adds its field offset to the pointer.
5494 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5495 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5496 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005497 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005498 Offset += Size*CI->getSExtValue();
5499 }
5500 }
5501
5502 // Okay, we know we have a single variable index, which must be a
5503 // pointer/array/vector index. If there is no offset, life is simple, return
5504 // the index.
5505 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5506 if (Offset == 0) {
5507 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5508 // we don't need to bother extending: the extension won't affect where the
5509 // computation crosses zero.
5510 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005511 VariableIdx = new TruncInst(VariableIdx,
5512 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005513 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005514 return VariableIdx;
5515 }
5516
5517 // Otherwise, there is an index. The computation we will do will be modulo
5518 // the pointer size, so get it.
5519 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5520
5521 Offset &= PtrSizeMask;
5522 VariableScale &= PtrSizeMask;
5523
5524 // To do this transformation, any constant index must be a multiple of the
5525 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5526 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5527 // multiple of the variable scale.
5528 int64_t NewOffs = Offset / (int64_t)VariableScale;
5529 if (Offset != NewOffs*(int64_t)VariableScale)
5530 return 0;
5531
5532 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005533 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005534 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005535 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005536 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005537 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005538 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005539 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005540}
5541
5542
Reid Spencere4d87aa2006-12-23 06:05:41 +00005543/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005544/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005545Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005546 ICmpInst::Predicate Cond,
5547 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005548 // Look through bitcasts.
5549 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5550 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005551
Chris Lattner574da9b2005-01-13 20:14:25 +00005552 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005553 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005554 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005555 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005556 // know pointers can't overflow since the gep is inbounds. See if we can
5557 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005558 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5559
5560 // If not, synthesize the offset the hard way.
5561 if (Offset == 0)
5562 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005563 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005564 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005565 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005566 // If the base pointers are different, but the indices are the same, just
5567 // compare the base pointer.
5568 if (PtrBase != GEPRHS->getOperand(0)) {
5569 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005570 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005571 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005572 if (IndicesTheSame)
5573 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5574 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5575 IndicesTheSame = false;
5576 break;
5577 }
5578
5579 // If all indices are the same, just compare the base pointers.
5580 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005581 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005582 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005583
5584 // Otherwise, the base pointers are different and the indices are
5585 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005586 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005587 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005588
Chris Lattnere9d782b2005-01-13 22:25:21 +00005589 // If one of the GEPs has all zero indices, recurse.
5590 bool AllZeros = true;
5591 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5592 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5593 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5594 AllZeros = false;
5595 break;
5596 }
5597 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005598 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5599 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005600
5601 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005602 AllZeros = true;
5603 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5604 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5605 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5606 AllZeros = false;
5607 break;
5608 }
5609 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005610 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005611
Chris Lattner4401c9c2005-01-14 00:20:05 +00005612 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5613 // If the GEPs only differ by one index, compare it.
5614 unsigned NumDifferences = 0; // Keep track of # differences.
5615 unsigned DiffOperand = 0; // The operand that differs.
5616 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5617 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005618 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5619 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005620 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005621 NumDifferences = 2;
5622 break;
5623 } else {
5624 if (NumDifferences++) break;
5625 DiffOperand = i;
5626 }
5627 }
5628
5629 if (NumDifferences == 0) // SAME GEP?
5630 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005631 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005632 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005633
Chris Lattner4401c9c2005-01-14 00:20:05 +00005634 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005635 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5636 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005637 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005638 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005639 }
5640 }
5641
Reid Spencere4d87aa2006-12-23 06:05:41 +00005642 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005643 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005644 if (TD &&
5645 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005646 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5647 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5648 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5649 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005650 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005651 }
5652 }
5653 return 0;
5654}
5655
Chris Lattnera5406232008-05-19 20:18:56 +00005656/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5657///
5658Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5659 Instruction *LHSI,
5660 Constant *RHSC) {
5661 if (!isa<ConstantFP>(RHSC)) return 0;
5662 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5663
5664 // Get the width of the mantissa. We don't want to hack on conversions that
5665 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005666 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005667 if (MantissaWidth == -1) return 0; // Unknown.
5668
5669 // Check to see that the input is converted from an integer type that is small
5670 // enough that preserves all bits. TODO: check here for "known" sign bits.
5671 // 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 +00005672 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005673
5674 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005675 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5676 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005677 ++InputSize;
5678
5679 // If the conversion would lose info, don't hack on this.
5680 if ((int)InputSize > MantissaWidth)
5681 return 0;
5682
5683 // Otherwise, we can potentially simplify the comparison. We know that it
5684 // will always come through as an integer value and we know the constant is
5685 // not a NAN (it would have been previously simplified).
5686 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5687
5688 ICmpInst::Predicate Pred;
5689 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005690 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005691 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005692 case FCmpInst::FCMP_OEQ:
5693 Pred = ICmpInst::ICMP_EQ;
5694 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005695 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005696 case FCmpInst::FCMP_OGT:
5697 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5698 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005699 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005700 case FCmpInst::FCMP_OGE:
5701 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5702 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005703 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005704 case FCmpInst::FCMP_OLT:
5705 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5706 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005707 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005708 case FCmpInst::FCMP_OLE:
5709 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5710 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005711 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005712 case FCmpInst::FCMP_ONE:
5713 Pred = ICmpInst::ICMP_NE;
5714 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005715 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005716 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005717 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005718 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005719 }
5720
5721 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5722
5723 // Now we know that the APFloat is a normal number, zero or inf.
5724
Chris Lattner85162782008-05-20 03:50:52 +00005725 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005726 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005727 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005728
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005729 if (!LHSUnsigned) {
5730 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5731 // and large values.
5732 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5733 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5734 APFloat::rmNearestTiesToEven);
5735 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5736 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5737 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005738 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5739 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005740 }
5741 } else {
5742 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5743 // +INF and large values.
5744 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5745 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5746 APFloat::rmNearestTiesToEven);
5747 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5748 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5749 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005750 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5751 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005752 }
Chris Lattnera5406232008-05-19 20:18:56 +00005753 }
5754
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005755 if (!LHSUnsigned) {
5756 // See if the RHS value is < SignedMin.
5757 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5758 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5759 APFloat::rmNearestTiesToEven);
5760 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5761 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5762 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005763 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5764 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005765 }
Chris Lattnera5406232008-05-19 20:18:56 +00005766 }
5767
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005768 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5769 // [0, UMAX], but it may still be fractional. See if it is fractional by
5770 // casting the FP value to the integer value and back, checking for equality.
5771 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005772 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005773 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5774 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005775 if (!RHS.isZero()) {
5776 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005777 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5778 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005779 if (!Equal) {
5780 // If we had a comparison against a fractional value, we have to adjust
5781 // the compare predicate and sometimes the value. RHSC is rounded towards
5782 // zero at this point.
5783 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005784 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005785 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005786 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005787 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005788 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005789 case ICmpInst::ICMP_ULE:
5790 // (float)int <= 4.4 --> int <= 4
5791 // (float)int <= -4.4 --> false
5792 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005793 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005794 break;
5795 case ICmpInst::ICMP_SLE:
5796 // (float)int <= 4.4 --> int <= 4
5797 // (float)int <= -4.4 --> int < -4
5798 if (RHS.isNegative())
5799 Pred = ICmpInst::ICMP_SLT;
5800 break;
5801 case ICmpInst::ICMP_ULT:
5802 // (float)int < -4.4 --> false
5803 // (float)int < 4.4 --> int <= 4
5804 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005805 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005806 Pred = ICmpInst::ICMP_ULE;
5807 break;
5808 case ICmpInst::ICMP_SLT:
5809 // (float)int < -4.4 --> int < -4
5810 // (float)int < 4.4 --> int <= 4
5811 if (!RHS.isNegative())
5812 Pred = ICmpInst::ICMP_SLE;
5813 break;
5814 case ICmpInst::ICMP_UGT:
5815 // (float)int > 4.4 --> int > 4
5816 // (float)int > -4.4 --> true
5817 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005818 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005819 break;
5820 case ICmpInst::ICMP_SGT:
5821 // (float)int > 4.4 --> int > 4
5822 // (float)int > -4.4 --> int >= -4
5823 if (RHS.isNegative())
5824 Pred = ICmpInst::ICMP_SGE;
5825 break;
5826 case ICmpInst::ICMP_UGE:
5827 // (float)int >= -4.4 --> true
5828 // (float)int >= 4.4 --> int > 4
5829 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005830 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005831 Pred = ICmpInst::ICMP_UGT;
5832 break;
5833 case ICmpInst::ICMP_SGE:
5834 // (float)int >= -4.4 --> int >= -4
5835 // (float)int >= 4.4 --> int > 4
5836 if (!RHS.isNegative())
5837 Pred = ICmpInst::ICMP_SGT;
5838 break;
5839 }
Chris Lattnera5406232008-05-19 20:18:56 +00005840 }
5841 }
5842
5843 // Lower this FP comparison into an appropriate integer version of the
5844 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005845 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005846}
5847
Reid Spencere4d87aa2006-12-23 06:05:41 +00005848Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5849 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005850 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005851
Chris Lattner58e97462007-01-14 19:42:17 +00005852 // Fold trivial predicates.
5853 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005854 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005855 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005856 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005857
5858 // Simplify 'fcmp pred X, X'
5859 if (Op0 == Op1) {
5860 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005861 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005862 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5863 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5864 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner9e17b632009-09-02 05:12:37 +00005865 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005866 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5867 case FCmpInst::FCMP_OLT: // True if ordered and less than
5868 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner9e17b632009-09-02 05:12:37 +00005869 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005870
5871 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5872 case FCmpInst::FCMP_ULT: // True if unordered or less than
5873 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5874 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5875 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5876 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005877 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005878 return &I;
5879
5880 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5881 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5882 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5883 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5884 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5885 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005886 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005887 return &I;
5888 }
5889 }
5890
Reid Spencere4d87aa2006-12-23 06:05:41 +00005891 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005892 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005893
Reid Spencere4d87aa2006-12-23 06:05:41 +00005894 // Handle fcmp with constant RHS
5895 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005896 // If the constant is a nan, see if we can fold the comparison based on it.
5897 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5898 if (CFP->getValueAPF().isNaN()) {
5899 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005900 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005901 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5902 "Comparison must be either ordered or unordered!");
5903 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005904 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005905 }
5906 }
5907
Reid Spencere4d87aa2006-12-23 06:05:41 +00005908 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5909 switch (LHSI->getOpcode()) {
5910 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005911 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5912 // block. If in the same block, we're encouraging jump threading. If
5913 // not, we are just pessimizing the code by making an i1 phi.
5914 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00005915 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005916 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005917 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005918 case Instruction::SIToFP:
5919 case Instruction::UIToFP:
5920 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5921 return NV;
5922 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005923 case Instruction::Select:
5924 // If either operand of the select is a constant, we can fold the
5925 // comparison into the select arms, which will cause one to be
5926 // constant folded and the select turned into a bitwise or.
5927 Value *Op1 = 0, *Op2 = 0;
5928 if (LHSI->hasOneUse()) {
5929 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5930 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005931 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005932 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005933 Op2 = Builder->CreateFCmp(I.getPredicate(),
5934 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005935 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5936 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005937 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005938 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005939 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5940 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005941 }
5942 }
5943
5944 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005945 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005946 break;
5947 }
5948 }
5949
5950 return Changed ? &I : 0;
5951}
5952
5953Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5954 bool Changed = SimplifyCompare(I);
5955 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5956 const Type *Ty = Op0->getType();
5957
5958 // icmp X, X
5959 if (Op0 == Op1)
Chris Lattner9e17b632009-09-02 05:12:37 +00005960 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005961 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005962
5963 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005964 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005965
Reid Spencere4d87aa2006-12-23 06:05:41 +00005966 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005967 // addresses never equal each other! We already know that Op0 != Op1.
Chris Lattnerbbc33852009-10-05 02:47:47 +00005968 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
Misha Brukmanfd939082005-04-21 23:48:37 +00005969 isa<ConstantPointerNull>(Op0)) &&
Chris Lattnerbbc33852009-10-05 02:47:47 +00005970 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005971 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00005972 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005973 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005974
Reid Spencere4d87aa2006-12-23 06:05:41 +00005975 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00005976 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005977 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005978 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005979 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00005980 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00005981 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005982 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005983 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005984 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005985
Reid Spencere4d87aa2006-12-23 06:05:41 +00005986 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005987 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005988 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005989 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00005990 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005991 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005992 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005993 case ICmpInst::ICMP_SGT:
5994 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005995 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005996 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00005997 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005998 return BinaryOperator::CreateAnd(Not, Op0);
5999 }
6000 case ICmpInst::ICMP_UGE:
6001 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6002 // FALL THROUGH
6003 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006004 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006005 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006006 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006007 case ICmpInst::ICMP_SGE:
6008 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6009 // FALL THROUGH
6010 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006011 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006012 return BinaryOperator::CreateOr(Not, Op0);
6013 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006014 }
Chris Lattner8b170942002-08-09 23:47:40 +00006015 }
6016
Dan Gohman1c8491e2009-04-25 17:12:48 +00006017 unsigned BitWidth = 0;
6018 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006019 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6020 else if (Ty->isIntOrIntVector())
6021 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006022
6023 bool isSignBit = false;
6024
Dan Gohman81b28ce2008-09-16 18:46:06 +00006025 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006026 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006027 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006028
Chris Lattnerb6566012008-01-05 01:18:20 +00006029 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6030 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006031 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006032 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006033 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006034 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006035
Dan Gohman81b28ce2008-09-16 18:46:06 +00006036 // If we have an icmp le or icmp ge instruction, turn it into the
6037 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6038 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006039 switch (I.getPredicate()) {
6040 default: break;
6041 case ICmpInst::ICMP_ULE:
6042 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006043 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006044 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006045 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006046 case ICmpInst::ICMP_SLE:
6047 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006048 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006049 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006050 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006051 case ICmpInst::ICMP_UGE:
6052 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006053 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006054 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006055 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006056 case ICmpInst::ICMP_SGE:
6057 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006058 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006059 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006060 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006061 }
6062
Chris Lattner183661e2008-07-11 05:40:05 +00006063 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006064 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006065 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006066 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6067 }
6068
6069 // See if we can fold the comparison based on range information we can get
6070 // by checking whether bits are known to be zero or one in the input.
6071 if (BitWidth != 0) {
6072 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6073 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6074
6075 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006076 isSignBit ? APInt::getSignBit(BitWidth)
6077 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006078 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006079 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006080 if (SimplifyDemandedBits(I.getOperandUse(1),
6081 APInt::getAllOnesValue(BitWidth),
6082 Op1KnownZero, Op1KnownOne, 0))
6083 return &I;
6084
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006085 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006086 // in. Compute the Min, Max and RHS values based on the known bits. For the
6087 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006088 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6089 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6090 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6091 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6092 Op0Min, Op0Max);
6093 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6094 Op1Min, Op1Max);
6095 } else {
6096 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6097 Op0Min, Op0Max);
6098 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6099 Op1Min, Op1Max);
6100 }
6101
Chris Lattner183661e2008-07-11 05:40:05 +00006102 // If Min and Max are known to be the same, then SimplifyDemandedBits
6103 // figured out that the LHS is a constant. Just constant fold this now so
6104 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006105 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006106 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006107 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006108 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006109 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006110 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006111
Chris Lattner183661e2008-07-11 05:40:05 +00006112 // Based on the range information we know about the LHS, see if we can
6113 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006114 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006115 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006116 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006117 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006118 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006119 break;
6120 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006121 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006122 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006123 break;
6124 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006125 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006126 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006127 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006128 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006129 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006130 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006131 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6132 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006133 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006134 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006135
6136 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6137 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006138 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006139 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006140 }
Chris Lattner84dff672008-07-11 05:08:55 +00006141 break;
6142 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006143 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006144 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006146 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006147
6148 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006149 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006150 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6151 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006152 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006153 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006154
6155 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6156 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006157 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006158 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159 }
Chris Lattner84dff672008-07-11 05:08:55 +00006160 break;
6161 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006162 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006163 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
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 <s 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 <s 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 }
Chris Lattner84dff672008-07-11 05:08:55 +00006173 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006174 case ICmpInst::ICMP_SGT:
6175 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006176 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006177 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006178 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006179
6180 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006181 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006182 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6183 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006184 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006185 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186 }
6187 break;
6188 case ICmpInst::ICMP_SGE:
6189 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6190 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006191 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006192 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006193 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006194 break;
6195 case ICmpInst::ICMP_SLE:
6196 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6197 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006198 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006199 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006200 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006201 break;
6202 case ICmpInst::ICMP_UGE:
6203 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6204 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006205 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006207 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006208 break;
6209 case ICmpInst::ICMP_ULE:
6210 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6211 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006212 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006213 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006214 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006215 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006216 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006217
6218 // Turn a signed comparison into an unsigned one if both operands
6219 // are known to have the same sign.
6220 if (I.isSignedPredicate() &&
6221 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6222 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006223 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006224 }
6225
6226 // Test if the ICmpInst instruction is used exclusively by a select as
6227 // part of a minimum or maximum operation. If so, refrain from doing
6228 // any other folding. This helps out other analyses which understand
6229 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6230 // and CodeGen. And in this case, at least one of the comparison
6231 // operands has at least one user besides the compare (the select),
6232 // which would often largely negate the benefit of folding anyway.
6233 if (I.hasOneUse())
6234 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6235 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6236 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6237 return 0;
6238
6239 // See if we are doing a comparison between a constant and an instruction that
6240 // can be folded into the comparison.
6241 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006242 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006243 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006244 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006245 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006246 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6247 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006248 }
6249
Chris Lattner01deb9d2007-04-03 17:43:25 +00006250 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006251 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6252 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6253 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006254 case Instruction::GetElementPtr:
6255 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006256 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006257 bool isAllZeros = true;
6258 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6259 if (!isa<Constant>(LHSI->getOperand(i)) ||
6260 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6261 isAllZeros = false;
6262 break;
6263 }
6264 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006265 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006266 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006267 }
6268 break;
6269
Chris Lattner6970b662005-04-23 15:31:55 +00006270 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006271 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006272 // block. If in the same block, we're encouraging jump threading. If
6273 // not, we are just pessimizing the code by making an i1 phi.
6274 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006275 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006276 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006277 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006278 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006279 // If either operand of the select is a constant, we can fold the
6280 // comparison into the select arms, which will cause one to be
6281 // constant folded and the select turned into a bitwise or.
6282 Value *Op1 = 0, *Op2 = 0;
6283 if (LHSI->hasOneUse()) {
6284 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6285 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006286 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006287 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006288 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6289 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006290 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6291 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006292 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006293 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006294 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6295 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006296 }
6297 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006298
Chris Lattner6970b662005-04-23 15:31:55 +00006299 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006300 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006301 break;
6302 }
Chris Lattner4802d902007-04-06 18:57:34 +00006303 case Instruction::Malloc:
6304 // If we have (malloc != null), and if the malloc has a single use, we
6305 // can assume it is successful and remove the malloc.
6306 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006307 Worklist.Add(LHSI);
Victor Hernandez83d63912009-09-18 22:35:49 +00006308 return ReplaceInstUsesWith(I,
6309 ConstantInt::get(Type::getInt1Ty(*Context),
6310 !I.isTrueWhenEqual()));
6311 }
6312 break;
6313 case Instruction::Call:
6314 // If we have (malloc != null), and if the malloc has a single use, we
6315 // can assume it is successful and remove the malloc.
6316 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6317 isa<ConstantPointerNull>(RHSC)) {
6318 Worklist.Add(LHSI);
6319 return ReplaceInstUsesWith(I,
6320 ConstantInt::get(Type::getInt1Ty(*Context),
6321 !I.isTrueWhenEqual()));
6322 }
6323 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006324 }
Chris Lattner6970b662005-04-23 15:31:55 +00006325 }
6326
Reid Spencere4d87aa2006-12-23 06:05:41 +00006327 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006328 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006329 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006330 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006331 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006332 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6333 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006334 return NI;
6335
Reid Spencere4d87aa2006-12-23 06:05:41 +00006336 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006337 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6338 // now.
6339 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6340 if (isa<PointerType>(Op0->getType()) &&
6341 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006342 // We keep moving the cast from the left operand over to the right
6343 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006344 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006345
Chris Lattner57d86372007-01-06 01:45:59 +00006346 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6347 // so eliminate it as well.
6348 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6349 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006350
Chris Lattnerde90b762003-11-03 04:25:02 +00006351 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006352 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006353 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006354 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006355 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006356 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006357 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006358 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006359 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006360 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006361 }
Chris Lattner57d86372007-01-06 01:45:59 +00006362 }
6363
6364 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006365 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006366 // This comes up when you have code like
6367 // int X = A < B;
6368 // if (X) ...
6369 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006370 // with a constant or another cast from the same type.
6371 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006372 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006373 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006374 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006375
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006376 // See if it's the same type of instruction on the left and right.
6377 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6378 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006379 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006380 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006381 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006382 default: break;
6383 case Instruction::Add:
6384 case Instruction::Sub:
6385 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006386 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006387 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006388 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006389 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6390 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6391 if (CI->getValue().isSignBit()) {
6392 ICmpInst::Predicate Pred = I.isSignedPredicate()
6393 ? I.getUnsignedPredicate()
6394 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006395 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006396 Op1I->getOperand(0));
6397 }
6398
6399 if (CI->getValue().isMaxSignedValue()) {
6400 ICmpInst::Predicate Pred = I.isSignedPredicate()
6401 ? I.getUnsignedPredicate()
6402 : I.getSignedPredicate();
6403 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006404 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006405 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006406 }
6407 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006408 break;
6409 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006410 if (!I.isEquality())
6411 break;
6412
Nick Lewycky5d52c452008-08-21 05:56:10 +00006413 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6414 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6415 // Mask = -1 >> count-trailing-zeros(Cst).
6416 if (!CI->isZero() && !CI->isOne()) {
6417 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006418 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006419 APInt::getLowBitsSet(AP.getBitWidth(),
6420 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006421 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006422 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6423 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006424 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006425 }
6426 }
6427 break;
6428 }
6429 }
6430 }
6431 }
6432
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006433 // ~x < ~y --> y < x
6434 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006435 if (match(Op0, m_Not(m_Value(A))) &&
6436 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006437 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006438 }
6439
Chris Lattner65b72ba2006-09-18 04:22:48 +00006440 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006441 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006442
6443 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006444 if (match(Op0, m_Neg(m_Value(A))) &&
6445 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006446 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006447
Dan Gohman4ae51262009-08-12 16:23:25 +00006448 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006449 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6450 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006451 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006452 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006453 }
6454
Dan Gohman4ae51262009-08-12 16:23:25 +00006455 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006456 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006457 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006458 if (match(B, m_ConstantInt(C1)) &&
6459 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006460 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006461 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006462 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6463 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006464 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006465
6466 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006467 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6468 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6469 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6470 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006471 }
6472 }
6473
Dan Gohman4ae51262009-08-12 16:23:25 +00006474 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006475 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006476 // A == (A^B) -> B == 0
6477 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006478 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006479 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006480 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006481
6482 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006483 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006484 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006485 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006486
6487 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006488 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006489 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006490 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006491
Chris Lattner9c2328e2006-11-14 06:06:06 +00006492 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6493 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006494 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6495 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006496 Value *X = 0, *Y = 0, *Z = 0;
6497
6498 if (A == C) {
6499 X = B; Y = D; Z = A;
6500 } else if (A == D) {
6501 X = B; Y = C; Z = A;
6502 } else if (B == C) {
6503 X = A; Y = D; Z = B;
6504 } else if (B == D) {
6505 X = A; Y = C; Z = B;
6506 }
6507
6508 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006509 Op1 = Builder->CreateXor(X, Y, "tmp");
6510 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006511 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006512 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006513 return &I;
6514 }
6515 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006516 }
Chris Lattner7e708292002-06-25 16:13:24 +00006517 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006518}
6519
Chris Lattner562ef782007-06-20 23:46:26 +00006520
6521/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6522/// and CmpRHS are both known to be integer constants.
6523Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6524 ConstantInt *DivRHS) {
6525 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6526 const APInt &CmpRHSV = CmpRHS->getValue();
6527
6528 // FIXME: If the operand types don't match the type of the divide
6529 // then don't attempt this transform. The code below doesn't have the
6530 // logic to deal with a signed divide and an unsigned compare (and
6531 // vice versa). This is because (x /s C1) <s C2 produces different
6532 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6533 // (x /u C1) <u C2. Simply casting the operands and result won't
6534 // work. :( The if statement below tests that condition and bails
6535 // if it finds it.
6536 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6537 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6538 return 0;
6539 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006540 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006541 if (DivIsSigned && DivRHS->isAllOnesValue())
6542 return 0; // The overflow computation also screws up here
6543 if (DivRHS->isOne())
6544 return 0; // Not worth bothering, and eliminates some funny cases
6545 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006546
6547 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6548 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6549 // C2 (CI). By solving for X we can turn this into a range check
6550 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006551 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006552
6553 // Determine if the product overflows by seeing if the product is
6554 // not equal to the divide. Make sure we do the same kind of divide
6555 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006556 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6557 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006558
6559 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006560 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006561
Chris Lattner1dbfd482007-06-21 18:11:19 +00006562 // Figure out the interval that is being checked. For example, a comparison
6563 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6564 // Compute this interval based on the constants involved and the signedness of
6565 // the compare/divide. This computes a half-open interval, keeping track of
6566 // whether either value in the interval overflows. After analysis each
6567 // overflow variable is set to 0 if it's corresponding bound variable is valid
6568 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6569 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006570 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006571
Chris Lattner562ef782007-06-20 23:46:26 +00006572 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006573 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006574 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006575 HiOverflow = LoOverflow = ProdOV;
6576 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006577 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006578 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006579 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006580 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006581 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006582 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006583 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006584 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6585 HiOverflow = LoOverflow = ProdOV;
6586 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006587 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006588 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006589 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006590 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006591 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6592 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006593 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006594 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006595 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006596 true) ? -1 : 0;
6597 }
Chris Lattner562ef782007-06-20 23:46:26 +00006598 }
Dan Gohman76491272008-02-13 22:09:18 +00006599 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006600 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006601 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006602 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006603 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006604 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6605 HiOverflow = 1; // [INTMIN+1, overflow)
6606 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6607 }
Dan Gohman76491272008-02-13 22:09:18 +00006608 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006609 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006610 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006611 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006612 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006613 LoOverflow = AddWithOverflow(LoBound, HiBound,
6614 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006615 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006616 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6617 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006618 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006619 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006620 }
6621
Chris Lattner1dbfd482007-06-21 18:11:19 +00006622 // Dividing by a negative swaps the condition. LT <-> GT
6623 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006624 }
6625
6626 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006627 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006628 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006629 case ICmpInst::ICMP_EQ:
6630 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006631 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006632 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006633 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006634 ICmpInst::ICMP_UGE, X, LoBound);
6635 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006636 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006637 ICmpInst::ICMP_ULT, X, HiBound);
6638 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006639 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006640 case ICmpInst::ICMP_NE:
6641 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006642 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006643 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006644 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006645 ICmpInst::ICMP_ULT, X, LoBound);
6646 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006647 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006648 ICmpInst::ICMP_UGE, X, HiBound);
6649 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006650 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006651 case ICmpInst::ICMP_ULT:
6652 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006653 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006654 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006655 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006656 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006657 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006658 case ICmpInst::ICMP_UGT:
6659 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006660 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006661 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006662 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006663 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006664 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006665 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006666 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006667 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006668 }
6669}
6670
6671
Chris Lattner01deb9d2007-04-03 17:43:25 +00006672/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6673///
6674Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6675 Instruction *LHSI,
6676 ConstantInt *RHS) {
6677 const APInt &RHSV = RHS->getValue();
6678
6679 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006680 case Instruction::Trunc:
6681 if (ICI.isEquality() && LHSI->hasOneUse()) {
6682 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6683 // of the high bits truncated out of x are known.
6684 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6685 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6686 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6687 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6688 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6689
6690 // If all the high bits are known, we can do this xform.
6691 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6692 // Pull in the high bits from known-ones set.
6693 APInt NewRHS(RHS->getValue());
6694 NewRHS.zext(SrcBits);
6695 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006696 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006697 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006698 }
6699 }
6700 break;
6701
Duncan Sands0091bf22007-04-04 06:42:45 +00006702 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006703 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6704 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6705 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006706 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6707 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006708 Value *CompareVal = LHSI->getOperand(0);
6709
6710 // If the sign bit of the XorCST is not set, there is no change to
6711 // the operation, just stop using the Xor.
6712 if (!XorCST->getValue().isNegative()) {
6713 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006714 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006715 return &ICI;
6716 }
6717
6718 // Was the old condition true if the operand is positive?
6719 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6720
6721 // If so, the new one isn't.
6722 isTrueIfPositive ^= true;
6723
6724 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006725 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006726 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006727 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006728 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006729 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006730 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006731
6732 if (LHSI->hasOneUse()) {
6733 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6734 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6735 const APInt &SignBit = XorCST->getValue();
6736 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6737 ? ICI.getUnsignedPredicate()
6738 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006739 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006740 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006741 }
6742
6743 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006744 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006745 const APInt &NotSignBit = XorCST->getValue();
6746 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6747 ? ICI.getUnsignedPredicate()
6748 : ICI.getSignedPredicate();
6749 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006750 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006751 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006752 }
6753 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006754 }
6755 break;
6756 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6757 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6758 LHSI->getOperand(0)->hasOneUse()) {
6759 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6760
6761 // If the LHS is an AND of a truncating cast, we can widen the
6762 // and/compare to be the input width without changing the value
6763 // produced, eliminating a cast.
6764 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6765 // We can do this transformation if either the AND constant does not
6766 // have its sign bit set or if it is an equality comparison.
6767 // Extending a relational comparison when we're checking the sign
6768 // bit would not work.
6769 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006770 (ICI.isEquality() ||
6771 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006772 uint32_t BitWidth =
6773 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6774 APInt NewCST = AndCST->getValue();
6775 NewCST.zext(BitWidth);
6776 APInt NewCI = RHSV;
6777 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006778 Value *NewAnd =
6779 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006780 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006781 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006782 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006783 }
6784 }
6785
6786 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6787 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6788 // happens a LOT in code produced by the C front-end, for bitfield
6789 // access.
6790 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6791 if (Shift && !Shift->isShift())
6792 Shift = 0;
6793
6794 ConstantInt *ShAmt;
6795 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6796 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6797 const Type *AndTy = AndCST->getType(); // Type of the and.
6798
6799 // We can fold this as long as we can't shift unknown bits
6800 // into the mask. This can only happen with signed shift
6801 // rights, as they sign-extend.
6802 if (ShAmt) {
6803 bool CanFold = Shift->isLogicalShift();
6804 if (!CanFold) {
6805 // To test for the bad case of the signed shr, see if any
6806 // of the bits shifted in could be tested after the mask.
6807 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6808 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6809
6810 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6811 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6812 AndCST->getValue()) == 0)
6813 CanFold = true;
6814 }
6815
6816 if (CanFold) {
6817 Constant *NewCst;
6818 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006819 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006820 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006821 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006822
6823 // Check to see if we are shifting out any of the bits being
6824 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006825 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006826 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006827 // If we shifted bits out, the fold is not going to work out.
6828 // As a special case, check to see if this means that the
6829 // result is always true or false now.
6830 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006831 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006832 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006833 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006834 } else {
6835 ICI.setOperand(1, NewCst);
6836 Constant *NewAndCST;
6837 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006838 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006839 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006840 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006841 LHSI->setOperand(1, NewAndCST);
6842 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006843 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006844 return &ICI;
6845 }
6846 }
6847 }
6848
6849 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6850 // preferable because it allows the C<<Y expression to be hoisted out
6851 // of a loop if Y is invariant and X is not.
6852 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006853 ICI.isEquality() && !Shift->isArithmeticShift() &&
6854 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006855 // Compute C << Y.
6856 Value *NS;
6857 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006858 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006859 } else {
6860 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006861 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006862 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006863
6864 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006865 Value *NewAnd =
6866 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006867
6868 ICI.setOperand(0, NewAnd);
6869 return &ICI;
6870 }
6871 }
6872 break;
6873
Chris Lattnera0141b92007-07-15 20:42:37 +00006874 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6875 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6876 if (!ShAmt) break;
6877
6878 uint32_t TypeBits = RHSV.getBitWidth();
6879
6880 // Check that the shift amount is in range. If not, don't perform
6881 // undefined shifts. When the shift is visited it will be
6882 // simplified.
6883 if (ShAmt->uge(TypeBits))
6884 break;
6885
6886 if (ICI.isEquality()) {
6887 // If we are comparing against bits always shifted out, the
6888 // comparison cannot succeed.
6889 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006890 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006891 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006892 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6893 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006894 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006895 return ReplaceInstUsesWith(ICI, Cst);
6896 }
6897
6898 if (LHSI->hasOneUse()) {
6899 // Otherwise strength reduce the shift into an and.
6900 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6901 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006902 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006903 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006904
Chris Lattner74381062009-08-30 07:44:24 +00006905 Value *And =
6906 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006907 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006908 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006909 }
6910 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006911
6912 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6913 bool TrueIfSigned = false;
6914 if (LHSI->hasOneUse() &&
6915 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6916 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006917 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006918 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006919 Value *And =
6920 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006921 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006922 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006923 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006924 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006925 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006926
6927 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006928 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006929 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006930 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006931 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006932
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006933 // Check that the shift amount is in range. If not, don't perform
6934 // undefined shifts. When the shift is visited it will be
6935 // simplified.
6936 uint32_t TypeBits = RHSV.getBitWidth();
6937 if (ShAmt->uge(TypeBits))
6938 break;
6939
6940 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006941
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006942 // If we are comparing against bits always shifted out, the
6943 // comparison cannot succeed.
6944 APInt Comp = RHSV << ShAmtVal;
6945 if (LHSI->getOpcode() == Instruction::LShr)
6946 Comp = Comp.lshr(ShAmtVal);
6947 else
6948 Comp = Comp.ashr(ShAmtVal);
6949
6950 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6951 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006952 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006953 return ReplaceInstUsesWith(ICI, Cst);
6954 }
6955
6956 // Otherwise, check to see if the bits shifted out are known to be zero.
6957 // If so, we can compare against the unshifted value:
6958 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006959 if (LHSI->hasOneUse() &&
6960 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006961 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006962 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006963 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006964 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006965
Evan Chengf30752c2008-04-23 00:38:06 +00006966 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006967 // Otherwise strength reduce the shift into an and.
6968 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006969 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006970
Chris Lattner74381062009-08-30 07:44:24 +00006971 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6972 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006973 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006974 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006975 }
6976 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006977 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006978
6979 case Instruction::SDiv:
6980 case Instruction::UDiv:
6981 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6982 // Fold this div into the comparison, producing a range check.
6983 // Determine, based on the divide type, what the range is being
6984 // checked. If there is an overflow on the low or high side, remember
6985 // it, otherwise compute the range [low, hi) bounding the new value.
6986 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006987 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6988 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6989 DivRHS))
6990 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006991 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006992
6993 case Instruction::Add:
6994 // Fold: icmp pred (add, X, C1), C2
6995
6996 if (!ICI.isEquality()) {
6997 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6998 if (!LHSC) break;
6999 const APInt &LHSV = LHSC->getValue();
7000
7001 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7002 .subtract(LHSV);
7003
7004 if (ICI.isSignedPredicate()) {
7005 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007006 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007007 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007008 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007009 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007010 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007011 }
7012 } else {
7013 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007014 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007015 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007016 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007017 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007018 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007019 }
7020 }
7021 }
7022 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007023 }
7024
7025 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7026 if (ICI.isEquality()) {
7027 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7028
7029 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7030 // the second operand is a constant, simplify a bit.
7031 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7032 switch (BO->getOpcode()) {
7033 case Instruction::SRem:
7034 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7035 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7036 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7037 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007038 Value *NewRem =
7039 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7040 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007041 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007042 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007043 }
7044 }
7045 break;
7046 case Instruction::Add:
7047 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7048 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7049 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007050 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007051 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007052 } else if (RHSV == 0) {
7053 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7054 // efficiently invertible, or if the add has just this one use.
7055 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7056
Dan Gohman186a6362009-08-12 16:04:34 +00007057 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007058 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007059 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007060 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007061 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007062 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007063 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007064 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007065 }
7066 }
7067 break;
7068 case Instruction::Xor:
7069 // For the xor case, we can xor two constants together, eliminating
7070 // the explicit xor.
7071 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007072 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007073 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007074
7075 // FALLTHROUGH
7076 case Instruction::Sub:
7077 // Replace (([sub|xor] A, B) != 0) with (A != B)
7078 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007079 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007080 BO->getOperand(1));
7081 break;
7082
7083 case Instruction::Or:
7084 // If bits are being or'd in that are not present in the constant we
7085 // are comparing against, then the comparison could never succeed!
7086 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007087 Constant *NotCI = ConstantExpr::getNot(RHS);
7088 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007089 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007090 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007091 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007092 }
7093 break;
7094
7095 case Instruction::And:
7096 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7097 // If bits are being compared against that are and'd out, then the
7098 // comparison can never succeed!
7099 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007100 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007101 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007102 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007103
7104 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7105 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007106 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007107 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007108 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007109
7110 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007111 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007112 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007113 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007114 ICmpInst::Predicate pred = isICMP_NE ?
7115 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007116 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007117 }
7118
7119 // ((X & ~7) == 0) --> X < 8
7120 if (RHSV == 0 && isHighOnes(BOC)) {
7121 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007122 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007123 ICmpInst::Predicate pred = isICMP_NE ?
7124 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007125 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007126 }
7127 }
7128 default: break;
7129 }
7130 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7131 // Handle icmp {eq|ne} <intrinsic>, intcst.
7132 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007133 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007134 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007135 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007136 return &ICI;
7137 }
7138 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007139 }
7140 return 0;
7141}
7142
7143/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7144/// We only handle extending casts so far.
7145///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007146Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7147 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007148 Value *LHSCIOp = LHSCI->getOperand(0);
7149 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007150 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007151 Value *RHSCIOp;
7152
Chris Lattner8c756c12007-05-05 22:41:33 +00007153 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7154 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007155 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7156 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007157 cast<IntegerType>(DestTy)->getBitWidth()) {
7158 Value *RHSOp = 0;
7159 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007160 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007161 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7162 RHSOp = RHSC->getOperand(0);
7163 // If the pointer types don't match, insert a bitcast.
7164 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007165 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007166 }
7167
7168 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007169 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007170 }
7171
7172 // The code below only handles extension cast instructions, so far.
7173 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007174 if (LHSCI->getOpcode() != Instruction::ZExt &&
7175 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007176 return 0;
7177
Reid Spencere4d87aa2006-12-23 06:05:41 +00007178 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7179 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007180
Reid Spencere4d87aa2006-12-23 06:05:41 +00007181 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007182 // Not an extension from the same type?
7183 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007184 if (RHSCIOp->getType() != LHSCIOp->getType())
7185 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007186
Nick Lewycky4189a532008-01-28 03:48:02 +00007187 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007188 // and the other is a zext), then we can't handle this.
7189 if (CI->getOpcode() != LHSCI->getOpcode())
7190 return 0;
7191
Nick Lewycky4189a532008-01-28 03:48:02 +00007192 // Deal with equality cases early.
7193 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007194 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007195
7196 // A signed comparison of sign extended values simplifies into a
7197 // signed comparison.
7198 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007199 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007200
7201 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007202 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007203 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007204
Reid Spencere4d87aa2006-12-23 06:05:41 +00007205 // If we aren't dealing with a constant on the RHS, exit early
7206 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7207 if (!CI)
7208 return 0;
7209
7210 // Compute the constant that would happen if we truncated to SrcTy then
7211 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007212 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7213 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007214 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007215
7216 // If the re-extended constant didn't change...
7217 if (Res2 == CI) {
7218 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7219 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007220 // %A = sext i16 %X to i32
7221 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007222 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007223 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007224 // because %A may have negative value.
7225 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007226 // However, we allow this when the compare is EQ/NE, because they are
7227 // signless.
7228 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007229 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007230 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007231 }
7232
7233 // The re-extended constant changed so the constant cannot be represented
7234 // in the shorter type. Consequently, we cannot emit a simple comparison.
7235
7236 // First, handle some easy cases. We know the result cannot be equal at this
7237 // point so handle the ICI.isEquality() cases
7238 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007239 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007240 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007241 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007242
7243 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7244 // should have been folded away previously and not enter in here.
7245 Value *Result;
7246 if (isSignedCmp) {
7247 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007248 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007249 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007250 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007251 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007252 } else {
7253 // We're performing an unsigned comparison.
7254 if (isSignedExt) {
7255 // We're performing an unsigned comp with a sign extended value.
7256 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007257 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007258 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007259 } else {
7260 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007261 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007262 }
7263 }
7264
7265 // Finally, return the value computed.
7266 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007267 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007268 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007269
7270 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7271 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7272 "ICmp should be folded!");
7273 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007274 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007275 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007276}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007277
Reid Spencer832254e2007-02-02 02:16:23 +00007278Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7279 return commonShiftTransforms(I);
7280}
7281
7282Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7283 return commonShiftTransforms(I);
7284}
7285
7286Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007287 if (Instruction *R = commonShiftTransforms(I))
7288 return R;
7289
7290 Value *Op0 = I.getOperand(0);
7291
7292 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7293 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7294 if (CSI->isAllOnesValue())
7295 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007296
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007297 // See if we can turn a signed shr into an unsigned shr.
7298 if (MaskedValueIsZero(Op0,
7299 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7300 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7301
7302 // Arithmetic shifting an all-sign-bit value is a no-op.
7303 unsigned NumSignBits = ComputeNumSignBits(Op0);
7304 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7305 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007306
Chris Lattner348f6652007-12-06 01:59:46 +00007307 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007308}
7309
7310Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7311 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007312 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007313
7314 // shl X, 0 == X and shr X, 0 == X
7315 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007316 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7317 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007318 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007319
Reid Spencere4d87aa2006-12-23 06:05:41 +00007320 if (isa<UndefValue>(Op0)) {
7321 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007322 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007323 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007324 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007325 }
7326 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007327 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7328 return ReplaceInstUsesWith(I, Op0);
7329 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007330 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007331 }
7332
Dan Gohman9004c8a2009-05-21 02:28:33 +00007333 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007334 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007335 return &I;
7336
Chris Lattner2eefe512004-04-09 19:05:30 +00007337 // Try to fold constant and into select arguments.
7338 if (isa<Constant>(Op0))
7339 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007340 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007341 return R;
7342
Reid Spencerb83eb642006-10-20 07:07:24 +00007343 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007344 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7345 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007346 return 0;
7347}
7348
Reid Spencerb83eb642006-10-20 07:07:24 +00007349Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007350 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007351 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007352
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007353 // See if we can simplify any instructions used by the instruction whose sole
7354 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007355 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007356
Dan Gohmana119de82009-06-14 23:30:43 +00007357 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7358 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007359 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007360 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007361 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007362 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007363 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007364 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007365 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007366 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007367 }
7368
7369 // ((X*C1) << C2) == (X * (C1 << C2))
7370 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7371 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7372 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007373 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007374 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007375
7376 // Try to fold constant and into select arguments.
7377 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7378 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7379 return R;
7380 if (isa<PHINode>(Op0))
7381 if (Instruction *NV = FoldOpIntoPhi(I))
7382 return NV;
7383
Chris Lattner8999dd32007-12-22 09:07:47 +00007384 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7385 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7386 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7387 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7388 // place. Don't try to do this transformation in this case. Also, we
7389 // require that the input operand is a shift-by-constant so that we have
7390 // confidence that the shifts will get folded together. We could do this
7391 // xform in more cases, but it is unlikely to be profitable.
7392 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7393 isa<ConstantInt>(TrOp->getOperand(1))) {
7394 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007395 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007396 // (shift2 (shift1 & 0x00FF), c2)
7397 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007398
7399 // For logical shifts, the truncation has the effect of making the high
7400 // part of the register be zeros. Emulate this by inserting an AND to
7401 // clear the top bits as needed. This 'and' will usually be zapped by
7402 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007403 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7404 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007405 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7406
7407 // The mask we constructed says what the trunc would do if occurring
7408 // between the shifts. We want to know the effect *after* the second
7409 // shift. We know that it is a logical shift by a constant, so adjust the
7410 // mask as appropriate.
7411 if (I.getOpcode() == Instruction::Shl)
7412 MaskV <<= Op1->getZExtValue();
7413 else {
7414 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7415 MaskV = MaskV.lshr(Op1->getZExtValue());
7416 }
7417
Chris Lattner74381062009-08-30 07:44:24 +00007418 // shift1 & 0x00FF
7419 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7420 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007421
7422 // Return the value truncated to the interesting size.
7423 return new TruncInst(And, I.getType());
7424 }
7425 }
7426
Chris Lattner4d5542c2006-01-06 07:12:35 +00007427 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007428 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7429 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7430 Value *V1, *V2;
7431 ConstantInt *CC;
7432 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007433 default: break;
7434 case Instruction::Add:
7435 case Instruction::And:
7436 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007437 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007438 // These operators commute.
7439 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007440 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007441 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007442 m_Specific(Op1)))) {
7443 Value *YS = // (Y << C)
7444 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7445 // (X + (Y << C))
7446 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7447 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007448 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007449 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007450 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007451 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007452
Chris Lattner150f12a2005-09-18 06:30:59 +00007453 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007454 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007455 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007456 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007457 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007458 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007459 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007460 Value *YS = // (Y << C)
7461 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7462 Op0BO->getName());
7463 // X & (CC << C)
7464 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7465 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007466 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007467 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007468 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007469
Reid Spencera07cb7d2007-02-02 14:41:37 +00007470 // FALL THROUGH.
7471 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007472 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007473 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007474 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007475 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007476 Value *YS = // (Y << C)
7477 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7478 // (X + (Y << C))
7479 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7480 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007481 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007482 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007483 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007484 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007485
Chris Lattner13d4ab42006-05-31 21:14:00 +00007486 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007487 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7488 match(Op0BO->getOperand(0),
7489 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007490 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007491 cast<BinaryOperator>(Op0BO->getOperand(0))
7492 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007493 Value *YS = // (Y << C)
7494 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7495 // X & (CC << C)
7496 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7497 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007498
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007499 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007500 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007501
Chris Lattner11021cb2005-09-18 05:12:10 +00007502 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007503 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007504 }
7505
7506
7507 // If the operand is an bitwise operator with a constant RHS, and the
7508 // shift is the only use, we can pull it out of the shift.
7509 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7510 bool isValid = true; // Valid only for And, Or, Xor
7511 bool highBitSet = false; // Transform if high bit of constant set?
7512
7513 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007514 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007515 case Instruction::Add:
7516 isValid = isLeftShift;
7517 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007518 case Instruction::Or:
7519 case Instruction::Xor:
7520 highBitSet = false;
7521 break;
7522 case Instruction::And:
7523 highBitSet = true;
7524 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007525 }
7526
7527 // If this is a signed shift right, and the high bit is modified
7528 // by the logical operation, do not perform the transformation.
7529 // The highBitSet boolean indicates the value of the high bit of
7530 // the constant which would cause it to be modified for this
7531 // operation.
7532 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007533 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007534 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007535
7536 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007537 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007538
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007539 Value *NewShift =
7540 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007541 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007542
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007543 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007544 NewRHS);
7545 }
7546 }
7547 }
7548 }
7549
Chris Lattnerad0124c2006-01-06 07:52:12 +00007550 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007551 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7552 if (ShiftOp && !ShiftOp->isShift())
7553 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007554
Reid Spencerb83eb642006-10-20 07:07:24 +00007555 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007556 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007557 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7558 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007559 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7560 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7561 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007562
Zhou Sheng4351c642007-04-02 08:20:41 +00007563 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007564
7565 const IntegerType *Ty = cast<IntegerType>(I.getType());
7566
7567 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007568 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007569 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7570 // saturates.
7571 if (AmtSum >= TypeBits) {
7572 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007573 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007574 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7575 }
7576
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007577 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007578 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007579 }
7580
7581 if (ShiftOp->getOpcode() == Instruction::LShr &&
7582 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007583 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007584 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007585
Chris Lattnerb87056f2007-02-05 00:57:54 +00007586 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007587 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007588 }
7589
7590 if (ShiftOp->getOpcode() == Instruction::AShr &&
7591 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007592 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007593 if (AmtSum >= TypeBits)
7594 AmtSum = TypeBits-1;
7595
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007596 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007597
Zhou Shenge9e03f62007-03-28 15:02:20 +00007598 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007599 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007600 }
7601
Chris Lattnerb87056f2007-02-05 00:57:54 +00007602 // Okay, if we get here, one shift must be left, and the other shift must be
7603 // right. See if the amounts are equal.
7604 if (ShiftAmt1 == ShiftAmt2) {
7605 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7606 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007607 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007608 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007609 }
7610 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7611 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007612 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007613 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007614 }
7615 // We can simplify ((X << C) >>s C) into a trunc + sext.
7616 // NOTE: we could do this for any C, but that would make 'unusual' integer
7617 // types. For now, just stick to ones well-supported by the code
7618 // generators.
7619 const Type *SExtType = 0;
7620 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007621 case 1 :
7622 case 8 :
7623 case 16 :
7624 case 32 :
7625 case 64 :
7626 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007627 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007628 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007629 default: break;
7630 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007631 if (SExtType)
7632 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007633 // Otherwise, we can't handle it yet.
7634 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007635 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007636
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007637 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007638 if (I.getOpcode() == Instruction::Shl) {
7639 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7640 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007641 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007642
Reid Spencer55702aa2007-03-25 21:11:44 +00007643 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007644 return BinaryOperator::CreateAnd(Shift,
7645 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007646 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007647
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007648 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007649 if (I.getOpcode() == Instruction::LShr) {
7650 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007651 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007652
Reid Spencerd5e30f02007-03-26 17:18:58 +00007653 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007654 return BinaryOperator::CreateAnd(Shift,
7655 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007656 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007657
7658 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7659 } else {
7660 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007661 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007662
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007663 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007664 if (I.getOpcode() == Instruction::Shl) {
7665 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7666 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007667 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7668 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007669
Reid Spencer55702aa2007-03-25 21:11:44 +00007670 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007671 return BinaryOperator::CreateAnd(Shift,
7672 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007673 }
7674
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007675 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007676 if (I.getOpcode() == Instruction::LShr) {
7677 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007678 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007679
Reid Spencer68d27cf2007-03-26 23:45:51 +00007680 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007681 return BinaryOperator::CreateAnd(Shift,
7682 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007683 }
7684
7685 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007686 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007687 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007688 return 0;
7689}
7690
Chris Lattnera1be5662002-05-02 17:06:02 +00007691
Chris Lattnercfd65102005-10-29 04:36:15 +00007692/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7693/// expression. If so, decompose it, returning some value X, such that Val is
7694/// X*Scale+Offset.
7695///
7696static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007697 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007698 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7699 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007700 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007701 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007702 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007703 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007704 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7705 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7706 if (I->getOpcode() == Instruction::Shl) {
7707 // This is a value scaled by '1 << the shift amt'.
7708 Scale = 1U << RHS->getZExtValue();
7709 Offset = 0;
7710 return I->getOperand(0);
7711 } else if (I->getOpcode() == Instruction::Mul) {
7712 // This value is scaled by 'RHS'.
7713 Scale = RHS->getZExtValue();
7714 Offset = 0;
7715 return I->getOperand(0);
7716 } else if (I->getOpcode() == Instruction::Add) {
7717 // We have X+C. Check to see if we really have (X*C2)+C1,
7718 // where C1 is divisible by C2.
7719 unsigned SubScale;
7720 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007721 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7722 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007723 Offset += RHS->getZExtValue();
7724 Scale = SubScale;
7725 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007726 }
7727 }
7728 }
7729
7730 // Otherwise, we can't look past this.
7731 Scale = 1;
7732 Offset = 0;
7733 return Val;
7734}
7735
7736
Chris Lattnerb3f83972005-10-24 06:03:58 +00007737/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7738/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007739Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007740 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007741 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007742
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007743 BuilderTy AllocaBuilder(*Builder);
7744 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7745
Chris Lattnerb53c2382005-10-24 06:22:12 +00007746 // Remove any uses of AI that are dead.
7747 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007748
Chris Lattnerb53c2382005-10-24 06:22:12 +00007749 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7750 Instruction *User = cast<Instruction>(*UI++);
7751 if (isInstructionTriviallyDead(User)) {
7752 while (UI != E && *UI == User)
7753 ++UI; // If this instruction uses AI more than once, don't break UI.
7754
Chris Lattnerb53c2382005-10-24 06:22:12 +00007755 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007756 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007757 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007758 }
7759 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007760
7761 // This requires TargetData to get the alloca alignment and size information.
7762 if (!TD) return 0;
7763
Chris Lattnerb3f83972005-10-24 06:03:58 +00007764 // Get the type really allocated and the type casted to.
7765 const Type *AllocElTy = AI.getAllocatedType();
7766 const Type *CastElTy = PTy->getElementType();
7767 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007768
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007769 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7770 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007771 if (CastElTyAlign < AllocElTyAlign) return 0;
7772
Chris Lattner39387a52005-10-24 06:35:18 +00007773 // If the allocation has multiple uses, only promote it if we are strictly
7774 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007775 // same, we open the door to infinite loops of various kinds. (A reference
7776 // from a dbg.declare doesn't count as a use for this purpose.)
7777 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7778 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007779
Duncan Sands777d2302009-05-09 07:06:46 +00007780 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7781 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007782 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007783
Chris Lattner455fcc82005-10-29 03:19:53 +00007784 // See if we can satisfy the modulus by pulling a scale out of the array
7785 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007786 unsigned ArraySizeScale;
7787 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007788 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007789 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7790 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007791
Chris Lattner455fcc82005-10-29 03:19:53 +00007792 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7793 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007794 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7795 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007796
Chris Lattner455fcc82005-10-29 03:19:53 +00007797 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7798 Value *Amt = 0;
7799 if (Scale == 1) {
7800 Amt = NumElements;
7801 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007802 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007803 // Insert before the alloca, not before the cast.
7804 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007805 }
7806
Jeff Cohen86796be2007-04-04 16:58:57 +00007807 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007808 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007809 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007810 }
7811
Chris Lattnerb3f83972005-10-24 06:03:58 +00007812 AllocationInst *New;
7813 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007814 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Chris Lattnerb3f83972005-10-24 06:03:58 +00007815 else
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007816 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7817 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007818 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007819
Dale Johannesena0a66372009-03-05 00:39:02 +00007820 // If the allocation has one real use plus a dbg.declare, just remove the
7821 // declare.
7822 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7823 EraseInstFromFunction(*DI);
7824 }
7825 // If the allocation has multiple real uses, insert a cast and change all
7826 // things that used it to use the new cast. This will also hack on CI, but it
7827 // will die soon.
7828 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007829 // New is the allocation instruction, pointer typed. AI is the original
7830 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007831 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007832 AI.replaceAllUsesWith(NewCast);
7833 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007834 return ReplaceInstUsesWith(CI, New);
7835}
7836
Chris Lattner70074e02006-05-13 02:06:03 +00007837/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007838/// and return it as type Ty without inserting any new casts and without
7839/// changing the computed value. This is used by code that tries to decide
7840/// whether promoting or shrinking integer operations to wider or smaller types
7841/// will allow us to eliminate a truncate or extend.
7842///
7843/// This is a truncation operation if Ty is smaller than V->getType(), or an
7844/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007845///
7846/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7847/// should return true if trunc(V) can be computed by computing V in the smaller
7848/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7849/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7850/// efficiently truncated.
7851///
7852/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7853/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7854/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007855bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007856 unsigned CastOpc,
7857 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007858 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007859 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007860 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007861
7862 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007863 if (!I) return false;
7864
Dan Gohman6de29f82009-06-15 22:12:54 +00007865 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007866
Chris Lattner951626b2007-08-02 06:11:14 +00007867 // If this is an extension or truncate, we can often eliminate it.
7868 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7869 // If this is a cast from the destination type, we can trivially eliminate
7870 // it, and this will remove a cast overall.
7871 if (I->getOperand(0)->getType() == Ty) {
7872 // If the first operand is itself a cast, and is eliminable, do not count
7873 // this as an eliminable cast. We would prefer to eliminate those two
7874 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007875 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007876 ++NumCastsRemoved;
7877 return true;
7878 }
7879 }
7880
7881 // We can't extend or shrink something that has multiple uses: doing so would
7882 // require duplicating the instruction in general, which isn't profitable.
7883 if (!I->hasOneUse()) return false;
7884
Evan Chengf35fd542009-01-15 17:01:23 +00007885 unsigned Opc = I->getOpcode();
7886 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007887 case Instruction::Add:
7888 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007889 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007890 case Instruction::And:
7891 case Instruction::Or:
7892 case Instruction::Xor:
7893 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007894 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007895 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007896 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007897 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007898
Eli Friedman070a9812009-07-13 22:46:01 +00007899 case Instruction::UDiv:
7900 case Instruction::URem: {
7901 // UDiv and URem can be truncated if all the truncated bits are zero.
7902 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7903 uint32_t BitWidth = Ty->getScalarSizeInBits();
7904 if (BitWidth < OrigBitWidth) {
7905 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7906 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7907 MaskedValueIsZero(I->getOperand(1), Mask)) {
7908 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7909 NumCastsRemoved) &&
7910 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7911 NumCastsRemoved);
7912 }
7913 }
7914 break;
7915 }
Chris Lattner46b96052006-11-29 07:18:39 +00007916 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007917 // If we are truncating the result of this SHL, and if it's a shift of a
7918 // constant amount, we can always perform a SHL in a smaller type.
7919 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007920 uint32_t BitWidth = Ty->getScalarSizeInBits();
7921 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007922 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007923 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007924 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007925 }
7926 break;
7927 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007928 // If this is a truncate of a logical shr, we can truncate it to a smaller
7929 // lshr iff we know that the bits we would otherwise be shifting in are
7930 // already zeros.
7931 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007932 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7933 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007934 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007935 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007936 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7937 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007938 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007939 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007940 }
7941 }
Chris Lattner46b96052006-11-29 07:18:39 +00007942 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007943 case Instruction::ZExt:
7944 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007945 case Instruction::Trunc:
7946 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007947 // can safely replace it. Note that replacing it does not reduce the number
7948 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007949 if (Opc == CastOpc)
7950 return true;
7951
7952 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007953 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007954 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007955 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007956 case Instruction::Select: {
7957 SelectInst *SI = cast<SelectInst>(I);
7958 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007959 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007960 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007961 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007962 }
Chris Lattner8114b712008-06-18 04:00:49 +00007963 case Instruction::PHI: {
7964 // We can change a phi if we can change all operands.
7965 PHINode *PN = cast<PHINode>(I);
7966 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7967 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007968 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007969 return false;
7970 return true;
7971 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007972 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007973 // TODO: Can handle more cases here.
7974 break;
7975 }
7976
7977 return false;
7978}
7979
7980/// EvaluateInDifferentType - Given an expression that
7981/// CanEvaluateInDifferentType returns true for, actually insert the code to
7982/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007983Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007984 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007985 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007986 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007987 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007988
7989 // Otherwise, it must be an instruction.
7990 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007991 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007992 unsigned Opc = I->getOpcode();
7993 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007994 case Instruction::Add:
7995 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007996 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007997 case Instruction::And:
7998 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007999 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008000 case Instruction::AShr:
8001 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008002 case Instruction::Shl:
8003 case Instruction::UDiv:
8004 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008005 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008006 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008007 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008008 break;
8009 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008010 case Instruction::Trunc:
8011 case Instruction::ZExt:
8012 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008013 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008014 // just return the source. There's no need to insert it because it is not
8015 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008016 if (I->getOperand(0)->getType() == Ty)
8017 return I->getOperand(0);
8018
Chris Lattner8114b712008-06-18 04:00:49 +00008019 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008020 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008021 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008022 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008023 case Instruction::Select: {
8024 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8025 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8026 Res = SelectInst::Create(I->getOperand(0), True, False);
8027 break;
8028 }
Chris Lattner8114b712008-06-18 04:00:49 +00008029 case Instruction::PHI: {
8030 PHINode *OPN = cast<PHINode>(I);
8031 PHINode *NPN = PHINode::Create(Ty);
8032 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8033 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8034 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8035 }
8036 Res = NPN;
8037 break;
8038 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008039 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008040 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008041 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008042 break;
8043 }
8044
Chris Lattner8114b712008-06-18 04:00:49 +00008045 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008046 return InsertNewInstBefore(Res, *I);
8047}
8048
Reid Spencer3da59db2006-11-27 01:05:10 +00008049/// @brief Implement the transforms common to all CastInst visitors.
8050Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008051 Value *Src = CI.getOperand(0);
8052
Dan Gohman23d9d272007-05-11 21:10:54 +00008053 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008054 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008055 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008056 if (Instruction::CastOps opc =
8057 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8058 // The first cast (CSrc) is eliminable so we need to fix up or replace
8059 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008060 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008061 }
8062 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008063
Reid Spencer3da59db2006-11-27 01:05:10 +00008064 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008065 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8066 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8067 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008068
8069 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008070 if (isa<PHINode>(Src))
8071 if (Instruction *NV = FoldOpIntoPhi(CI))
8072 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008073
Reid Spencer3da59db2006-11-27 01:05:10 +00008074 return 0;
8075}
8076
Chris Lattner46cd5a12009-01-09 05:44:56 +00008077/// FindElementAtOffset - Given a type and a constant offset, determine whether
8078/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008079/// the specified offset. If so, fill them into NewIndices and return the
8080/// resultant element type, otherwise return null.
8081static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8082 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008083 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008084 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008085 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008086 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008087
8088 // Start with the index over the outer type. Note that the type size
8089 // might be zero (even if the offset isn't zero) if the indexed type
8090 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008091 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008092 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008093 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008094 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008095 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008096
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008097 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008098 if (Offset < 0) {
8099 --FirstIdx;
8100 Offset += TySize;
8101 assert(Offset >= 0);
8102 }
8103 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8104 }
8105
Owen Andersoneed707b2009-07-24 23:12:02 +00008106 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008107
8108 // Index into the types. If we fail, set OrigBase to null.
8109 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008110 // Indexing into tail padding between struct/array elements.
8111 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008112 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008113
Chris Lattner46cd5a12009-01-09 05:44:56 +00008114 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8115 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008116 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8117 "Offset must stay within the indexed type");
8118
Chris Lattner46cd5a12009-01-09 05:44:56 +00008119 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008120 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008121
8122 Offset -= SL->getElementOffset(Elt);
8123 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008124 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008125 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008126 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008127 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008128 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008129 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008130 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008131 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008132 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008133 }
8134 }
8135
Chris Lattner3914f722009-01-24 01:00:13 +00008136 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008137}
8138
Chris Lattnerd3e28342007-04-27 17:44:50 +00008139/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8140Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8141 Value *Src = CI.getOperand(0);
8142
Chris Lattnerd3e28342007-04-27 17:44:50 +00008143 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008144 // If casting the result of a getelementptr instruction with no offset, turn
8145 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008146 if (GEP->hasAllZeroIndices()) {
8147 // Changing the cast operand is usually not a good idea but it is safe
8148 // here because the pointer operand is being replaced with another
8149 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008150 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008151 CI.setOperand(0, GEP->getOperand(0));
8152 return &CI;
8153 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008154
8155 // If the GEP has a single use, and the base pointer is a bitcast, and the
8156 // GEP computes a constant offset, see if we can convert these three
8157 // instructions into fewer. This typically happens with unions and other
8158 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008159 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008160 if (GEP->hasAllConstantIndices()) {
8161 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008162 ConstantInt *OffsetV =
8163 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008164 int64_t Offset = OffsetV->getSExtValue();
8165
8166 // Get the base pointer input of the bitcast, and the type it points to.
8167 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8168 const Type *GEPIdxTy =
8169 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008170 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008171 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008172 // If we were able to index down into an element, create the GEP
8173 // and bitcast the result. This eliminates one bitcast, potentially
8174 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008175 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8176 Builder->CreateInBoundsGEP(OrigBase,
8177 NewIndices.begin(), NewIndices.end()) :
8178 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008179 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008180
Chris Lattner46cd5a12009-01-09 05:44:56 +00008181 if (isa<BitCastInst>(CI))
8182 return new BitCastInst(NGEP, CI.getType());
8183 assert(isa<PtrToIntInst>(CI));
8184 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008185 }
8186 }
8187 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008188 }
8189
8190 return commonCastTransforms(CI);
8191}
8192
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008193/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8194/// type like i42. We don't want to introduce operations on random non-legal
8195/// integer types where they don't already exist in the code. In the future,
8196/// we should consider making this based off target-data, so that 32-bit targets
8197/// won't get i64 operations etc.
8198static bool isSafeIntegerType(const Type *Ty) {
8199 switch (Ty->getPrimitiveSizeInBits()) {
8200 case 8:
8201 case 16:
8202 case 32:
8203 case 64:
8204 return true;
8205 default:
8206 return false;
8207 }
8208}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008209
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008210/// commonIntCastTransforms - This function implements the common transforms
8211/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008212Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8213 if (Instruction *Result = commonCastTransforms(CI))
8214 return Result;
8215
8216 Value *Src = CI.getOperand(0);
8217 const Type *SrcTy = Src->getType();
8218 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008219 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8220 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008221
Reid Spencer3da59db2006-11-27 01:05:10 +00008222 // See if we can simplify any instructions used by the LHS whose sole
8223 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008224 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008225 return &CI;
8226
8227 // If the source isn't an instruction or has more than one use then we
8228 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008229 Instruction *SrcI = dyn_cast<Instruction>(Src);
8230 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008231 return 0;
8232
Chris Lattnerc739cd62007-03-03 05:27:34 +00008233 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008234 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008235 // Only do this if the dest type is a simple type, don't convert the
8236 // expression tree to something weird like i93 unless the source is also
8237 // strange.
8238 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008239 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8240 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008241 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008242 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008243 // eliminates the cast, so it is always a win. If this is a zero-extension,
8244 // we need to do an AND to maintain the clear top-part of the computation,
8245 // so we require that the input have eliminated at least one cast. If this
8246 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008247 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008248 bool DoXForm = false;
8249 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008250 switch (CI.getOpcode()) {
8251 default:
8252 // All the others use floating point so we shouldn't actually
8253 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008254 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008255 case Instruction::Trunc:
8256 DoXForm = true;
8257 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008258 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008259 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008260 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008261 // If it's unnecessary to issue an AND to clear the high bits, it's
8262 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008263 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008264 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8265 if (MaskedValueIsZero(TryRes, Mask))
8266 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008267
8268 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008269 if (TryI->use_empty())
8270 EraseInstFromFunction(*TryI);
8271 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008272 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008273 }
Evan Chengf35fd542009-01-15 17:01:23 +00008274 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008275 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008276 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008277 // If we do not have to emit the truncate + sext pair, then it's always
8278 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008279 //
8280 // It's not safe to eliminate the trunc + sext pair if one of the
8281 // eliminated cast is a truncate. e.g.
8282 // t2 = trunc i32 t1 to i16
8283 // t3 = sext i16 t2 to i32
8284 // !=
8285 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008286 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008287 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8288 if (NumSignBits > (DestBitSize - SrcBitSize))
8289 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008290
8291 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008292 if (TryI->use_empty())
8293 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008294 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008295 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008296 }
Evan Chengf35fd542009-01-15 17:01:23 +00008297 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008298
8299 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008300 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8301 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008302 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8303 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008304 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008305 // Just replace this cast with the result.
8306 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008307
Reid Spencer3da59db2006-11-27 01:05:10 +00008308 assert(Res->getType() == DestTy);
8309 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008310 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008311 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008312 // Just replace this cast with the result.
8313 return ReplaceInstUsesWith(CI, Res);
8314 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008315 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008316
8317 // If the high bits are already zero, just replace this cast with the
8318 // result.
8319 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8320 if (MaskedValueIsZero(Res, Mask))
8321 return ReplaceInstUsesWith(CI, Res);
8322
8323 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008324 Constant *C = ConstantInt::get(*Context,
8325 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008326 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008327 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008328 case Instruction::SExt: {
8329 // If the high bits are already filled with sign bit, just replace this
8330 // cast with the result.
8331 unsigned NumSignBits = ComputeNumSignBits(Res);
8332 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008333 return ReplaceInstUsesWith(CI, Res);
8334
Reid Spencer3da59db2006-11-27 01:05:10 +00008335 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008336 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008337 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008338 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008339 }
8340 }
8341
8342 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8343 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8344
8345 switch (SrcI->getOpcode()) {
8346 case Instruction::Add:
8347 case Instruction::Mul:
8348 case Instruction::And:
8349 case Instruction::Or:
8350 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008351 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008352 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8353 // Don't insert two casts unless at least one can be eliminated.
8354 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008355 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008356 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8357 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008358 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008359 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008360 }
8361 }
8362
8363 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8364 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8365 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008366 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008367 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008368 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008369 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008370 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008371 }
8372 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008373
Eli Friedman65445c52009-07-13 21:45:57 +00008374 case Instruction::Shl: {
8375 // Canonicalize trunc inside shl, if we can.
8376 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8377 if (CI && DestBitSize < SrcBitSize &&
8378 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008379 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8380 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008381 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008382 }
8383 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008384 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008385 }
8386 return 0;
8387}
8388
Chris Lattner8a9f5712007-04-11 06:57:46 +00008389Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008390 if (Instruction *Result = commonIntCastTransforms(CI))
8391 return Result;
8392
8393 Value *Src = CI.getOperand(0);
8394 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008395 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8396 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008397
8398 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008399 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008400 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008401 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008402 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008403 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008404 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008405
Chris Lattner4f9797d2009-03-24 18:15:30 +00008406 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8407 ConstantInt *ShAmtV = 0;
8408 Value *ShiftOp = 0;
8409 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008410 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008411 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8412
8413 // Get a mask for the bits shifting in.
8414 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8415 if (MaskedValueIsZero(ShiftOp, Mask)) {
8416 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008417 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008418
8419 // Okay, we can shrink this. Truncate the input, then return a new
8420 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008421 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008422 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008423 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008424 }
8425 }
8426
8427 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008428}
8429
Evan Chengb98a10e2008-03-24 00:21:34 +00008430/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8431/// in order to eliminate the icmp.
8432Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8433 bool DoXform) {
8434 // If we are just checking for a icmp eq of a single bit and zext'ing it
8435 // to an integer, then shift the bit to the appropriate place and then
8436 // cast to integer to avoid the comparison.
8437 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8438 const APInt &Op1CV = Op1C->getValue();
8439
8440 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8441 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8442 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8443 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8444 if (!DoXform) return ICI;
8445
8446 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008447 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008448 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008449 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008450 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008451 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008452
8453 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008454 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008455 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008456 }
8457
8458 return ReplaceInstUsesWith(CI, In);
8459 }
8460
8461
8462
8463 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8464 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8465 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8466 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8467 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8468 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8469 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8470 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8471 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8472 // This only works for EQ and NE
8473 ICI->isEquality()) {
8474 // If Op1C some other power of two, convert:
8475 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8476 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8477 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8478 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8479
8480 APInt KnownZeroMask(~KnownZero);
8481 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8482 if (!DoXform) return ICI;
8483
8484 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8485 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8486 // (X&4) == 2 --> false
8487 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008488 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008489 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008490 return ReplaceInstUsesWith(CI, Res);
8491 }
8492
8493 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8494 Value *In = ICI->getOperand(0);
8495 if (ShiftAmt) {
8496 // Perform a logical shr by shiftamt.
8497 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008498 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8499 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008500 }
8501
8502 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008503 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008504 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008505 }
8506
8507 if (CI.getType() == In->getType())
8508 return ReplaceInstUsesWith(CI, In);
8509 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008510 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008511 }
8512 }
8513 }
8514
8515 return 0;
8516}
8517
Chris Lattner8a9f5712007-04-11 06:57:46 +00008518Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008519 // If one of the common conversion will work ..
8520 if (Instruction *Result = commonIntCastTransforms(CI))
8521 return Result;
8522
8523 Value *Src = CI.getOperand(0);
8524
Chris Lattnera84f47c2009-02-17 20:47:23 +00008525 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8526 // types and if the sizes are just right we can convert this into a logical
8527 // 'and' which will be much cheaper than the pair of casts.
8528 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8529 // Get the sizes of the types involved. We know that the intermediate type
8530 // will be smaller than A or C, but don't know the relation between A and C.
8531 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008532 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8533 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8534 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008535 // If we're actually extending zero bits, then if
8536 // SrcSize < DstSize: zext(a & mask)
8537 // SrcSize == DstSize: a & mask
8538 // SrcSize > DstSize: trunc(a) & mask
8539 if (SrcSize < DstSize) {
8540 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008541 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008542 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008543 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008544 }
8545
8546 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008547 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008548 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008549 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008550 }
8551 if (SrcSize > DstSize) {
8552 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008553 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008554 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008555 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008556 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008557 }
8558 }
8559
Evan Chengb98a10e2008-03-24 00:21:34 +00008560 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8561 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008562
Evan Chengb98a10e2008-03-24 00:21:34 +00008563 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8564 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8565 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8566 // of the (zext icmp) will be transformed.
8567 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8568 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8569 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8570 (transformZExtICmp(LHS, CI, false) ||
8571 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008572 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8573 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008574 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008575 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008576 }
8577
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008578 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008579 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8580 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8581 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8582 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008583 if (TI0->getType() == CI.getType())
8584 return
8585 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008586 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008587 }
8588
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008589 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8590 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8591 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8592 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8593 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8594 And->getOperand(1) == C)
8595 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8596 Value *TI0 = TI->getOperand(0);
8597 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008598 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008599 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008600 return BinaryOperator::CreateXor(NewAnd, ZC);
8601 }
8602 }
8603
Reid Spencer3da59db2006-11-27 01:05:10 +00008604 return 0;
8605}
8606
Chris Lattner8a9f5712007-04-11 06:57:46 +00008607Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008608 if (Instruction *I = commonIntCastTransforms(CI))
8609 return I;
8610
Chris Lattner8a9f5712007-04-11 06:57:46 +00008611 Value *Src = CI.getOperand(0);
8612
Dan Gohman1975d032008-10-30 20:40:10 +00008613 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008614 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008615 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008616 Constant::getAllOnesValue(CI.getType()),
8617 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008618
8619 // See if the value being truncated is already sign extended. If so, just
8620 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008621 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008622 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008623 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8624 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8625 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008626 unsigned NumSignBits = ComputeNumSignBits(Op);
8627
8628 if (OpBits == DestBits) {
8629 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8630 // bits, it is already ready.
8631 if (NumSignBits > DestBits-MidBits)
8632 return ReplaceInstUsesWith(CI, Op);
8633 } else if (OpBits < DestBits) {
8634 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8635 // bits, just sext from i32.
8636 if (NumSignBits > OpBits-MidBits)
8637 return new SExtInst(Op, CI.getType(), "tmp");
8638 } else {
8639 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8640 // bits, just truncate to i32.
8641 if (NumSignBits > OpBits-MidBits)
8642 return new TruncInst(Op, CI.getType(), "tmp");
8643 }
8644 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008645
8646 // If the input is a shl/ashr pair of a same constant, then this is a sign
8647 // extension from a smaller value. If we could trust arbitrary bitwidth
8648 // integers, we could turn this into a truncate to the smaller bit and then
8649 // use a sext for the whole extension. Since we don't, look deeper and check
8650 // for a truncate. If the source and dest are the same type, eliminate the
8651 // trunc and extend and just do shifts. For example, turn:
8652 // %a = trunc i32 %i to i8
8653 // %b = shl i8 %a, 6
8654 // %c = ashr i8 %b, 6
8655 // %d = sext i8 %c to i32
8656 // into:
8657 // %a = shl i32 %i, 30
8658 // %d = ashr i32 %a, 30
8659 Value *A = 0;
8660 ConstantInt *BA = 0, *CA = 0;
8661 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008662 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008663 BA == CA && isa<TruncInst>(A)) {
8664 Value *I = cast<TruncInst>(A)->getOperand(0);
8665 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008666 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8667 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008668 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008669 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008670 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008671 return BinaryOperator::CreateAShr(I, ShAmtV);
8672 }
8673 }
8674
Chris Lattnerba417832007-04-11 06:12:58 +00008675 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008676}
8677
Chris Lattnerb7530652008-01-27 05:29:54 +00008678/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8679/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008680static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008681 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008682 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008683 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008684 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8685 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008686 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008687 return 0;
8688}
8689
8690/// LookThroughFPExtensions - If this is an fp extension instruction, look
8691/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008692static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008693 if (Instruction *I = dyn_cast<Instruction>(V))
8694 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008695 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008696
8697 // If this value is a constant, return the constant in the smallest FP type
8698 // that can accurately represent it. This allows us to turn
8699 // (float)((double)X+2.0) into x+2.0f.
8700 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008701 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008702 return V; // No constant folding of this.
8703 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008704 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008705 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008706 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008707 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008708 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008709 return V;
8710 // Don't try to shrink to various long double types.
8711 }
8712
8713 return V;
8714}
8715
8716Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8717 if (Instruction *I = commonCastTransforms(CI))
8718 return I;
8719
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008720 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008721 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008722 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008723 // many builtins (sqrt, etc).
8724 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8725 if (OpI && OpI->hasOneUse()) {
8726 switch (OpI->getOpcode()) {
8727 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008728 case Instruction::FAdd:
8729 case Instruction::FSub:
8730 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008731 case Instruction::FDiv:
8732 case Instruction::FRem:
8733 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008734 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8735 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008736 if (LHSTrunc->getType() != SrcTy &&
8737 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008738 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008739 // If the source types were both smaller than the destination type of
8740 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008741 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8742 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008743 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8744 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008745 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008746 }
8747 }
8748 break;
8749 }
8750 }
8751 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008752}
8753
8754Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8755 return commonCastTransforms(CI);
8756}
8757
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008758Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008759 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8760 if (OpI == 0)
8761 return commonCastTransforms(FI);
8762
8763 // fptoui(uitofp(X)) --> X
8764 // fptoui(sitofp(X)) --> X
8765 // This is safe if the intermediate type has enough bits in its mantissa to
8766 // accurately represent all values of X. For example, do not do this with
8767 // i64->float->i64. This is also safe for sitofp case, because any negative
8768 // 'X' value would cause an undefined result for the fptoui.
8769 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8770 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008771 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008772 OpI->getType()->getFPMantissaWidth())
8773 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008774
8775 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008776}
8777
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008778Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008779 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8780 if (OpI == 0)
8781 return commonCastTransforms(FI);
8782
8783 // fptosi(sitofp(X)) --> X
8784 // fptosi(uitofp(X)) --> X
8785 // This is safe if the intermediate type has enough bits in its mantissa to
8786 // accurately represent all values of X. For example, do not do this with
8787 // i64->float->i64. This is also safe for sitofp case, because any negative
8788 // 'X' value would cause an undefined result for the fptoui.
8789 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8790 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008791 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008792 OpI->getType()->getFPMantissaWidth())
8793 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008794
8795 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008796}
8797
8798Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8799 return commonCastTransforms(CI);
8800}
8801
8802Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8803 return commonCastTransforms(CI);
8804}
8805
Chris Lattnera0e69692009-03-24 18:35:40 +00008806Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8807 // If the destination integer type is smaller than the intptr_t type for
8808 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8809 // trunc to be exposed to other transforms. Don't do this for extending
8810 // ptrtoint's, because we don't know if the target sign or zero extends its
8811 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008812 if (TD &&
8813 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008814 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8815 TD->getIntPtrType(CI.getContext()),
8816 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008817 return new TruncInst(P, CI.getType());
8818 }
8819
Chris Lattnerd3e28342007-04-27 17:44:50 +00008820 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008821}
8822
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008823Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008824 // If the source integer type is larger than the intptr_t type for
8825 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8826 // allows the trunc to be exposed to other transforms. Don't do this for
8827 // extending inttoptr's, because we don't know if the target sign or zero
8828 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008829 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008830 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008831 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8832 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008833 return new IntToPtrInst(P, CI.getType());
8834 }
8835
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008836 if (Instruction *I = commonCastTransforms(CI))
8837 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008838
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008839 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008840}
8841
Chris Lattnerd3e28342007-04-27 17:44:50 +00008842Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008843 // If the operands are integer typed then apply the integer transforms,
8844 // otherwise just apply the common ones.
8845 Value *Src = CI.getOperand(0);
8846 const Type *SrcTy = Src->getType();
8847 const Type *DestTy = CI.getType();
8848
Eli Friedman7e25d452009-07-13 20:53:00 +00008849 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008850 if (Instruction *I = commonPointerCastTransforms(CI))
8851 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008852 } else {
8853 if (Instruction *Result = commonCastTransforms(CI))
8854 return Result;
8855 }
8856
8857
8858 // Get rid of casts from one type to the same type. These are useless and can
8859 // be replaced by the operand.
8860 if (DestTy == Src->getType())
8861 return ReplaceInstUsesWith(CI, Src);
8862
Reid Spencer3da59db2006-11-27 01:05:10 +00008863 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008864 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8865 const Type *DstElTy = DstPTy->getElementType();
8866 const Type *SrcElTy = SrcPTy->getElementType();
8867
Nate Begeman83ad90a2008-03-31 00:22:16 +00008868 // If the address spaces don't match, don't eliminate the bitcast, which is
8869 // required for changing types.
8870 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8871 return 0;
8872
Victor Hernandez83d63912009-09-18 22:35:49 +00008873 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008874 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008875 // There is no need to modify malloc calls because it is their bitcast that
8876 // needs to be cleaned up.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008877 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8878 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8879 return V;
8880
Chris Lattnerd717c182007-05-05 22:32:24 +00008881 // If the source and destination are pointers, and this cast is equivalent
8882 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008883 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008884 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008885 unsigned NumZeros = 0;
8886 while (SrcElTy != DstElTy &&
8887 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8888 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8889 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8890 ++NumZeros;
8891 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008892
Chris Lattnerd3e28342007-04-27 17:44:50 +00008893 // If we found a path from the src to dest, create the getelementptr now.
8894 if (SrcElTy == DstElTy) {
8895 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008896 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8897 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008898 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008899 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008900
Eli Friedman2451a642009-07-18 23:06:53 +00008901 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8902 if (DestVTy->getNumElements() == 1) {
8903 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008904 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008905 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008906 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008907 }
8908 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8909 }
8910 }
8911
8912 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8913 if (SrcVTy->getNumElements() == 1) {
8914 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008915 Value *Elem =
8916 Builder->CreateExtractElement(Src,
8917 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008918 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8919 }
8920 }
8921 }
8922
Reid Spencer3da59db2006-11-27 01:05:10 +00008923 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8924 if (SVI->hasOneUse()) {
8925 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8926 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008927 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008928 cast<VectorType>(DestTy)->getNumElements() ==
8929 SVI->getType()->getNumElements() &&
8930 SVI->getType()->getNumElements() ==
8931 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008932 CastInst *Tmp;
8933 // If either of the operands is a cast from CI.getType(), then
8934 // evaluating the shuffle in the casted destination's type will allow
8935 // us to eliminate at least one cast.
8936 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8937 Tmp->getOperand(0)->getType() == DestTy) ||
8938 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8939 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008940 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8941 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008942 // Return a new shuffle vector. Use the same element ID's, as we
8943 // know the vector types match #elts.
8944 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008945 }
8946 }
8947 }
8948 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008949 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008950}
8951
Chris Lattnere576b912004-04-09 23:46:01 +00008952/// GetSelectFoldableOperands - We want to turn code that looks like this:
8953/// %C = or %A, %B
8954/// %D = select %cond, %C, %A
8955/// into:
8956/// %C = select %cond, %B, 0
8957/// %D = or %A, %C
8958///
8959/// Assuming that the specified instruction is an operand to the select, return
8960/// a bitmask indicating which operands of this instruction are foldable if they
8961/// equal the other incoming value of the select.
8962///
8963static unsigned GetSelectFoldableOperands(Instruction *I) {
8964 switch (I->getOpcode()) {
8965 case Instruction::Add:
8966 case Instruction::Mul:
8967 case Instruction::And:
8968 case Instruction::Or:
8969 case Instruction::Xor:
8970 return 3; // Can fold through either operand.
8971 case Instruction::Sub: // Can only fold on the amount subtracted.
8972 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008973 case Instruction::LShr:
8974 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008975 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008976 default:
8977 return 0; // Cannot fold
8978 }
8979}
8980
8981/// GetSelectFoldableConstant - For the same transformation as the previous
8982/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008983static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008984 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008985 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008986 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008987 case Instruction::Add:
8988 case Instruction::Sub:
8989 case Instruction::Or:
8990 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008991 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008992 case Instruction::LShr:
8993 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008994 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008995 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008996 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008997 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00008998 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00008999 }
9000}
9001
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009002/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9003/// have the same opcode and only one use each. Try to simplify this.
9004Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9005 Instruction *FI) {
9006 if (TI->getNumOperands() == 1) {
9007 // If this is a non-volatile load or a cast from the same type,
9008 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009009 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009010 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9011 return 0;
9012 } else {
9013 return 0; // unknown unary op.
9014 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009015
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009016 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009017 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009018 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009019 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009020 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009021 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009022 }
9023
Reid Spencer832254e2007-02-02 02:16:23 +00009024 // Only handle binary operators here.
9025 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009026 return 0;
9027
9028 // Figure out if the operations have any operands in common.
9029 Value *MatchOp, *OtherOpT, *OtherOpF;
9030 bool MatchIsOpZero;
9031 if (TI->getOperand(0) == FI->getOperand(0)) {
9032 MatchOp = TI->getOperand(0);
9033 OtherOpT = TI->getOperand(1);
9034 OtherOpF = FI->getOperand(1);
9035 MatchIsOpZero = true;
9036 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9037 MatchOp = TI->getOperand(1);
9038 OtherOpT = TI->getOperand(0);
9039 OtherOpF = FI->getOperand(0);
9040 MatchIsOpZero = false;
9041 } else if (!TI->isCommutative()) {
9042 return 0;
9043 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9044 MatchOp = TI->getOperand(0);
9045 OtherOpT = TI->getOperand(1);
9046 OtherOpF = FI->getOperand(0);
9047 MatchIsOpZero = true;
9048 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9049 MatchOp = TI->getOperand(1);
9050 OtherOpT = TI->getOperand(0);
9051 OtherOpF = FI->getOperand(1);
9052 MatchIsOpZero = true;
9053 } else {
9054 return 0;
9055 }
9056
9057 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009058 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9059 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009060 InsertNewInstBefore(NewSI, SI);
9061
9062 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9063 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009064 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009065 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009066 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009067 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009068 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009069 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009070}
9071
Evan Chengde621922009-03-31 20:42:45 +00009072static bool isSelect01(Constant *C1, Constant *C2) {
9073 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9074 if (!C1I)
9075 return false;
9076 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9077 if (!C2I)
9078 return false;
9079 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9080}
9081
9082/// FoldSelectIntoOp - Try fold the select into one of the operands to
9083/// facilitate further optimization.
9084Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9085 Value *FalseVal) {
9086 // See the comment above GetSelectFoldableOperands for a description of the
9087 // transformation we are doing here.
9088 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9089 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9090 !isa<Constant>(FalseVal)) {
9091 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9092 unsigned OpToFold = 0;
9093 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9094 OpToFold = 1;
9095 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9096 OpToFold = 2;
9097 }
9098
9099 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009100 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009101 Value *OOp = TVI->getOperand(2-OpToFold);
9102 // Avoid creating select between 2 constants unless it's selecting
9103 // between 0 and 1.
9104 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9105 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9106 InsertNewInstBefore(NewSel, SI);
9107 NewSel->takeName(TVI);
9108 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9109 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009110 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009111 }
9112 }
9113 }
9114 }
9115 }
9116
9117 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9118 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9119 !isa<Constant>(TrueVal)) {
9120 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9121 unsigned OpToFold = 0;
9122 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9123 OpToFold = 1;
9124 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9125 OpToFold = 2;
9126 }
9127
9128 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009129 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009130 Value *OOp = FVI->getOperand(2-OpToFold);
9131 // Avoid creating select between 2 constants unless it's selecting
9132 // between 0 and 1.
9133 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9134 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9135 InsertNewInstBefore(NewSel, SI);
9136 NewSel->takeName(FVI);
9137 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9138 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009139 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009140 }
9141 }
9142 }
9143 }
9144 }
9145
9146 return 0;
9147}
9148
Dan Gohman81b28ce2008-09-16 18:46:06 +00009149/// visitSelectInstWithICmp - Visit a SelectInst that has an
9150/// ICmpInst as its first operand.
9151///
9152Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9153 ICmpInst *ICI) {
9154 bool Changed = false;
9155 ICmpInst::Predicate Pred = ICI->getPredicate();
9156 Value *CmpLHS = ICI->getOperand(0);
9157 Value *CmpRHS = ICI->getOperand(1);
9158 Value *TrueVal = SI.getTrueValue();
9159 Value *FalseVal = SI.getFalseValue();
9160
9161 // Check cases where the comparison is with a constant that
9162 // can be adjusted to fit the min/max idiom. We may edit ICI in
9163 // place here, so make sure the select is the only user.
9164 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009165 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009166 switch (Pred) {
9167 default: break;
9168 case ICmpInst::ICMP_ULT:
9169 case ICmpInst::ICMP_SLT: {
9170 // X < MIN ? T : F --> F
9171 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9172 return ReplaceInstUsesWith(SI, FalseVal);
9173 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009174 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009175 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9176 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9177 Pred = ICmpInst::getSwappedPredicate(Pred);
9178 CmpRHS = AdjustedRHS;
9179 std::swap(FalseVal, TrueVal);
9180 ICI->setPredicate(Pred);
9181 ICI->setOperand(1, CmpRHS);
9182 SI.setOperand(1, TrueVal);
9183 SI.setOperand(2, FalseVal);
9184 Changed = true;
9185 }
9186 break;
9187 }
9188 case ICmpInst::ICMP_UGT:
9189 case ICmpInst::ICMP_SGT: {
9190 // X > MAX ? T : F --> F
9191 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9192 return ReplaceInstUsesWith(SI, FalseVal);
9193 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009194 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009195 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9196 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9197 Pred = ICmpInst::getSwappedPredicate(Pred);
9198 CmpRHS = AdjustedRHS;
9199 std::swap(FalseVal, TrueVal);
9200 ICI->setPredicate(Pred);
9201 ICI->setOperand(1, CmpRHS);
9202 SI.setOperand(1, TrueVal);
9203 SI.setOperand(2, FalseVal);
9204 Changed = true;
9205 }
9206 break;
9207 }
9208 }
9209
Dan Gohman1975d032008-10-30 20:40:10 +00009210 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9211 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009212 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009213 if (match(TrueVal, m_ConstantInt<-1>()) &&
9214 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009215 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009216 else if (match(TrueVal, m_ConstantInt<0>()) &&
9217 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009218 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9219
Dan Gohman1975d032008-10-30 20:40:10 +00009220 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9221 // If we are just checking for a icmp eq of a single bit and zext'ing it
9222 // to an integer, then shift the bit to the appropriate place and then
9223 // cast to integer to avoid the comparison.
9224 const APInt &Op1CV = CI->getValue();
9225
9226 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9227 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9228 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009229 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009230 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009231 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009232 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009233 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009234 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009235 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009236 if (In->getType() != SI.getType())
9237 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009238 true/*SExt*/, "tmp", ICI);
9239
9240 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009241 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009242 In->getName()+".not"), *ICI);
9243
9244 return ReplaceInstUsesWith(SI, In);
9245 }
9246 }
9247 }
9248
Dan Gohman81b28ce2008-09-16 18:46:06 +00009249 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9250 // Transform (X == Y) ? X : Y -> Y
9251 if (Pred == ICmpInst::ICMP_EQ)
9252 return ReplaceInstUsesWith(SI, FalseVal);
9253 // Transform (X != Y) ? X : Y -> X
9254 if (Pred == ICmpInst::ICMP_NE)
9255 return ReplaceInstUsesWith(SI, TrueVal);
9256 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9257
9258 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9259 // Transform (X == Y) ? Y : X -> X
9260 if (Pred == ICmpInst::ICMP_EQ)
9261 return ReplaceInstUsesWith(SI, FalseVal);
9262 // Transform (X != Y) ? Y : X -> Y
9263 if (Pred == ICmpInst::ICMP_NE)
9264 return ReplaceInstUsesWith(SI, TrueVal);
9265 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9266 }
9267
9268 /// NOTE: if we wanted to, this is where to detect integer ABS
9269
9270 return Changed ? &SI : 0;
9271}
9272
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009273/// isDefinedInBB - Return true if the value is an instruction defined in the
9274/// specified basicblock.
9275static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9276 const Instruction *I = dyn_cast<Instruction>(V);
9277 return I != 0 && I->getParent() == BB;
9278}
9279
9280
Chris Lattner3d69f462004-03-12 05:52:32 +00009281Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009282 Value *CondVal = SI.getCondition();
9283 Value *TrueVal = SI.getTrueValue();
9284 Value *FalseVal = SI.getFalseValue();
9285
9286 // select true, X, Y -> X
9287 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009288 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009289 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009290
9291 // select C, X, X -> X
9292 if (TrueVal == FalseVal)
9293 return ReplaceInstUsesWith(SI, TrueVal);
9294
Chris Lattnere87597f2004-10-16 18:11:37 +00009295 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9296 return ReplaceInstUsesWith(SI, FalseVal);
9297 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9298 return ReplaceInstUsesWith(SI, TrueVal);
9299 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9300 if (isa<Constant>(TrueVal))
9301 return ReplaceInstUsesWith(SI, TrueVal);
9302 else
9303 return ReplaceInstUsesWith(SI, FalseVal);
9304 }
9305
Owen Anderson1d0be152009-08-13 21:58:54 +00009306 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009307 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009308 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009309 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009310 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009311 } else {
9312 // Change: A = select B, false, C --> A = and !B, C
9313 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009314 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009315 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009316 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009317 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009318 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009319 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009320 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009321 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009322 } else {
9323 // Change: A = select B, C, true --> A = or !B, C
9324 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009325 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009326 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009327 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009328 }
9329 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009330
9331 // select a, b, a -> a&b
9332 // select a, a, b -> a|b
9333 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009334 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009335 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009336 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009337 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009338
Chris Lattner2eefe512004-04-09 19:05:30 +00009339 // Selecting between two integer constants?
9340 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9341 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009342 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009343 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009344 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009345 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009346 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009347 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009348 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009349 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009350 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009351 }
Chris Lattner457dd822004-06-09 07:59:58 +00009352
Reid Spencere4d87aa2006-12-23 06:05:41 +00009353 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009354 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009355 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009356 // non-constant value, eliminate this whole mess. This corresponds to
9357 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009358 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009359 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009360 cast<Constant>(IC->getOperand(1))->isNullValue())
9361 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9362 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009363 isa<ConstantInt>(ICA->getOperand(1)) &&
9364 (ICA->getOperand(1) == TrueValC ||
9365 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009366 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9367 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009368 // know whether we have a icmp_ne or icmp_eq and whether the
9369 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009370 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009371 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009372 Value *V = ICA;
9373 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009374 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009375 Instruction::Xor, V, ICA->getOperand(1)), SI);
9376 return ReplaceInstUsesWith(SI, V);
9377 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009378 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009379 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009380
9381 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009382 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9383 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009384 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009385 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9386 // This is not safe in general for floating point:
9387 // consider X== -0, Y== +0.
9388 // It becomes safe if either operand is a nonzero constant.
9389 ConstantFP *CFPt, *CFPf;
9390 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9391 !CFPt->getValueAPF().isZero()) ||
9392 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9393 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009394 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009395 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009396 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009397 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009398 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009399 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009400
Reid Spencere4d87aa2006-12-23 06:05:41 +00009401 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009402 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009403 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9404 // This is not safe in general for floating point:
9405 // consider X== -0, Y== +0.
9406 // It becomes safe if either operand is a nonzero constant.
9407 ConstantFP *CFPt, *CFPf;
9408 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9409 !CFPt->getValueAPF().isZero()) ||
9410 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9411 !CFPf->getValueAPF().isZero()))
9412 return ReplaceInstUsesWith(SI, FalseVal);
9413 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009414 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009415 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9416 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009417 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009418 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009419 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009420 }
9421
9422 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009423 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9424 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9425 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009426
Chris Lattner87875da2005-01-13 22:52:24 +00009427 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9428 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9429 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009430 Instruction *AddOp = 0, *SubOp = 0;
9431
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009432 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9433 if (TI->getOpcode() == FI->getOpcode())
9434 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9435 return IV;
9436
9437 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9438 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009439 if ((TI->getOpcode() == Instruction::Sub &&
9440 FI->getOpcode() == Instruction::Add) ||
9441 (TI->getOpcode() == Instruction::FSub &&
9442 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009443 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009444 } else if ((FI->getOpcode() == Instruction::Sub &&
9445 TI->getOpcode() == Instruction::Add) ||
9446 (FI->getOpcode() == Instruction::FSub &&
9447 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009448 AddOp = TI; SubOp = FI;
9449 }
9450
9451 if (AddOp) {
9452 Value *OtherAddOp = 0;
9453 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9454 OtherAddOp = AddOp->getOperand(1);
9455 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9456 OtherAddOp = AddOp->getOperand(0);
9457 }
9458
9459 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009460 // So at this point we know we have (Y -> OtherAddOp):
9461 // select C, (add X, Y), (sub X, Z)
9462 Value *NegVal; // Compute -Z
9463 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009464 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009465 } else {
9466 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009467 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009468 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009469 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009470
9471 Value *NewTrueOp = OtherAddOp;
9472 Value *NewFalseOp = NegVal;
9473 if (AddOp != TI)
9474 std::swap(NewTrueOp, NewFalseOp);
9475 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009476 SelectInst::Create(CondVal, NewTrueOp,
9477 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009478
9479 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009480 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009481 }
9482 }
9483 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009484
Chris Lattnere576b912004-04-09 23:46:01 +00009485 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009486 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009487 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9488 if (FoldI)
9489 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009490 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009491
Chris Lattner5d1704d2009-09-27 19:57:57 +00009492 // See if we can fold the select into a phi node. The true/false values have
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009493 // to be live in the predecessor blocks. If they are instructions in SI's
9494 // block, we can't map to the predecessor.
Chris Lattner5d1704d2009-09-27 19:57:57 +00009495 if (isa<PHINode>(SI.getCondition()) &&
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009496 (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9497 isa<PHINode>(SI.getTrueValue())) &&
9498 (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9499 isa<PHINode>(SI.getFalseValue())))
Chris Lattner5d1704d2009-09-27 19:57:57 +00009500 if (Instruction *NV = FoldOpIntoPhi(SI))
9501 return NV;
9502
Chris Lattnera1df33c2005-04-24 07:30:14 +00009503 if (BinaryOperator::isNot(CondVal)) {
9504 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9505 SI.setOperand(1, FalseVal);
9506 SI.setOperand(2, TrueVal);
9507 return &SI;
9508 }
9509
Chris Lattner3d69f462004-03-12 05:52:32 +00009510 return 0;
9511}
9512
Dan Gohmaneee962e2008-04-10 18:43:06 +00009513/// EnforceKnownAlignment - If the specified pointer points to an object that
9514/// we control, modify the object's alignment to PrefAlign. This isn't
9515/// often possible though. If alignment is important, a more reliable approach
9516/// is to simply align all global variables and allocation instructions to
9517/// their preferred alignment from the beginning.
9518///
9519static unsigned EnforceKnownAlignment(Value *V,
9520 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009521
Dan Gohmaneee962e2008-04-10 18:43:06 +00009522 User *U = dyn_cast<User>(V);
9523 if (!U) return Align;
9524
Dan Gohmanca178902009-07-17 20:47:02 +00009525 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009526 default: break;
9527 case Instruction::BitCast:
9528 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9529 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009530 // If all indexes are zero, it is just the alignment of the base pointer.
9531 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009532 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009533 if (!isa<Constant>(*i) ||
9534 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009535 AllZeroOperands = false;
9536 break;
9537 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009538
9539 if (AllZeroOperands) {
9540 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009541 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009542 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009543 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009544 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009545 }
9546
9547 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9548 // If there is a large requested alignment and we can, bump up the alignment
9549 // of the global.
9550 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009551 if (GV->getAlignment() >= PrefAlign)
9552 Align = GV->getAlignment();
9553 else {
9554 GV->setAlignment(PrefAlign);
9555 Align = PrefAlign;
9556 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009557 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009558 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9559 // If there is a requested alignment and if this is an alloca, round up.
9560 if (AI->getAlignment() >= PrefAlign)
9561 Align = AI->getAlignment();
9562 else {
9563 AI->setAlignment(PrefAlign);
9564 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009565 }
9566 }
9567
9568 return Align;
9569}
9570
9571/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9572/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9573/// and it is more than the alignment of the ultimate object, see if we can
9574/// increase the alignment of the ultimate object, making this check succeed.
9575unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9576 unsigned PrefAlign) {
9577 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9578 sizeof(PrefAlign) * CHAR_BIT;
9579 APInt Mask = APInt::getAllOnesValue(BitWidth);
9580 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9581 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9582 unsigned TrailZ = KnownZero.countTrailingOnes();
9583 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9584
9585 if (PrefAlign > Align)
9586 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9587
9588 // We don't need to make any adjustment.
9589 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009590}
9591
Chris Lattnerf497b022008-01-13 23:50:23 +00009592Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009593 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009594 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009595 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009596 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009597
9598 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009599 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009600 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009601 return MI;
9602 }
9603
9604 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9605 // load/store.
9606 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9607 if (MemOpLength == 0) return 0;
9608
Chris Lattner37ac6082008-01-14 00:28:35 +00009609 // Source and destination pointer types are always "i8*" for intrinsic. See
9610 // if the size is something we can handle with a single primitive load/store.
9611 // A single load+store correctly handles overlapping memory in the memmove
9612 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009613 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009614 if (Size == 0) return MI; // Delete this mem transfer.
9615
9616 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009617 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009618
Chris Lattner37ac6082008-01-14 00:28:35 +00009619 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009620 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009621 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009622
9623 // Memcpy forces the use of i8* for the source and destination. That means
9624 // that if you're using memcpy to move one double around, you'll get a cast
9625 // from double* to i8*. We'd much rather use a double load+store rather than
9626 // an i64 load+store, here because this improves the odds that the source or
9627 // dest address will be promotable. See if we can find a better type than the
9628 // integer datatype.
9629 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9630 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009631 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009632 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9633 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009634 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009635 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9636 if (STy->getNumElements() == 1)
9637 SrcETy = STy->getElementType(0);
9638 else
9639 break;
9640 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9641 if (ATy->getNumElements() == 1)
9642 SrcETy = ATy->getElementType();
9643 else
9644 break;
9645 } else
9646 break;
9647 }
9648
Dan Gohman8f8e2692008-05-23 01:52:21 +00009649 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009650 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009651 }
9652 }
9653
9654
Chris Lattnerf497b022008-01-13 23:50:23 +00009655 // If the memcpy/memmove provides better alignment info than we can
9656 // infer, use it.
9657 SrcAlign = std::max(SrcAlign, CopyAlign);
9658 DstAlign = std::max(DstAlign, CopyAlign);
9659
Chris Lattner08142f22009-08-30 19:47:22 +00009660 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9661 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009662 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9663 InsertNewInstBefore(L, *MI);
9664 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9665
9666 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009667 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009668 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009669}
Chris Lattner3d69f462004-03-12 05:52:32 +00009670
Chris Lattner69ea9d22008-04-30 06:39:11 +00009671Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9672 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009673 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009674 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009675 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009676 return MI;
9677 }
9678
9679 // Extract the length and alignment and fill if they are constant.
9680 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9681 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009682 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009683 return 0;
9684 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009685 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009686
9687 // If the length is zero, this is a no-op
9688 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9689
9690 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9691 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009692 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009693
9694 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009695 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009696
9697 // Alignment 0 is identity for alignment 1 for memset, but not store.
9698 if (Alignment == 0) Alignment = 1;
9699
9700 // Extract the fill value and store.
9701 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009702 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009703 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009704
9705 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009706 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009707 return MI;
9708 }
9709
9710 return 0;
9711}
9712
9713
Chris Lattner8b0ea312006-01-13 20:11:04 +00009714/// visitCallInst - CallInst simplification. This mostly only handles folding
9715/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9716/// the heavy lifting.
9717///
Chris Lattner9fe38862003-06-19 17:00:31 +00009718Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009719 // If the caller function is nounwind, mark the call as nounwind, even if the
9720 // callee isn't.
9721 if (CI.getParent()->getParent()->doesNotThrow() &&
9722 !CI.doesNotThrow()) {
9723 CI.setDoesNotThrow();
9724 return &CI;
9725 }
9726
Chris Lattner8b0ea312006-01-13 20:11:04 +00009727 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9728 if (!II) return visitCallSite(&CI);
9729
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009730 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9731 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009732 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009733 bool Changed = false;
9734
9735 // memmove/cpy/set of zero bytes is a noop.
9736 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9737 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9738
Chris Lattner35b9e482004-10-12 04:52:52 +00009739 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009740 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009741 // Replace the instruction with just byte operations. We would
9742 // transform other cases to loads/stores, but we don't know if
9743 // alignment is sufficient.
9744 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009745 }
9746
Chris Lattner35b9e482004-10-12 04:52:52 +00009747 // If we have a memmove and the source operation is a constant global,
9748 // then the source and dest pointers can't alias, so we can change this
9749 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009750 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009751 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9752 if (GVSrc->isConstant()) {
9753 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009754 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9755 const Type *Tys[1];
9756 Tys[0] = CI.getOperand(3)->getType();
9757 CI.setOperand(0,
9758 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009759 Changed = true;
9760 }
Chris Lattnera935db82008-05-28 05:30:41 +00009761
9762 // memmove(x,x,size) -> noop.
9763 if (MMI->getSource() == MMI->getDest())
9764 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009765 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009766
Chris Lattner95a959d2006-03-06 20:18:44 +00009767 // If we can determine a pointer alignment that is bigger than currently
9768 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009769 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009770 if (Instruction *I = SimplifyMemTransfer(MI))
9771 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009772 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9773 if (Instruction *I = SimplifyMemSet(MSI))
9774 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009775 }
9776
Chris Lattner8b0ea312006-01-13 20:11:04 +00009777 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009778 }
9779
9780 switch (II->getIntrinsicID()) {
9781 default: break;
9782 case Intrinsic::bswap:
9783 // bswap(bswap(x)) -> x
9784 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9785 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9786 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9787 break;
9788 case Intrinsic::ppc_altivec_lvx:
9789 case Intrinsic::ppc_altivec_lvxl:
9790 case Intrinsic::x86_sse_loadu_ps:
9791 case Intrinsic::x86_sse2_loadu_pd:
9792 case Intrinsic::x86_sse2_loadu_dq:
9793 // Turn PPC lvx -> load if the pointer is known aligned.
9794 // Turn X86 loadups -> load if the pointer is known aligned.
9795 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009796 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9797 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009798 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009799 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009800 break;
9801 case Intrinsic::ppc_altivec_stvx:
9802 case Intrinsic::ppc_altivec_stvxl:
9803 // Turn stvx -> store if the pointer is known aligned.
9804 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9805 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009806 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009807 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009808 return new StoreInst(II->getOperand(1), Ptr);
9809 }
9810 break;
9811 case Intrinsic::x86_sse_storeu_ps:
9812 case Intrinsic::x86_sse2_storeu_pd:
9813 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009814 // Turn X86 storeu -> store if the pointer is known aligned.
9815 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9816 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009817 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009818 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009819 return new StoreInst(II->getOperand(2), Ptr);
9820 }
9821 break;
9822
9823 case Intrinsic::x86_sse_cvttss2si: {
9824 // These intrinsics only demands the 0th element of its input vector. If
9825 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009826 unsigned VWidth =
9827 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9828 APInt DemandedElts(VWidth, 1);
9829 APInt UndefElts(VWidth, 0);
9830 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009831 UndefElts)) {
9832 II->setOperand(1, V);
9833 return II;
9834 }
9835 break;
9836 }
9837
9838 case Intrinsic::ppc_altivec_vperm:
9839 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9840 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9841 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009842
Chris Lattner0521e3c2008-06-18 04:33:20 +00009843 // Check that all of the elements are integer constants or undefs.
9844 bool AllEltsOk = true;
9845 for (unsigned i = 0; i != 16; ++i) {
9846 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9847 !isa<UndefValue>(Mask->getOperand(i))) {
9848 AllEltsOk = false;
9849 break;
9850 }
9851 }
9852
9853 if (AllEltsOk) {
9854 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009855 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9856 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009857 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009858
Chris Lattner0521e3c2008-06-18 04:33:20 +00009859 // Only extract each element once.
9860 Value *ExtractedElts[32];
9861 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9862
Chris Lattnere2ed0572006-04-06 19:19:17 +00009863 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009864 if (isa<UndefValue>(Mask->getOperand(i)))
9865 continue;
9866 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9867 Idx &= 31; // Match the hardware behavior.
9868
9869 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009870 ExtractedElts[Idx] =
9871 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9872 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9873 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009874 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009875
Chris Lattner0521e3c2008-06-18 04:33:20 +00009876 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009877 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9878 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9879 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009880 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009881 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009882 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009883 }
9884 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009885
Chris Lattner0521e3c2008-06-18 04:33:20 +00009886 case Intrinsic::stackrestore: {
9887 // If the save is right next to the restore, remove the restore. This can
9888 // happen when variable allocas are DCE'd.
9889 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9890 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9891 BasicBlock::iterator BI = SS;
9892 if (&*++BI == II)
9893 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009894 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009895 }
9896
9897 // Scan down this block to see if there is another stack restore in the
9898 // same block without an intervening call/alloca.
9899 BasicBlock::iterator BI = II;
9900 TerminatorInst *TI = II->getParent()->getTerminator();
9901 bool CannotRemove = false;
9902 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009903 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009904 CannotRemove = true;
9905 break;
9906 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009907 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9908 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9909 // If there is a stackrestore below this one, remove this one.
9910 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9911 return EraseInstFromFunction(CI);
9912 // Otherwise, ignore the intrinsic.
9913 } else {
9914 // If we found a non-intrinsic call, we can't remove the stack
9915 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009916 CannotRemove = true;
9917 break;
9918 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009919 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009920 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009921
9922 // If the stack restore is in a return/unwind block and if there are no
9923 // allocas or calls between the restore and the return, nuke the restore.
9924 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9925 return EraseInstFromFunction(CI);
9926 break;
9927 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009928 }
9929
Chris Lattner8b0ea312006-01-13 20:11:04 +00009930 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009931}
9932
9933// InvokeInst simplification
9934//
9935Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009936 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009937}
9938
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009939/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9940/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009941static bool isSafeToEliminateVarargsCast(const CallSite CS,
9942 const CastInst * const CI,
9943 const TargetData * const TD,
9944 const int ix) {
9945 if (!CI->isLosslessCast())
9946 return false;
9947
9948 // The size of ByVal arguments is derived from the type, so we
9949 // can't change to a type with a different size. If the size were
9950 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009951 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009952 return true;
9953
9954 const Type* SrcTy =
9955 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9956 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9957 if (!SrcTy->isSized() || !DstTy->isSized())
9958 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009959 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009960 return false;
9961 return true;
9962}
9963
Chris Lattnera44d8a22003-10-07 22:32:43 +00009964// visitCallSite - Improvements for call and invoke instructions.
9965//
9966Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009967 bool Changed = false;
9968
9969 // If the callee is a constexpr cast of a function, attempt to move the cast
9970 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009971 if (transformConstExprCastCall(CS)) return 0;
9972
Chris Lattner6c266db2003-10-07 22:54:13 +00009973 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009974
Chris Lattner08b22ec2005-05-13 07:09:09 +00009975 if (Function *CalleeF = dyn_cast<Function>(Callee))
9976 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9977 Instruction *OldCall = CS.getInstruction();
9978 // If the call and callee calling conventions don't match, this call must
9979 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +00009980 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +00009981 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +00009982 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +00009983 // If OldCall dues not return void then replaceAllUsesWith undef.
9984 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00009985 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00009986 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00009987 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9988 return EraseInstFromFunction(*OldCall);
9989 return 0;
9990 }
9991
Chris Lattner17be6352004-10-18 02:59:09 +00009992 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9993 // This instruction is not reachable, just remove it. We insert a store to
9994 // undef so that we know that this code is not reachable, despite the fact
9995 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +00009996 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +00009997 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +00009998 CS.getInstruction());
9999
Devang Patel228ebd02009-10-13 22:56:32 +000010000 // If CS dues not return void then replaceAllUsesWith undef.
10001 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010002 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010003 CS.getInstruction()->
10004 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010005
10006 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10007 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010008 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010009 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010010 }
Chris Lattner17be6352004-10-18 02:59:09 +000010011 return EraseInstFromFunction(*CS.getInstruction());
10012 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010013
Duncan Sandscdb6d922007-09-17 10:26:40 +000010014 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10015 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10016 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10017 return transformCallThroughTrampoline(CS);
10018
Chris Lattner6c266db2003-10-07 22:54:13 +000010019 const PointerType *PTy = cast<PointerType>(Callee->getType());
10020 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10021 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010022 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010023 // See if we can optimize any arguments passed through the varargs area of
10024 // the call.
10025 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010026 E = CS.arg_end(); I != E; ++I, ++ix) {
10027 CastInst *CI = dyn_cast<CastInst>(*I);
10028 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10029 *I = CI->getOperand(0);
10030 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010031 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010032 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010033 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010034
Duncan Sandsf0c33542007-12-19 21:13:37 +000010035 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010036 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010037 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010038 Changed = true;
10039 }
10040
Chris Lattner6c266db2003-10-07 22:54:13 +000010041 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010042}
10043
Chris Lattner9fe38862003-06-19 17:00:31 +000010044// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10045// attempt to move the cast to the arguments of the call/invoke.
10046//
10047bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10048 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10049 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010050 if (CE->getOpcode() != Instruction::BitCast ||
10051 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010052 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010053 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010054 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010055 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010056
10057 // Okay, this is a cast from a function to a different type. Unless doing so
10058 // would cause a type conversion of one of our arguments, change this call to
10059 // be a direct call with arguments casted to the appropriate types.
10060 //
10061 const FunctionType *FT = Callee->getFunctionType();
10062 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010063 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010064
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010065 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010066 return false; // TODO: Handle multiple return values.
10067
Chris Lattnerf78616b2004-01-14 06:06:08 +000010068 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010069 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010070 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010071 // Conversion is ok if changing from one pointer type to another or from
10072 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010073 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010074 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010075 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010076 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010077 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010078
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010079 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010080 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010081 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010082 return false; // Cannot transform this return value.
10083
Chris Lattner58d74912008-03-12 17:45:29 +000010084 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010085 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010086 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010087 return false; // Attribute not compatible with transformed value.
10088 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010089
Chris Lattnerf78616b2004-01-14 06:06:08 +000010090 // If the callsite is an invoke instruction, and the return value is used by
10091 // a PHI node in a successor, we cannot change the return type of the call
10092 // because there is no place to put the cast instruction (without breaking
10093 // the critical edge). Bail out in this case.
10094 if (!Caller->use_empty())
10095 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10096 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10097 UI != E; ++UI)
10098 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10099 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010100 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010101 return false;
10102 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010103
10104 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10105 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010106
Chris Lattner9fe38862003-06-19 17:00:31 +000010107 CallSite::arg_iterator AI = CS.arg_begin();
10108 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10109 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010110 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010111
10112 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010113 return false; // Cannot transform this parameter value.
10114
Devang Patel19c87462008-09-26 22:53:05 +000010115 if (CallerPAL.getParamAttributes(i + 1)
10116 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010117 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010118
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010119 // Converting from one pointer type to another or between a pointer and an
10120 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010121 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010122 (TD && ((isa<PointerType>(ParamTy) ||
10123 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10124 (isa<PointerType>(ActTy) ||
10125 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010126 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010127 }
10128
10129 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010130 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010131 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010132
Chris Lattner58d74912008-03-12 17:45:29 +000010133 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10134 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010135 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010136 // won't be dropping them. Check that these extra arguments have attributes
10137 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010138 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10139 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010140 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010141 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010142 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010143 return false;
10144 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010145
Chris Lattner9fe38862003-06-19 17:00:31 +000010146 // Okay, we decided that this is a safe thing to do: go ahead and start
10147 // inserting cast instructions as necessary...
10148 std::vector<Value*> Args;
10149 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010150 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010151 attrVec.reserve(NumCommonArgs);
10152
10153 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010154 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010155
10156 // If the return value is not being used, the type may not be compatible
10157 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010158 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010159
10160 // Add the new return attributes.
10161 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010162 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010163
10164 AI = CS.arg_begin();
10165 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10166 const Type *ParamTy = FT->getParamType(i);
10167 if ((*AI)->getType() == ParamTy) {
10168 Args.push_back(*AI);
10169 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010170 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010171 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010172 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010173 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010174
10175 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010176 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010177 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010178 }
10179
10180 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010181 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010182 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010183 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010184
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010185 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010186 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010187 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010188 errs() << "WARNING: While resolving call to function '"
10189 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010190 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010191 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010192 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10193 const Type *PTy = getPromotedType((*AI)->getType());
10194 if (PTy != (*AI)->getType()) {
10195 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010196 Instruction::CastOps opcode =
10197 CastInst::getCastOpcode(*AI, false, PTy, false);
10198 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010199 } else {
10200 Args.push_back(*AI);
10201 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010202
Duncan Sandse1e520f2008-01-13 08:02:44 +000010203 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010204 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010205 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010206 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010207 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010208 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010209
Devang Patel19c87462008-09-26 22:53:05 +000010210 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10211 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10212
Devang Patel9674d152009-10-14 17:29:00 +000010213 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010214 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010215
Eric Christophera66297a2009-07-25 02:45:27 +000010216 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10217 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010218
Chris Lattner9fe38862003-06-19 17:00:31 +000010219 Instruction *NC;
10220 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010221 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010222 Args.begin(), Args.end(),
10223 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010224 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010225 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010226 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010227 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10228 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010229 CallInst *CI = cast<CallInst>(Caller);
10230 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010231 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010232 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010233 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010234 }
10235
Chris Lattner6934a042007-02-11 01:23:03 +000010236 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010237 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010238 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010239 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010240 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010241 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010242 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010243
10244 // If this is an invoke instruction, we should insert it after the first
10245 // non-phi, instruction in the normal successor block.
10246 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010247 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010248 InsertNewInstBefore(NC, *I);
10249 } else {
10250 // Otherwise, it's a call, just insert cast right after the call instr
10251 InsertNewInstBefore(NC, *Caller);
10252 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010253 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010254 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010255 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010256 }
10257 }
10258
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010259
Chris Lattner931f8f32009-08-31 05:17:58 +000010260 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010261 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010262
10263 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010264 return true;
10265}
10266
Duncan Sandscdb6d922007-09-17 10:26:40 +000010267// transformCallThroughTrampoline - Turn a call to a function created by the
10268// init_trampoline intrinsic into a direct call to the underlying function.
10269//
10270Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10271 Value *Callee = CS.getCalledValue();
10272 const PointerType *PTy = cast<PointerType>(Callee->getType());
10273 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010274 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010275
10276 // If the call already has the 'nest' attribute somewhere then give up -
10277 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010278 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010279 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010280
10281 IntrinsicInst *Tramp =
10282 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10283
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010284 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010285 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10286 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10287
Devang Patel05988662008-09-25 21:00:45 +000010288 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010289 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010290 unsigned NestIdx = 1;
10291 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010292 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010293
10294 // Look for a parameter marked with the 'nest' attribute.
10295 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10296 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010297 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010298 // Record the parameter type and any other attributes.
10299 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010300 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010301 break;
10302 }
10303
10304 if (NestTy) {
10305 Instruction *Caller = CS.getInstruction();
10306 std::vector<Value*> NewArgs;
10307 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10308
Devang Patel05988662008-09-25 21:00:45 +000010309 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010310 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010311
Duncan Sandscdb6d922007-09-17 10:26:40 +000010312 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010313 // mean appending it. Likewise for attributes.
10314
Devang Patel19c87462008-09-26 22:53:05 +000010315 // Add any result attributes.
10316 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010317 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010318
Duncan Sandscdb6d922007-09-17 10:26:40 +000010319 {
10320 unsigned Idx = 1;
10321 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10322 do {
10323 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010324 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010325 Value *NestVal = Tramp->getOperand(3);
10326 if (NestVal->getType() != NestTy)
10327 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10328 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010329 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010330 }
10331
10332 if (I == E)
10333 break;
10334
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010335 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010336 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010337 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010338 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010339 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010340
10341 ++Idx, ++I;
10342 } while (1);
10343 }
10344
Devang Patel19c87462008-09-26 22:53:05 +000010345 // Add any function attributes.
10346 if (Attributes Attr = Attrs.getFnAttributes())
10347 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10348
Duncan Sandscdb6d922007-09-17 10:26:40 +000010349 // The trampoline may have been bitcast to a bogus type (FTy).
10350 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010351 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010352
Duncan Sandscdb6d922007-09-17 10:26:40 +000010353 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010354 NewTypes.reserve(FTy->getNumParams()+1);
10355
Duncan Sandscdb6d922007-09-17 10:26:40 +000010356 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010357 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010358 {
10359 unsigned Idx = 1;
10360 FunctionType::param_iterator I = FTy->param_begin(),
10361 E = FTy->param_end();
10362
10363 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010364 if (Idx == NestIdx)
10365 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010366 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010367
10368 if (I == E)
10369 break;
10370
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010371 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010372 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010373
10374 ++Idx, ++I;
10375 } while (1);
10376 }
10377
10378 // Replace the trampoline call with a direct call. Let the generic
10379 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010380 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010381 FTy->isVarArg());
10382 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010383 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010384 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010385 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010386 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10387 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010388
10389 Instruction *NewCaller;
10390 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010391 NewCaller = InvokeInst::Create(NewCallee,
10392 II->getNormalDest(), II->getUnwindDest(),
10393 NewArgs.begin(), NewArgs.end(),
10394 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010395 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010396 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010397 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010398 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10399 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010400 if (cast<CallInst>(Caller)->isTailCall())
10401 cast<CallInst>(NewCaller)->setTailCall();
10402 cast<CallInst>(NewCaller)->
10403 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010404 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010405 }
Devang Patel9674d152009-10-14 17:29:00 +000010406 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010407 Caller->replaceAllUsesWith(NewCaller);
10408 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010409 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010410 return 0;
10411 }
10412 }
10413
10414 // Replace the trampoline call with a direct call. Since there is no 'nest'
10415 // parameter, there is no need to adjust the argument list. Let the generic
10416 // code sort out any function type mismatches.
10417 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010418 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010419 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010420 CS.setCalledFunction(NewCallee);
10421 return CS.getInstruction();
10422}
10423
Dan Gohman9ad29202009-09-16 16:50:24 +000010424/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10425/// 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 +000010426/// and a single binop.
10427Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10428 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010429 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010430 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010431 Value *LHSVal = FirstInst->getOperand(0);
10432 Value *RHSVal = FirstInst->getOperand(1);
10433
10434 const Type *LHSType = LHSVal->getType();
10435 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010436
Dan Gohman9ad29202009-09-16 16:50:24 +000010437 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010438 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010439 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010440 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010441 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010442 // types or GEP's with different index types.
10443 I->getOperand(0)->getType() != LHSType ||
10444 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010445 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010446
10447 // If they are CmpInst instructions, check their predicates
10448 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10449 if (cast<CmpInst>(I)->getPredicate() !=
10450 cast<CmpInst>(FirstInst)->getPredicate())
10451 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010452
10453 // Keep track of which operand needs a phi node.
10454 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10455 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010456 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010457
10458 // If both LHS and RHS would need a PHI, don't do this transformation,
10459 // because it would increase the number of PHIs entering the block,
10460 // which leads to higher register pressure. This is especially
10461 // bad when the PHIs are in the header of a loop.
10462 if (!LHSVal && !RHSVal)
10463 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010464
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010465 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010466
Chris Lattner7da52b22006-11-01 04:51:18 +000010467 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010468 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010469 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010470 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010471 NewLHS = PHINode::Create(LHSType,
10472 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010473 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10474 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010475 InsertNewInstBefore(NewLHS, PN);
10476 LHSVal = NewLHS;
10477 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010478
10479 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010480 NewRHS = PHINode::Create(RHSType,
10481 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010482 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10483 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010484 InsertNewInstBefore(NewRHS, PN);
10485 RHSVal = NewRHS;
10486 }
10487
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010488 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010489 if (NewLHS || NewRHS) {
10490 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10491 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10492 if (NewLHS) {
10493 Value *NewInLHS = InInst->getOperand(0);
10494 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10495 }
10496 if (NewRHS) {
10497 Value *NewInRHS = InInst->getOperand(1);
10498 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10499 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010500 }
10501 }
10502
Chris Lattner7da52b22006-11-01 04:51:18 +000010503 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010504 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010505 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010506 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010507 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010508}
10509
Chris Lattner05f18922008-12-01 02:34:36 +000010510Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10511 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10512
10513 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10514 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010515 // This is true if all GEP bases are allocas and if all indices into them are
10516 // constants.
10517 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010518
10519 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010520 // more than one phi, which leads to higher register pressure. This is
10521 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010522 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010523
Dan Gohman9ad29202009-09-16 16:50:24 +000010524 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010525 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10526 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10527 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10528 GEP->getNumOperands() != FirstInst->getNumOperands())
10529 return 0;
10530
Chris Lattner36d3e322009-02-21 00:46:50 +000010531 // Keep track of whether or not all GEPs are of alloca pointers.
10532 if (AllBasePointersAreAllocas &&
10533 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10534 !GEP->hasAllConstantIndices()))
10535 AllBasePointersAreAllocas = false;
10536
Chris Lattner05f18922008-12-01 02:34:36 +000010537 // Compare the operand lists.
10538 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10539 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10540 continue;
10541
10542 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10543 // if one of the PHIs has a constant for the index. The index may be
10544 // substantially cheaper to compute for the constants, so making it a
10545 // variable index could pessimize the path. This also handles the case
10546 // for struct indices, which must always be constant.
10547 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10548 isa<ConstantInt>(GEP->getOperand(op)))
10549 return 0;
10550
10551 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10552 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010553
10554 // If we already needed a PHI for an earlier operand, and another operand
10555 // also requires a PHI, we'd be introducing more PHIs than we're
10556 // eliminating, which increases register pressure on entry to the PHI's
10557 // block.
10558 if (NeededPhi)
10559 return 0;
10560
Chris Lattner05f18922008-12-01 02:34:36 +000010561 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010562 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010563 }
10564 }
10565
Chris Lattner36d3e322009-02-21 00:46:50 +000010566 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010567 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010568 // offset calculation, but all the predecessors will have to materialize the
10569 // stack address into a register anyway. We'd actually rather *clone* the
10570 // load up into the predecessors so that we have a load of a gep of an alloca,
10571 // which can usually all be folded into the load.
10572 if (AllBasePointersAreAllocas)
10573 return 0;
10574
Chris Lattner05f18922008-12-01 02:34:36 +000010575 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10576 // that is variable.
10577 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10578
10579 bool HasAnyPHIs = false;
10580 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10581 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10582 Value *FirstOp = FirstInst->getOperand(i);
10583 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10584 FirstOp->getName()+".pn");
10585 InsertNewInstBefore(NewPN, PN);
10586
10587 NewPN->reserveOperandSpace(e);
10588 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10589 OperandPhis[i] = NewPN;
10590 FixedOperands[i] = NewPN;
10591 HasAnyPHIs = true;
10592 }
10593
10594
10595 // Add all operands to the new PHIs.
10596 if (HasAnyPHIs) {
10597 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10598 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10599 BasicBlock *InBB = PN.getIncomingBlock(i);
10600
10601 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10602 if (PHINode *OpPhi = OperandPhis[op])
10603 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10604 }
10605 }
10606
10607 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010608 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10609 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10610 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010611 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10612 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010613}
10614
10615
Chris Lattner21550882009-02-23 05:56:17 +000010616/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10617/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010618/// obvious the value of the load is not changed from the point of the load to
10619/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010620///
10621/// Finally, it is safe, but not profitable, to sink a load targetting a
10622/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10623/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010624static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010625 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10626
10627 for (++BBI; BBI != E; ++BBI)
10628 if (BBI->mayWriteToMemory())
10629 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010630
10631 // Check for non-address taken alloca. If not address-taken already, it isn't
10632 // profitable to do this xform.
10633 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10634 bool isAddressTaken = false;
10635 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10636 UI != E; ++UI) {
10637 if (isa<LoadInst>(UI)) continue;
10638 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10639 // If storing TO the alloca, then the address isn't taken.
10640 if (SI->getOperand(1) == AI) continue;
10641 }
10642 isAddressTaken = true;
10643 break;
10644 }
10645
Chris Lattner36d3e322009-02-21 00:46:50 +000010646 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010647 return false;
10648 }
10649
Chris Lattner36d3e322009-02-21 00:46:50 +000010650 // If this load is a load from a GEP with a constant offset from an alloca,
10651 // then we don't want to sink it. In its present form, it will be
10652 // load [constant stack offset]. Sinking it will cause us to have to
10653 // materialize the stack addresses in each predecessor in a register only to
10654 // do a shared load from register in the successor.
10655 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10656 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10657 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10658 return false;
10659
Chris Lattner76c73142006-11-01 07:13:54 +000010660 return true;
10661}
10662
Chris Lattner9fe38862003-06-19 17:00:31 +000010663
Chris Lattnerbac32862004-11-14 19:13:23 +000010664// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10665// operator and they all are only used by the PHI, PHI together their
10666// inputs, and do the operation once, to the result of the PHI.
10667Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10668 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10669
10670 // Scan the instruction, looking for input operations that can be folded away.
10671 // If all input operands to the phi are the same instruction (e.g. a cast from
10672 // the same type or "+42") we can pull the operation through the PHI, reducing
10673 // code size and simplifying code.
10674 Constant *ConstantOp = 0;
10675 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010676 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010677 if (isa<CastInst>(FirstInst)) {
10678 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010679 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010680 // Can fold binop, compare or shift here if the RHS is a constant,
10681 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010682 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010683 if (ConstantOp == 0)
10684 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010685 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10686 isVolatile = LI->isVolatile();
10687 // We can't sink the load if the loaded value could be modified between the
10688 // load and the PHI.
10689 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010690 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010691 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010692
10693 // If the PHI is of volatile loads and the load block has multiple
10694 // successors, sinking it would remove a load of the volatile value from
10695 // the path through the other successor.
10696 if (isVolatile &&
10697 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10698 return 0;
10699
Chris Lattner9c080502006-11-01 07:43:41 +000010700 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010701 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010702 } else {
10703 return 0; // Cannot fold this operation.
10704 }
10705
10706 // Check to see if all arguments are the same operation.
10707 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10708 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10709 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010710 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010711 return 0;
10712 if (CastSrcTy) {
10713 if (I->getOperand(0)->getType() != CastSrcTy)
10714 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010715 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010716 // We can't sink the load if the loaded value could be modified between
10717 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010718 if (LI->isVolatile() != isVolatile ||
10719 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010720 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010721 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010722
Chris Lattner71042962008-07-08 17:18:32 +000010723 // If the PHI is of volatile loads and the load block has multiple
10724 // successors, sinking it would remove a load of the volatile value from
10725 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010726 if (isVolatile &&
10727 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10728 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010729
Chris Lattnerbac32862004-11-14 19:13:23 +000010730 } else if (I->getOperand(1) != ConstantOp) {
10731 return 0;
10732 }
10733 }
10734
10735 // Okay, they are all the same operation. Create a new PHI node of the
10736 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010737 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10738 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010739 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010740
10741 Value *InVal = FirstInst->getOperand(0);
10742 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010743
10744 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010745 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10746 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10747 if (NewInVal != InVal)
10748 InVal = 0;
10749 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10750 }
10751
10752 Value *PhiVal;
10753 if (InVal) {
10754 // The new PHI unions all of the same values together. This is really
10755 // common, so we handle it intelligently here for compile-time speed.
10756 PhiVal = InVal;
10757 delete NewPN;
10758 } else {
10759 InsertNewInstBefore(NewPN, PN);
10760 PhiVal = NewPN;
10761 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010762
Chris Lattnerbac32862004-11-14 19:13:23 +000010763 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010764 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010765 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010766 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010767 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010768 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010769 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010770 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010771 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10772
10773 // If this was a volatile load that we are merging, make sure to loop through
10774 // and mark all the input loads as non-volatile. If we don't do this, we will
10775 // insert a new volatile load and the old ones will not be deletable.
10776 if (isVolatile)
10777 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10778 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10779
10780 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010781}
Chris Lattnera1be5662002-05-02 17:06:02 +000010782
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010783/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10784/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010785static bool DeadPHICycle(PHINode *PN,
10786 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010787 if (PN->use_empty()) return true;
10788 if (!PN->hasOneUse()) return false;
10789
10790 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010791 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010792 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010793
10794 // Don't scan crazily complex things.
10795 if (PotentiallyDeadPHIs.size() == 16)
10796 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010797
10798 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10799 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010800
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010801 return false;
10802}
10803
Chris Lattnercf5008a2007-11-06 21:52:06 +000010804/// PHIsEqualValue - Return true if this phi node is always equal to
10805/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10806/// z = some value; x = phi (y, z); y = phi (x, z)
10807static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10808 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10809 // See if we already saw this PHI node.
10810 if (!ValueEqualPHIs.insert(PN))
10811 return true;
10812
10813 // Don't scan crazily complex things.
10814 if (ValueEqualPHIs.size() == 16)
10815 return false;
10816
10817 // Scan the operands to see if they are either phi nodes or are equal to
10818 // the value.
10819 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10820 Value *Op = PN->getIncomingValue(i);
10821 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10822 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10823 return false;
10824 } else if (Op != NonPhiInVal)
10825 return false;
10826 }
10827
10828 return true;
10829}
10830
10831
Chris Lattner473945d2002-05-06 18:06:38 +000010832// PHINode simplification
10833//
Chris Lattner7e708292002-06-25 16:13:24 +000010834Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010835 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010836 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010837
Owen Anderson7e057142006-07-10 22:03:18 +000010838 if (Value *V = PN.hasConstantValue())
10839 return ReplaceInstUsesWith(PN, V);
10840
Owen Anderson7e057142006-07-10 22:03:18 +000010841 // If all PHI operands are the same operation, pull them through the PHI,
10842 // reducing code size.
10843 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010844 isa<Instruction>(PN.getIncomingValue(1)) &&
10845 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10846 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10847 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10848 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010849 PN.getIncomingValue(0)->hasOneUse())
10850 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10851 return Result;
10852
10853 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10854 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10855 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010856 if (PN.hasOneUse()) {
10857 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10858 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010859 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010860 PotentiallyDeadPHIs.insert(&PN);
10861 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010862 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010863 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010864
10865 // If this phi has a single use, and if that use just computes a value for
10866 // the next iteration of a loop, delete the phi. This occurs with unused
10867 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10868 // common case here is good because the only other things that catch this
10869 // are induction variable analysis (sometimes) and ADCE, which is only run
10870 // late.
10871 if (PHIUser->hasOneUse() &&
10872 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10873 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010874 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010875 }
10876 }
Owen Anderson7e057142006-07-10 22:03:18 +000010877
Chris Lattnercf5008a2007-11-06 21:52:06 +000010878 // We sometimes end up with phi cycles that non-obviously end up being the
10879 // same value, for example:
10880 // z = some value; x = phi (y, z); y = phi (x, z)
10881 // where the phi nodes don't necessarily need to be in the same block. Do a
10882 // quick check to see if the PHI node only contains a single non-phi value, if
10883 // so, scan to see if the phi cycle is actually equal to that value.
10884 {
10885 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10886 // Scan for the first non-phi operand.
10887 while (InValNo != NumOperandVals &&
10888 isa<PHINode>(PN.getIncomingValue(InValNo)))
10889 ++InValNo;
10890
10891 if (InValNo != NumOperandVals) {
10892 Value *NonPhiInVal = PN.getOperand(InValNo);
10893
10894 // Scan the rest of the operands to see if there are any conflicts, if so
10895 // there is no need to recursively scan other phis.
10896 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10897 Value *OpVal = PN.getIncomingValue(InValNo);
10898 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10899 break;
10900 }
10901
10902 // If we scanned over all operands, then we have one unique value plus
10903 // phi values. Scan PHI nodes to see if they all merge in each other or
10904 // the value.
10905 if (InValNo == NumOperandVals) {
10906 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10907 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10908 return ReplaceInstUsesWith(PN, NonPhiInVal);
10909 }
10910 }
10911 }
Chris Lattner60921c92003-12-19 05:58:40 +000010912 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010913}
10914
Chris Lattner7e708292002-06-25 16:13:24 +000010915Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010916 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000010917 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010918 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010919 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010920
Chris Lattnere87597f2004-10-16 18:11:37 +000010921 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010922 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010923
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010924 bool HasZeroPointerIndex = false;
10925 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10926 HasZeroPointerIndex = C->isNullValue();
10927
10928 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010929 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010930
Chris Lattner28977af2004-04-05 01:30:19 +000010931 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010932 if (TD) {
10933 bool MadeChange = false;
10934 unsigned PtrSize = TD->getPointerSizeInBits();
10935
10936 gep_type_iterator GTI = gep_type_begin(GEP);
10937 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10938 I != E; ++I, ++GTI) {
10939 if (!isa<SequentialType>(*GTI)) continue;
10940
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010941 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010942 // to what we need. If narrower, sign-extend it to what we need. This
10943 // explicit cast can make subsequent optimizations more obvious.
10944 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000010945 if (OpBits == PtrSize)
10946 continue;
10947
Chris Lattner2345d1d2009-08-30 20:01:10 +000010948 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010949 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010950 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010951 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010952 }
Chris Lattner28977af2004-04-05 01:30:19 +000010953
Chris Lattner90ac28c2002-08-02 19:29:35 +000010954 // Combine Indices - If the source pointer to this getelementptr instruction
10955 // is a getelementptr instruction, combine the indices of the two
10956 // getelementptr instructions into a single instruction.
10957 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010958 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010959 // Note that if our source is a gep chain itself that we wait for that
10960 // chain to be resolved before we perform this transformation. This
10961 // avoids us creating a TON of code in some cases.
10962 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010963 if (GetElementPtrInst *SrcGEP =
10964 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10965 if (SrcGEP->getNumOperands() == 2)
10966 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000010967
Chris Lattner72588fc2007-02-15 22:48:32 +000010968 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010969
10970 // Find out whether the last index in the source GEP is a sequential idx.
10971 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000010972 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10973 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010974 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010975
Chris Lattner90ac28c2002-08-02 19:29:35 +000010976 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010977 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010978 // Replace: gep (gep %P, long B), long A, ...
10979 // With: T = long A+B; gep %P, T, ...
10980 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010981 Value *Sum;
10982 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10983 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000010984 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010985 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000010986 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010987 Sum = SO1;
10988 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000010989 // If they aren't the same type, then the input hasn't been processed
10990 // by the loop above yet (which canonicalizes sequential index types to
10991 // intptr_t). Just avoid transforming this until the input has been
10992 // normalized.
10993 if (SO1->getType() != GO1->getType())
10994 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010995 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000010996 }
Chris Lattner620ce142004-05-07 22:09:22 +000010997
Chris Lattnerab984842009-08-30 05:30:55 +000010998 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010999 if (Src->getNumOperands() == 2) {
11000 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011001 GEP.setOperand(1, Sum);
11002 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011003 }
Chris Lattnerab984842009-08-30 05:30:55 +000011004 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011005 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011006 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011007 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011008 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011009 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011010 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011011 Indices.append(Src->op_begin()+1, Src->op_end());
11012 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011013 }
11014
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011015 if (!Indices.empty())
11016 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11017 Src->isInBounds()) ?
11018 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11019 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011020 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011021 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011022 }
11023
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011024 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11025 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011026 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011027
Chris Lattner2de23192009-08-30 20:38:21 +000011028 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11029 // want to change the gep until the bitcasts are eliminated.
11030 if (getBitCastOperand(X)) {
11031 Worklist.AddValue(PtrOp);
11032 return 0;
11033 }
11034
Chris Lattner963f4ba2009-08-30 20:36:46 +000011035 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11036 // into : GEP [10 x i8]* X, i32 0, ...
11037 //
11038 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11039 // into : GEP i8* X, ...
11040 //
11041 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011042 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011043 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11044 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011045 if (const ArrayType *CATy =
11046 dyn_cast<ArrayType>(CPTy->getElementType())) {
11047 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11048 if (CATy->getElementType() == XTy->getElementType()) {
11049 // -> GEP i8* X, ...
11050 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011051 return cast<GEPOperator>(&GEP)->isInBounds() ?
11052 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11053 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011054 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11055 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011056 }
11057
11058 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011059 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011060 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011061 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011062 // At this point, we know that the cast source type is a pointer
11063 // to an array of the same type as the destination pointer
11064 // array. Because the array type is never stepped over (there
11065 // is a leading zero) we can fold the cast into this GEP.
11066 GEP.setOperand(0, X);
11067 return &GEP;
11068 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011069 }
11070 }
Chris Lattnereed48272005-09-13 00:40:14 +000011071 } else if (GEP.getNumOperands() == 2) {
11072 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011073 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11074 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011075 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11076 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011077 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011078 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11079 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011080 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011081 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011082 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011083 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11084 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011085 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011086 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011087 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011088 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011089
11090 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011091 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011092 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011093 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011094
Owen Anderson1d0be152009-08-13 21:58:54 +000011095 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011096 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011097 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011098
11099 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11100 // allow either a mul, shift, or constant here.
11101 Value *NewIdx = 0;
11102 ConstantInt *Scale = 0;
11103 if (ArrayEltSize == 1) {
11104 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011105 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011106 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011107 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011108 Scale = CI;
11109 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11110 if (Inst->getOpcode() == Instruction::Shl &&
11111 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011112 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11113 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011114 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011115 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011116 NewIdx = Inst->getOperand(0);
11117 } else if (Inst->getOpcode() == Instruction::Mul &&
11118 isa<ConstantInt>(Inst->getOperand(1))) {
11119 Scale = cast<ConstantInt>(Inst->getOperand(1));
11120 NewIdx = Inst->getOperand(0);
11121 }
11122 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011123
Chris Lattner7835cdd2005-09-13 18:36:04 +000011124 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011125 // out, perform the transformation. Note, we don't know whether Scale is
11126 // signed or not. We'll use unsigned version of division/modulo
11127 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011128 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011129 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011130 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011131 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011132 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011133 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11134 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011135 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011136 }
11137
11138 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011139 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011140 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011141 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011142 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11143 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11144 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011145 // The NewGEP must be pointer typed, so must the old one -> BitCast
11146 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011147 }
11148 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011149 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011150 }
Chris Lattner58407792009-01-09 04:53:57 +000011151
Chris Lattner46cd5a12009-01-09 05:44:56 +000011152 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011153 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011154 /// Y = gep X, <...constant indices...>
11155 /// into a gep of the original struct. This is important for SROA and alias
11156 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011157 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011158 if (TD &&
11159 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011160 // Determine how much the GEP moves the pointer. We are guaranteed to get
11161 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011162 ConstantInt *OffsetV =
11163 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011164 int64_t Offset = OffsetV->getSExtValue();
11165
11166 // If this GEP instruction doesn't move the pointer, just replace the GEP
11167 // with a bitcast of the real input to the dest type.
11168 if (Offset == 0) {
11169 // If the bitcast is of an allocation, and the allocation will be
11170 // converted to match the type of the cast, don't touch this.
Victor Hernandez83d63912009-09-18 22:35:49 +000011171 if (isa<AllocationInst>(BCI->getOperand(0)) ||
11172 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011173 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11174 if (Instruction *I = visitBitCast(*BCI)) {
11175 if (I != BCI) {
11176 I->takeName(BCI);
11177 BCI->getParent()->getInstList().insert(BCI, I);
11178 ReplaceInstUsesWith(*BCI, I);
11179 }
11180 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011181 }
Chris Lattner58407792009-01-09 04:53:57 +000011182 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011183 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011184 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011185
11186 // Otherwise, if the offset is non-zero, we need to find out if there is a
11187 // field at Offset in 'A's type. If so, we can pull the cast through the
11188 // GEP.
11189 SmallVector<Value*, 8> NewIndices;
11190 const Type *InTy =
11191 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011192 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011193 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11194 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11195 NewIndices.end()) :
11196 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11197 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011198
11199 if (NGEP->getType() == GEP.getType())
11200 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011201 NGEP->takeName(&GEP);
11202 return new BitCastInst(NGEP, GEP.getType());
11203 }
Chris Lattner58407792009-01-09 04:53:57 +000011204 }
11205 }
11206
Chris Lattner8a2a3112001-12-14 16:52:21 +000011207 return 0;
11208}
11209
Chris Lattner0864acf2002-11-04 16:18:53 +000011210Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11211 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011212 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011213 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11214 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011215 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011216 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011217
11218 // Create and insert the replacement instruction...
11219 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011220 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011221 else {
11222 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011223 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011224 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011225 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011226
Chris Lattner0864acf2002-11-04 16:18:53 +000011227 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011228 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011229 //
11230 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011231 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011232
11233 // Now that I is pointing to the first non-allocation-inst in the block,
11234 // insert our getelementptr instruction...
11235 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011236 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011237 Value *Idx[2];
11238 Idx[0] = NullIdx;
11239 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011240 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11241 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011242
11243 // Now make everything use the getelementptr instead of the original
11244 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011245 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011246 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011247 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011248 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011249 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011250
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011251 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011252 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011253 // Note that we only do this for alloca's, because malloc should allocate
11254 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011255 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011256 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011257
11258 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11259 if (AI.getAlignment() == 0)
11260 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11261 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011262
Chris Lattner0864acf2002-11-04 16:18:53 +000011263 return 0;
11264}
11265
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011266Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11267 Value *Op = FI.getOperand(0);
11268
Chris Lattner17be6352004-10-18 02:59:09 +000011269 // free undef -> unreachable.
11270 if (isa<UndefValue>(Op)) {
11271 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011272 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000011273 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011274 return EraseInstFromFunction(FI);
11275 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011276
Chris Lattner6160e852004-02-28 04:57:37 +000011277 // If we have 'free null' delete the instruction. This can happen in stl code
11278 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011279 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011280 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011281
11282 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11283 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11284 FI.setOperand(0, CI->getOperand(0));
11285 return &FI;
11286 }
11287
11288 // Change free (gep X, 0,0,0,0) into free(X)
11289 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11290 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011291 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011292 FI.setOperand(0, GEPI->getOperand(0));
11293 return &FI;
11294 }
11295 }
11296
11297 // Change free(malloc) into nothing, if the malloc has a single use.
11298 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11299 if (MI->hasOneUse()) {
11300 EraseInstFromFunction(FI);
11301 return EraseInstFromFunction(*MI);
11302 }
Victor Hernandez83d63912009-09-18 22:35:49 +000011303 if (isMalloc(Op)) {
11304 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11305 if (Op->hasOneUse() && CI->hasOneUse()) {
11306 EraseInstFromFunction(FI);
11307 EraseInstFromFunction(*CI);
11308 return EraseInstFromFunction(*cast<Instruction>(Op));
11309 }
11310 } else {
11311 // Op is a call to malloc
11312 if (Op->hasOneUse()) {
11313 EraseInstFromFunction(FI);
11314 return EraseInstFromFunction(*cast<Instruction>(Op));
11315 }
11316 }
11317 }
Chris Lattner6160e852004-02-28 04:57:37 +000011318
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011319 return 0;
11320}
11321
11322
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011323/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011324static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011325 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011326 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011327 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011328 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011329
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011330 if (TD) {
11331 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11332 // Instead of loading constant c string, use corresponding integer value
11333 // directly if string length is small enough.
11334 std::string Str;
11335 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11336 unsigned len = Str.length();
11337 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11338 unsigned numBits = Ty->getPrimitiveSizeInBits();
11339 // Replace LI with immediate integer store.
11340 if ((numBits >> 3) == len + 1) {
11341 APInt StrVal(numBits, 0);
11342 APInt SingleChar(numBits, 0);
11343 if (TD->isLittleEndian()) {
11344 for (signed i = len-1; i >= 0; i--) {
11345 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11346 StrVal = (StrVal << 8) | SingleChar;
11347 }
11348 } else {
11349 for (unsigned i = 0; i < len; i++) {
11350 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11351 StrVal = (StrVal << 8) | SingleChar;
11352 }
11353 // Append NULL at the end.
11354 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011355 StrVal = (StrVal << 8) | SingleChar;
11356 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011357 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011358 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011359 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011360 }
11361 }
11362 }
11363
Mon P Wang6753f952009-02-07 22:19:29 +000011364 const PointerType *DestTy = cast<PointerType>(CI->getType());
11365 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011366 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011367
11368 // If the address spaces don't match, don't eliminate the cast.
11369 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11370 return 0;
11371
Chris Lattnerb89e0712004-07-13 01:49:43 +000011372 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011373
Reid Spencer42230162007-01-22 05:51:25 +000011374 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011375 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011376 // If the source is an array, the code below will not succeed. Check to
11377 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11378 // constants.
11379 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11380 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11381 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011382 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011383 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011384 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011385 SrcTy = cast<PointerType>(CastOp->getType());
11386 SrcPTy = SrcTy->getElementType();
11387 }
11388
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011389 if (IC.getTargetData() &&
11390 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011391 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011392 // Do not allow turning this into a load of an integer, which is then
11393 // casted to a pointer, this pessimizes pointer analysis a lot.
11394 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011395 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11396 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011397
Chris Lattnerf9527852005-01-31 04:50:46 +000011398 // Okay, we are casting from one integer or pointer type to another of
11399 // the same size. Instead of casting the pointer before the load, cast
11400 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011401 Value *NewLoad =
11402 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011403 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011404 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011405 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011406 }
11407 }
11408 return 0;
11409}
11410
Chris Lattner833b8a42003-06-26 05:06:25 +000011411Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11412 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011413
Dan Gohman9941f742007-07-20 16:34:21 +000011414 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011415 if (TD) {
11416 unsigned KnownAlign =
11417 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11418 if (KnownAlign >
11419 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11420 LI.getAlignment()))
11421 LI.setAlignment(KnownAlign);
11422 }
Dan Gohman9941f742007-07-20 16:34:21 +000011423
Chris Lattner963f4ba2009-08-30 20:36:46 +000011424 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011425 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011426 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011427 return Res;
11428
11429 // None of the following transforms are legal for volatile loads.
11430 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011431
Dan Gohman2276a7b2008-10-15 23:19:35 +000011432 // Do really simple store-to-load forwarding and load CSE, to catch cases
11433 // where there are several consequtive memory accesses to the same location,
11434 // separated by a few arithmetic operations.
11435 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011436 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11437 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011438
Christopher Lambb15147e2007-12-29 07:56:53 +000011439 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11440 const Value *GEPI0 = GEPI->getOperand(0);
11441 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011442 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011443 // Insert a new store to null instruction before the load to indicate
11444 // that this code is not reachable. We do this instead of inserting
11445 // an unreachable instruction directly because we cannot modify the
11446 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011447 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011448 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011449 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011450 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011451 }
Chris Lattner37366c12005-05-01 04:24:53 +000011452
Chris Lattnere87597f2004-10-16 18:11:37 +000011453 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011454 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011455 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011456 if (isa<UndefValue>(C) ||
11457 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011458 // Insert a new store to null instruction before the load to indicate that
11459 // this code is not reachable. We do this instead of inserting an
11460 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011461 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011462 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011463 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011464 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011465
Chris Lattnere87597f2004-10-16 18:11:37 +000011466 // Instcombine load (constant global) into the value loaded.
11467 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011468 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011469 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011470
Chris Lattnere87597f2004-10-16 18:11:37 +000011471 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011472 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011473 if (CE->getOpcode() == Instruction::GetElementPtr) {
11474 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011475 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011476 if (Constant *V =
Dan Gohmanc6f69e92009-10-05 16:36:26 +000011477 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011478 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011479 if (CE->getOperand(0)->isNullValue()) {
11480 // Insert a new store to null instruction before the load to indicate
11481 // that this code is not reachable. We do this instead of inserting
11482 // an unreachable instruction directly because we cannot modify the
11483 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011484 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011485 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011486 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011487 }
11488
Reid Spencer3da59db2006-11-27 01:05:10 +000011489 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011490 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011491 return Res;
11492 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011493 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011494 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011495
11496 // If this load comes from anywhere in a constant global, and if the global
11497 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011498 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011499 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011500 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011501 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011502 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011503 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011504 }
11505 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011506
Chris Lattner37366c12005-05-01 04:24:53 +000011507 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011508 // Change select and PHI nodes to select values instead of addresses: this
11509 // helps alias analysis out a lot, allows many others simplifications, and
11510 // exposes redundancy in the code.
11511 //
11512 // Note that we cannot do the transformation unless we know that the
11513 // introduced loads cannot trap! Something like this is valid as long as
11514 // the condition is always false: load (select bool %C, int* null, int* %G),
11515 // but it would not be valid if we transformed it to load from null
11516 // unconditionally.
11517 //
11518 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11519 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011520 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11521 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011522 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11523 SI->getOperand(1)->getName()+".val");
11524 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11525 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011526 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011527 }
11528
Chris Lattner684fe212004-09-23 15:46:00 +000011529 // load (select (cond, null, P)) -> load P
11530 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11531 if (C->isNullValue()) {
11532 LI.setOperand(0, SI->getOperand(2));
11533 return &LI;
11534 }
11535
11536 // load (select (cond, P, null)) -> load P
11537 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11538 if (C->isNullValue()) {
11539 LI.setOperand(0, SI->getOperand(1));
11540 return &LI;
11541 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011542 }
11543 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011544 return 0;
11545}
11546
Reid Spencer55af2b52007-01-19 21:20:31 +000011547/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011548/// when possible. This makes it generally easy to do alias analysis and/or
11549/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011550static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11551 User *CI = cast<User>(SI.getOperand(1));
11552 Value *CastOp = CI->getOperand(0);
11553
11554 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011555 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11556 if (SrcTy == 0) return 0;
11557
11558 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011559
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011560 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11561 return 0;
11562
Chris Lattner3914f722009-01-24 01:00:13 +000011563 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11564 /// to its first element. This allows us to handle things like:
11565 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11566 /// on 32-bit hosts.
11567 SmallVector<Value*, 4> NewGEPIndices;
11568
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011569 // If the source is an array, the code below will not succeed. Check to
11570 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11571 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011572 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11573 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011574 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011575 NewGEPIndices.push_back(Zero);
11576
11577 while (1) {
11578 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011579 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011580 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011581 NewGEPIndices.push_back(Zero);
11582 SrcPTy = STy->getElementType(0);
11583 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11584 NewGEPIndices.push_back(Zero);
11585 SrcPTy = ATy->getElementType();
11586 } else {
11587 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011588 }
Chris Lattner3914f722009-01-24 01:00:13 +000011589 }
11590
Owen Andersondebcb012009-07-29 22:17:13 +000011591 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011592 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011593
11594 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11595 return 0;
11596
Chris Lattner71759c42009-01-16 20:12:52 +000011597 // If the pointers point into different address spaces or if they point to
11598 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011599 if (!IC.getTargetData() ||
11600 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011601 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011602 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11603 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011604 return 0;
11605
11606 // Okay, we are casting from one integer or pointer type to another of
11607 // the same size. Instead of casting the pointer before
11608 // the store, cast the value to be stored.
11609 Value *NewCast;
11610 Value *SIOp0 = SI.getOperand(0);
11611 Instruction::CastOps opcode = Instruction::BitCast;
11612 const Type* CastSrcTy = SIOp0->getType();
11613 const Type* CastDstTy = SrcPTy;
11614 if (isa<PointerType>(CastDstTy)) {
11615 if (CastSrcTy->isInteger())
11616 opcode = Instruction::IntToPtr;
11617 } else if (isa<IntegerType>(CastDstTy)) {
11618 if (isa<PointerType>(SIOp0->getType()))
11619 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011620 }
Chris Lattner3914f722009-01-24 01:00:13 +000011621
11622 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11623 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011624 if (!NewGEPIndices.empty())
11625 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11626 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011627
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011628 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11629 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011630 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011631}
11632
Chris Lattner4aebaee2008-11-27 08:56:30 +000011633/// equivalentAddressValues - Test if A and B will obviously have the same
11634/// value. This includes recognizing that %t0 and %t1 will have the same
11635/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011636/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011637/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011638/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011639/// %t2 = load i32* %t1
11640///
11641static bool equivalentAddressValues(Value *A, Value *B) {
11642 // Test if the values are trivially equivalent.
11643 if (A == B) return true;
11644
11645 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011646 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11647 // its only used to compare two uses within the same basic block, which
11648 // means that they'll always either have the same value or one of them
11649 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011650 if (isa<BinaryOperator>(A) ||
11651 isa<CastInst>(A) ||
11652 isa<PHINode>(A) ||
11653 isa<GetElementPtrInst>(A))
11654 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011655 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011656 return true;
11657
11658 // Otherwise they may not be equivalent.
11659 return false;
11660}
11661
Dale Johannesen4945c652009-03-03 21:26:39 +000011662// If this instruction has two uses, one of which is a llvm.dbg.declare,
11663// return the llvm.dbg.declare.
11664DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11665 if (!V->hasNUses(2))
11666 return 0;
11667 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11668 UI != E; ++UI) {
11669 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11670 return DI;
11671 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11672 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11673 return DI;
11674 }
11675 }
11676 return 0;
11677}
11678
Chris Lattner2f503e62005-01-31 05:36:43 +000011679Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11680 Value *Val = SI.getOperand(0);
11681 Value *Ptr = SI.getOperand(1);
11682
11683 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011684 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011685 ++NumCombined;
11686 return 0;
11687 }
Chris Lattner836692d2007-01-15 06:51:56 +000011688
11689 // If the RHS is an alloca with a single use, zapify the store, making the
11690 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011691 // If the RHS is an alloca with a two uses, the other one being a
11692 // llvm.dbg.declare, zapify the store and the declare, making the
11693 // alloca dead. We must do this to prevent declare's from affecting
11694 // codegen.
11695 if (!SI.isVolatile()) {
11696 if (Ptr->hasOneUse()) {
11697 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011698 EraseInstFromFunction(SI);
11699 ++NumCombined;
11700 return 0;
11701 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011702 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11703 if (isa<AllocaInst>(GEP->getOperand(0))) {
11704 if (GEP->getOperand(0)->hasOneUse()) {
11705 EraseInstFromFunction(SI);
11706 ++NumCombined;
11707 return 0;
11708 }
11709 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11710 EraseInstFromFunction(*DI);
11711 EraseInstFromFunction(SI);
11712 ++NumCombined;
11713 return 0;
11714 }
11715 }
11716 }
11717 }
11718 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11719 EraseInstFromFunction(*DI);
11720 EraseInstFromFunction(SI);
11721 ++NumCombined;
11722 return 0;
11723 }
Chris Lattner836692d2007-01-15 06:51:56 +000011724 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011725
Dan Gohman9941f742007-07-20 16:34:21 +000011726 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011727 if (TD) {
11728 unsigned KnownAlign =
11729 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11730 if (KnownAlign >
11731 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11732 SI.getAlignment()))
11733 SI.setAlignment(KnownAlign);
11734 }
Dan Gohman9941f742007-07-20 16:34:21 +000011735
Dale Johannesenacb51a32009-03-03 01:43:03 +000011736 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011737 // stores to the same location, separated by a few arithmetic operations. This
11738 // situation often occurs with bitfield accesses.
11739 BasicBlock::iterator BBI = &SI;
11740 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11741 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011742 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011743 // Don't count debug info directives, lest they affect codegen,
11744 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11745 // It is necessary for correctness to skip those that feed into a
11746 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011747 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011748 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011749 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011750 continue;
11751 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011752
11753 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11754 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011755 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11756 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011757 ++NumDeadStore;
11758 ++BBI;
11759 EraseInstFromFunction(*PrevSI);
11760 continue;
11761 }
11762 break;
11763 }
11764
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011765 // If this is a load, we have to stop. However, if the loaded value is from
11766 // the pointer we're loading and is producing the pointer we're storing,
11767 // then *this* store is dead (X = load P; store X -> P).
11768 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011769 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11770 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011771 EraseInstFromFunction(SI);
11772 ++NumCombined;
11773 return 0;
11774 }
11775 // Otherwise, this is a load from some other location. Stores before it
11776 // may not be dead.
11777 break;
11778 }
11779
Chris Lattner9ca96412006-02-08 03:25:32 +000011780 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011781 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011782 break;
11783 }
11784
11785
11786 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011787
11788 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011789 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011790 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011791 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011792 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011793 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011794 ++NumCombined;
11795 }
11796 return 0; // Do not modify these!
11797 }
11798
11799 // store undef, Ptr -> noop
11800 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011801 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011802 ++NumCombined;
11803 return 0;
11804 }
11805
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011806 // If the pointer destination is a cast, see if we can fold the cast into the
11807 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011808 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011809 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11810 return Res;
11811 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011812 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011813 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11814 return Res;
11815
Chris Lattner408902b2005-09-12 23:23:25 +000011816
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011817 // If this store is the last instruction in the basic block (possibly
11818 // excepting debug info instructions and the pointer bitcasts that feed
11819 // into them), and if the block ends with an unconditional branch, try
11820 // to move it to the successor block.
11821 BBI = &SI;
11822 do {
11823 ++BBI;
11824 } while (isa<DbgInfoIntrinsic>(BBI) ||
11825 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011826 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011827 if (BI->isUnconditional())
11828 if (SimplifyStoreAtEndOfBlock(SI))
11829 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011830
Chris Lattner2f503e62005-01-31 05:36:43 +000011831 return 0;
11832}
11833
Chris Lattner3284d1f2007-04-15 00:07:55 +000011834/// SimplifyStoreAtEndOfBlock - Turn things like:
11835/// if () { *P = v1; } else { *P = v2 }
11836/// into a phi node with a store in the successor.
11837///
Chris Lattner31755a02007-04-15 01:02:18 +000011838/// Simplify things like:
11839/// *P = v1; if () { *P = v2; }
11840/// into a phi node with a store in the successor.
11841///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011842bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11843 BasicBlock *StoreBB = SI.getParent();
11844
11845 // Check to see if the successor block has exactly two incoming edges. If
11846 // so, see if the other predecessor contains a store to the same location.
11847 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011848 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011849
11850 // Determine whether Dest has exactly two predecessors and, if so, compute
11851 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011852 pred_iterator PI = pred_begin(DestBB);
11853 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011854 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011855 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011856 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011857 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011858 return false;
11859
11860 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011861 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011862 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011863 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011864 }
Chris Lattner31755a02007-04-15 01:02:18 +000011865 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011866 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011867
11868 // Bail out if all the relevant blocks aren't distinct (this can happen,
11869 // for example, if SI is in an infinite loop)
11870 if (StoreBB == DestBB || OtherBB == DestBB)
11871 return false;
11872
Chris Lattner31755a02007-04-15 01:02:18 +000011873 // Verify that the other block ends in a branch and is not otherwise empty.
11874 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011875 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011876 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011877 return false;
11878
Chris Lattner31755a02007-04-15 01:02:18 +000011879 // If the other block ends in an unconditional branch, check for the 'if then
11880 // else' case. there is an instruction before the branch.
11881 StoreInst *OtherStore = 0;
11882 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011883 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011884 // Skip over debugging info.
11885 while (isa<DbgInfoIntrinsic>(BBI) ||
11886 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11887 if (BBI==OtherBB->begin())
11888 return false;
11889 --BBI;
11890 }
11891 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011892 OtherStore = dyn_cast<StoreInst>(BBI);
11893 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11894 return false;
11895 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011896 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011897 // destinations is StoreBB, then we have the if/then case.
11898 if (OtherBr->getSuccessor(0) != StoreBB &&
11899 OtherBr->getSuccessor(1) != StoreBB)
11900 return false;
11901
11902 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011903 // if/then triangle. See if there is a store to the same ptr as SI that
11904 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011905 for (;; --BBI) {
11906 // Check to see if we find the matching store.
11907 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11908 if (OtherStore->getOperand(1) != SI.getOperand(1))
11909 return false;
11910 break;
11911 }
Eli Friedman6903a242008-06-13 22:02:12 +000011912 // If we find something that may be using or overwriting the stored
11913 // value, or if we run out of instructions, we can't do the xform.
11914 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011915 BBI == OtherBB->begin())
11916 return false;
11917 }
11918
11919 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011920 // make sure nothing reads or overwrites the stored value in
11921 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011922 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11923 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011924 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011925 return false;
11926 }
11927 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011928
Chris Lattner31755a02007-04-15 01:02:18 +000011929 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011930 Value *MergedVal = OtherStore->getOperand(0);
11931 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011932 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011933 PN->reserveOperandSpace(2);
11934 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011935 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11936 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011937 }
11938
11939 // Advance to a place where it is safe to insert the new store and
11940 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011941 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011942 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11943 OtherStore->isVolatile()), *BBI);
11944
11945 // Nuke the old stores.
11946 EraseInstFromFunction(SI);
11947 EraseInstFromFunction(*OtherStore);
11948 ++NumCombined;
11949 return true;
11950}
11951
Chris Lattner2f503e62005-01-31 05:36:43 +000011952
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011953Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11954 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011955 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011956 BasicBlock *TrueDest;
11957 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011958 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011959 !isa<Constant>(X)) {
11960 // Swap Destinations and condition...
11961 BI.setCondition(X);
11962 BI.setSuccessor(0, FalseDest);
11963 BI.setSuccessor(1, TrueDest);
11964 return &BI;
11965 }
11966
Reid Spencere4d87aa2006-12-23 06:05:41 +000011967 // Cannonicalize fcmp_one -> fcmp_oeq
11968 FCmpInst::Predicate FPred; Value *Y;
11969 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011970 TrueDest, FalseDest)) &&
11971 BI.getCondition()->hasOneUse())
11972 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11973 FPred == FCmpInst::FCMP_OGE) {
11974 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11975 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11976
11977 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011978 BI.setSuccessor(0, FalseDest);
11979 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011980 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011981 return &BI;
11982 }
11983
11984 // Cannonicalize icmp_ne -> icmp_eq
11985 ICmpInst::Predicate IPred;
11986 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011987 TrueDest, FalseDest)) &&
11988 BI.getCondition()->hasOneUse())
11989 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11990 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11991 IPred == ICmpInst::ICMP_SGE) {
11992 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11993 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11994 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011995 BI.setSuccessor(0, FalseDest);
11996 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011997 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011998 return &BI;
11999 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012000
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012001 return 0;
12002}
Chris Lattner0864acf2002-11-04 16:18:53 +000012003
Chris Lattner46238a62004-07-03 00:26:11 +000012004Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12005 Value *Cond = SI.getCondition();
12006 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12007 if (I->getOpcode() == Instruction::Add)
12008 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12009 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12010 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012011 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012012 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012013 AddRHS));
12014 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012015 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012016 return &SI;
12017 }
12018 }
12019 return 0;
12020}
12021
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012022Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012023 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012024
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012025 if (!EV.hasIndices())
12026 return ReplaceInstUsesWith(EV, Agg);
12027
12028 if (Constant *C = dyn_cast<Constant>(Agg)) {
12029 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012030 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012031
12032 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012033 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012034
12035 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12036 // Extract the element indexed by the first index out of the constant
12037 Value *V = C->getOperand(*EV.idx_begin());
12038 if (EV.getNumIndices() > 1)
12039 // Extract the remaining indices out of the constant indexed by the
12040 // first index
12041 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12042 else
12043 return ReplaceInstUsesWith(EV, V);
12044 }
12045 return 0; // Can't handle other constants
12046 }
12047 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12048 // We're extracting from an insertvalue instruction, compare the indices
12049 const unsigned *exti, *exte, *insi, *inse;
12050 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12051 exte = EV.idx_end(), inse = IV->idx_end();
12052 exti != exte && insi != inse;
12053 ++exti, ++insi) {
12054 if (*insi != *exti)
12055 // The insert and extract both reference distinctly different elements.
12056 // This means the extract is not influenced by the insert, and we can
12057 // replace the aggregate operand of the extract with the aggregate
12058 // operand of the insert. i.e., replace
12059 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12060 // %E = extractvalue { i32, { i32 } } %I, 0
12061 // with
12062 // %E = extractvalue { i32, { i32 } } %A, 0
12063 return ExtractValueInst::Create(IV->getAggregateOperand(),
12064 EV.idx_begin(), EV.idx_end());
12065 }
12066 if (exti == exte && insi == inse)
12067 // Both iterators are at the end: Index lists are identical. Replace
12068 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12069 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12070 // with "i32 42"
12071 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12072 if (exti == exte) {
12073 // The extract list is a prefix of the insert list. i.e. replace
12074 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12075 // %E = extractvalue { i32, { i32 } } %I, 1
12076 // with
12077 // %X = extractvalue { i32, { i32 } } %A, 1
12078 // %E = insertvalue { i32 } %X, i32 42, 0
12079 // by switching the order of the insert and extract (though the
12080 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012081 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12082 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012083 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12084 insi, inse);
12085 }
12086 if (insi == inse)
12087 // The insert list is a prefix of the extract list
12088 // We can simply remove the common indices from the extract and make it
12089 // operate on the inserted value instead of the insertvalue result.
12090 // i.e., replace
12091 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12092 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12093 // with
12094 // %E extractvalue { i32 } { i32 42 }, 0
12095 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12096 exti, exte);
12097 }
12098 // Can't simplify extracts from other values. Note that nested extracts are
12099 // already simplified implicitely by the above (extract ( extract (insert) )
12100 // will be translated into extract ( insert ( extract ) ) first and then just
12101 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012102 return 0;
12103}
12104
Chris Lattner220b0cf2006-03-05 00:22:33 +000012105/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12106/// is to leave as a vector operation.
12107static bool CheapToScalarize(Value *V, bool isConstant) {
12108 if (isa<ConstantAggregateZero>(V))
12109 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012110 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012111 if (isConstant) return true;
12112 // If all elts are the same, we can extract.
12113 Constant *Op0 = C->getOperand(0);
12114 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12115 if (C->getOperand(i) != Op0)
12116 return false;
12117 return true;
12118 }
12119 Instruction *I = dyn_cast<Instruction>(V);
12120 if (!I) return false;
12121
12122 // Insert element gets simplified to the inserted element or is deleted if
12123 // this is constant idx extract element and its a constant idx insertelt.
12124 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12125 isa<ConstantInt>(I->getOperand(2)))
12126 return true;
12127 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12128 return true;
12129 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12130 if (BO->hasOneUse() &&
12131 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12132 CheapToScalarize(BO->getOperand(1), isConstant)))
12133 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012134 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12135 if (CI->hasOneUse() &&
12136 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12137 CheapToScalarize(CI->getOperand(1), isConstant)))
12138 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012139
12140 return false;
12141}
12142
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012143/// Read and decode a shufflevector mask.
12144///
12145/// It turns undef elements into values that are larger than the number of
12146/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012147static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12148 unsigned NElts = SVI->getType()->getNumElements();
12149 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12150 return std::vector<unsigned>(NElts, 0);
12151 if (isa<UndefValue>(SVI->getOperand(2)))
12152 return std::vector<unsigned>(NElts, 2*NElts);
12153
12154 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012155 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012156 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12157 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012158 Result.push_back(NElts*2); // undef -> 8
12159 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012160 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012161 return Result;
12162}
12163
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012164/// FindScalarElement - Given a vector and an element number, see if the scalar
12165/// value is already around as a register, for example if it were inserted then
12166/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012167static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012168 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012169 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12170 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012171 unsigned Width = PTy->getNumElements();
12172 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012173 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012174
12175 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012176 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012177 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012178 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012179 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012180 return CP->getOperand(EltNo);
12181 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12182 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012183 if (!isa<ConstantInt>(III->getOperand(2)))
12184 return 0;
12185 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012186
12187 // If this is an insert to the element we are looking for, return the
12188 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012189 if (EltNo == IIElt)
12190 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012191
12192 // Otherwise, the insertelement doesn't modify the value, recurse on its
12193 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012194 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012195 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012196 unsigned LHSWidth =
12197 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012198 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012199 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012200 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012201 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012202 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012203 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012204 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012205 }
12206
12207 // Otherwise, we don't know.
12208 return 0;
12209}
12210
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012211Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012212 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012213 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012214 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012215
Dan Gohman07a96762007-07-16 14:29:03 +000012216 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012217 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012218 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012219
Reid Spencer9d6565a2007-02-15 02:26:10 +000012220 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012221 // If vector val is constant with all elements the same, replace EI with
12222 // that element. When the elements are not identical, we cannot replace yet
12223 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012224 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012225 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012226 if (C->getOperand(i) != op0) {
12227 op0 = 0;
12228 break;
12229 }
12230 if (op0)
12231 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012232 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012233
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012234 // If extracting a specified index from the vector, see if we can recursively
12235 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012236 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012237 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012238 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012239
12240 // If this is extracting an invalid index, turn this into undef, to avoid
12241 // crashing the code below.
12242 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012243 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012244
Chris Lattner867b99f2006-10-05 06:55:50 +000012245 // This instruction only demands the single element from the input vector.
12246 // If the input vector has a single use, simplify it based on this use
12247 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012248 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012249 APInt UndefElts(VectorWidth, 0);
12250 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012251 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012252 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012253 EI.setOperand(0, V);
12254 return &EI;
12255 }
12256 }
12257
Owen Andersond672ecb2009-07-03 00:17:18 +000012258 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012259 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012260
12261 // If the this extractelement is directly using a bitcast from a vector of
12262 // the same number of elements, see if we can find the source element from
12263 // it. In this case, we will end up needing to bitcast the scalars.
12264 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12265 if (const VectorType *VT =
12266 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12267 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012268 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12269 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012270 return new BitCastInst(Elt, EI.getType());
12271 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012272 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012273
Chris Lattner73fa49d2006-05-25 22:53:38 +000012274 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012275 // Push extractelement into predecessor operation if legal and
12276 // profitable to do so
12277 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12278 if (I->hasOneUse() &&
12279 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12280 Value *newEI0 =
12281 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12282 EI.getName()+".lhs");
12283 Value *newEI1 =
12284 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12285 EI.getName()+".rhs");
12286 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012287 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012288 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012289 // Extracting the inserted element?
12290 if (IE->getOperand(2) == EI.getOperand(1))
12291 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12292 // If the inserted and extracted elements are constants, they must not
12293 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012294 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012295 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012296 EI.setOperand(0, IE->getOperand(0));
12297 return &EI;
12298 }
12299 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12300 // If this is extracting an element from a shufflevector, figure out where
12301 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012302 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12303 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012304 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012305 unsigned LHSWidth =
12306 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12307
12308 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012309 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012310 else if (SrcIdx < LHSWidth*2) {
12311 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012312 Src = SVI->getOperand(1);
12313 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012314 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012315 }
Eric Christophera3500da2009-07-25 02:28:41 +000012316 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012317 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12318 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012319 }
12320 }
Eli Friedman2451a642009-07-18 23:06:53 +000012321 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012322 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012323 return 0;
12324}
12325
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012326/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12327/// elements from either LHS or RHS, return the shuffle mask and true.
12328/// Otherwise, return false.
12329static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012330 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012331 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012332 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12333 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012334 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012335
12336 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012337 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012338 return true;
12339 } else if (V == LHS) {
12340 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012341 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012342 return true;
12343 } else if (V == RHS) {
12344 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012345 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012346 return true;
12347 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12348 // If this is an insert of an extract from some other vector, include it.
12349 Value *VecOp = IEI->getOperand(0);
12350 Value *ScalarOp = IEI->getOperand(1);
12351 Value *IdxOp = IEI->getOperand(2);
12352
Chris Lattnerd929f062006-04-27 21:14:21 +000012353 if (!isa<ConstantInt>(IdxOp))
12354 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012355 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012356
12357 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12358 // Okay, we can handle this if the vector we are insertinting into is
12359 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012360 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012361 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012362 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012363 return true;
12364 }
12365 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12366 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012367 EI->getOperand(0)->getType() == V->getType()) {
12368 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012369 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012370
12371 // This must be extracting from either LHS or RHS.
12372 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12373 // Okay, we can handle this if the vector we are insertinting into is
12374 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012375 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012376 // If so, update the mask to reflect the inserted value.
12377 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012378 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012379 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012380 } else {
12381 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012382 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012383 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012384
12385 }
12386 return true;
12387 }
12388 }
12389 }
12390 }
12391 }
12392 // TODO: Handle shufflevector here!
12393
12394 return false;
12395}
12396
12397/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12398/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12399/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012400static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012401 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012402 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012403 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012404 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012405 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012406
12407 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012408 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012409 return V;
12410 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012411 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012412 return V;
12413 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12414 // If this is an insert of an extract from some other vector, include it.
12415 Value *VecOp = IEI->getOperand(0);
12416 Value *ScalarOp = IEI->getOperand(1);
12417 Value *IdxOp = IEI->getOperand(2);
12418
12419 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12420 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12421 EI->getOperand(0)->getType() == V->getType()) {
12422 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012423 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12424 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012425
12426 // Either the extracted from or inserted into vector must be RHSVec,
12427 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012428 if (EI->getOperand(0) == RHS || RHS == 0) {
12429 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012430 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012431 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012432 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012433 return V;
12434 }
12435
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012436 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012437 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12438 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012439 // Everything but the extracted element is replaced with the RHS.
12440 for (unsigned i = 0; i != NumElts; ++i) {
12441 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012442 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012443 }
12444 return V;
12445 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012446
12447 // If this insertelement is a chain that comes from exactly these two
12448 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012449 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12450 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012451 return EI->getOperand(0);
12452
Chris Lattnerefb47352006-04-15 01:39:45 +000012453 }
12454 }
12455 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012456 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012457
12458 // Otherwise, can't do anything fancy. Return an identity vector.
12459 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012460 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012461 return V;
12462}
12463
12464Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12465 Value *VecOp = IE.getOperand(0);
12466 Value *ScalarOp = IE.getOperand(1);
12467 Value *IdxOp = IE.getOperand(2);
12468
Chris Lattner599ded12007-04-09 01:11:16 +000012469 // Inserting an undef or into an undefined place, remove this.
12470 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12471 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012472
Chris Lattnerefb47352006-04-15 01:39:45 +000012473 // If the inserted element was extracted from some other vector, and if the
12474 // indexes are constant, try to turn this into a shufflevector operation.
12475 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12476 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12477 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012478 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012479 unsigned ExtractedIdx =
12480 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012481 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012482
12483 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12484 return ReplaceInstUsesWith(IE, VecOp);
12485
12486 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012487 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012488
12489 // If we are extracting a value from a vector, then inserting it right
12490 // back into the same place, just use the input vector.
12491 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12492 return ReplaceInstUsesWith(IE, VecOp);
12493
Chris Lattnerefb47352006-04-15 01:39:45 +000012494 // If this insertelement isn't used by some other insertelement, turn it
12495 // (and any insertelements it points to), into one big shuffle.
12496 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12497 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012498 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012499 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012500 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012501 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012502 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012503 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012504 }
12505 }
12506 }
12507
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012508 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12509 APInt UndefElts(VWidth, 0);
12510 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12511 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12512 return &IE;
12513
Chris Lattnerefb47352006-04-15 01:39:45 +000012514 return 0;
12515}
12516
12517
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012518Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12519 Value *LHS = SVI.getOperand(0);
12520 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012521 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012522
12523 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012524
Chris Lattner867b99f2006-10-05 06:55:50 +000012525 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012526 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012527 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012528
Dan Gohman488fbfc2008-09-09 18:11:14 +000012529 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012530
12531 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12532 return 0;
12533
Evan Cheng388df622009-02-03 10:05:09 +000012534 APInt UndefElts(VWidth, 0);
12535 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12536 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012537 LHS = SVI.getOperand(0);
12538 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012539 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012540 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012541
Chris Lattner863bcff2006-05-25 23:48:38 +000012542 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12543 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12544 if (LHS == RHS || isa<UndefValue>(LHS)) {
12545 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012546 // shuffle(undef,undef,mask) -> undef.
12547 return ReplaceInstUsesWith(SVI, LHS);
12548 }
12549
Chris Lattner863bcff2006-05-25 23:48:38 +000012550 // Remap any references to RHS to use LHS.
12551 std::vector<Constant*> Elts;
12552 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012553 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012554 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012555 else {
12556 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012557 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012558 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012559 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012560 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012561 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012562 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012563 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012564 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012565 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012566 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012567 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012568 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012569 LHS = SVI.getOperand(0);
12570 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012571 MadeChange = true;
12572 }
12573
Chris Lattner7b2e27922006-05-26 00:29:06 +000012574 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012575 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012576
Chris Lattner863bcff2006-05-25 23:48:38 +000012577 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12578 if (Mask[i] >= e*2) continue; // Ignore undef values.
12579 // Is this an identity shuffle of the LHS value?
12580 isLHSID &= (Mask[i] == i);
12581
12582 // Is this an identity shuffle of the RHS value?
12583 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012584 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012585
Chris Lattner863bcff2006-05-25 23:48:38 +000012586 // Eliminate identity shuffles.
12587 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12588 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012589
Chris Lattner7b2e27922006-05-26 00:29:06 +000012590 // If the LHS is a shufflevector itself, see if we can combine it with this
12591 // one without producing an unusual shuffle. Here we are really conservative:
12592 // we are absolutely afraid of producing a shuffle mask not in the input
12593 // program, because the code gen may not be smart enough to turn a merged
12594 // shuffle into two specific shuffles: it may produce worse code. As such,
12595 // we only merge two shuffles if the result is one of the two input shuffle
12596 // masks. In this case, merging the shuffles just removes one instruction,
12597 // which we know is safe. This is good for things like turning:
12598 // (splat(splat)) -> splat.
12599 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12600 if (isa<UndefValue>(RHS)) {
12601 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12602
12603 std::vector<unsigned> NewMask;
12604 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12605 if (Mask[i] >= 2*e)
12606 NewMask.push_back(2*e);
12607 else
12608 NewMask.push_back(LHSMask[Mask[i]]);
12609
12610 // If the result mask is equal to the src shuffle or this shuffle mask, do
12611 // the replacement.
12612 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012613 unsigned LHSInNElts =
12614 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012615 std::vector<Constant*> Elts;
12616 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012617 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012618 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012619 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012620 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012621 }
12622 }
12623 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12624 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012625 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012626 }
12627 }
12628 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012629
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012630 return MadeChange ? &SVI : 0;
12631}
12632
12633
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012634
Chris Lattnerea1c4542004-12-08 23:43:58 +000012635
12636/// TryToSinkInstruction - Try to move the specified instruction from its
12637/// current block into the beginning of DestBlock, which can only happen if it's
12638/// safe to move the instruction past all of the instructions between it and the
12639/// end of its block.
12640static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12641 assert(I->hasOneUse() && "Invariants didn't hold!");
12642
Chris Lattner108e9022005-10-27 17:13:11 +000012643 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012644 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012645 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012646
Chris Lattnerea1c4542004-12-08 23:43:58 +000012647 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012648 if (isa<AllocaInst>(I) && I->getParent() ==
12649 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012650 return false;
12651
Chris Lattner96a52a62004-12-09 07:14:34 +000012652 // We can only sink load instructions if there is nothing between the load and
12653 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012654 if (I->mayReadFromMemory()) {
12655 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012656 Scan != E; ++Scan)
12657 if (Scan->mayWriteToMemory())
12658 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012659 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012660
Dan Gohman02dea8b2008-05-23 21:05:58 +000012661 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012662
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012663 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012664 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012665 ++NumSunkInst;
12666 return true;
12667}
12668
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012669
12670/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12671/// all reachable code to the worklist.
12672///
12673/// This has a couple of tricks to make the code faster and more powerful. In
12674/// particular, we constant fold and DCE instructions as we go, to avoid adding
12675/// them to the worklist (this significantly speeds up instcombine on code where
12676/// many instructions are dead or constant). Additionally, if we find a branch
12677/// whose condition is a known constant, we only visit the reachable successors.
12678///
12679static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012680 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012681 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012682 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012683 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012684 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000012685
12686 std::vector<Instruction*> InstrsForInstCombineWorklist;
12687 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012688
Chris Lattner2c7718a2007-03-23 19:17:18 +000012689 while (!Worklist.empty()) {
12690 BB = Worklist.back();
12691 Worklist.pop_back();
12692
12693 // We have now visited this block! If we've already been here, ignore it.
12694 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012695
Chris Lattner2c7718a2007-03-23 19:17:18 +000012696 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12697 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012698
Chris Lattner2c7718a2007-03-23 19:17:18 +000012699 // DCE instruction if trivially dead.
12700 if (isInstructionTriviallyDead(Inst)) {
12701 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012702 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012703 Inst->eraseFromParent();
12704 continue;
12705 }
12706
12707 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012708 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
12709 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12710 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12711 << *Inst << '\n');
12712 Inst->replaceAllUsesWith(C);
12713 ++NumConstProp;
12714 Inst->eraseFromParent();
12715 continue;
12716 }
Devang Patel7fe1dec2008-11-19 18:56:50 +000012717
Chris Lattner67f7d542009-10-12 03:58:40 +000012718 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012719 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012720
12721 // Recursively visit successors. If this is a branch or switch on a
12722 // constant, only visit the reachable successor.
12723 TerminatorInst *TI = BB->getTerminator();
12724 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12725 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12726 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012727 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012728 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012729 continue;
12730 }
12731 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12732 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12733 // See if this is an explicit destination.
12734 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12735 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012736 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012737 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012738 continue;
12739 }
12740
12741 // Otherwise it is the default destination.
12742 Worklist.push_back(SI->getSuccessor(0));
12743 continue;
12744 }
12745 }
12746
12747 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12748 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012749 }
Chris Lattner67f7d542009-10-12 03:58:40 +000012750
12751 // Once we've found all of the instructions to add to instcombine's worklist,
12752 // add them in reverse order. This way instcombine will visit from the top
12753 // of the function down. This jives well with the way that it adds all uses
12754 // of instructions to the worklist after doing a transformation, thus avoiding
12755 // some N^2 behavior in pathological cases.
12756 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12757 InstrsForInstCombineWorklist.size());
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012758}
12759
Chris Lattnerec9c3582007-03-03 02:04:50 +000012760bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012761 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012762
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012763 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12764 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012765
Chris Lattnerb3d59702005-07-07 20:40:38 +000012766 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012767 // Do a depth-first traversal of the function, populate the worklist with
12768 // the reachable instructions. Ignore blocks that are not reachable. Keep
12769 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012770 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012771 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012772
Chris Lattnerb3d59702005-07-07 20:40:38 +000012773 // Do a quick scan over the function. If we find any blocks that are
12774 // unreachable, remove any instructions inside of them. This prevents
12775 // the instcombine code from having to deal with some bad special cases.
12776 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12777 if (!Visited.count(BB)) {
12778 Instruction *Term = BB->getTerminator();
12779 while (Term != BB->begin()) { // Remove instrs bottom-up
12780 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012781
Chris Lattnerbdff5482009-08-23 04:37:46 +000012782 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012783 // A debug intrinsic shouldn't force another iteration if we weren't
12784 // going to do one without it.
12785 if (!isa<DbgInfoIntrinsic>(I)) {
12786 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012787 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000012788 }
Devang Patel228ebd02009-10-13 22:56:32 +000012789
12790
12791 // If I is not void type then replaceAllUsesWith undef.
12792 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000012793 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000012794 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012795 I->eraseFromParent();
12796 }
12797 }
12798 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012799
Chris Lattner873ff012009-08-30 05:55:36 +000012800 while (!Worklist.isEmpty()) {
12801 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012802 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012803
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012804 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012805 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012806 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012807 EraseInstFromFunction(*I);
12808 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012809 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012810 continue;
12811 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012812
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012813 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012814 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
12815 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12816 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012817
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012818 // Add operands to the worklist.
12819 ReplaceInstUsesWith(*I, C);
12820 ++NumConstProp;
12821 EraseInstFromFunction(*I);
12822 MadeIRChange = true;
12823 continue;
12824 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012825
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012826 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012827 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012828 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12829 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012830 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12831 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012832 if (NewC != CE) {
Dan Gohmane41a1152009-10-05 16:31:55 +000012833 *i = NewC;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012834 MadeIRChange = true;
Chris Lattner1e19d602009-01-31 07:04:22 +000012835 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012836 }
12837
Chris Lattnerea1c4542004-12-08 23:43:58 +000012838 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012839 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012840 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000012841 Instruction *UserInst = cast<Instruction>(I->use_back());
12842 BasicBlock *UserParent;
12843
12844 // Get the block the use occurs in.
12845 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12846 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12847 else
12848 UserParent = UserInst->getParent();
12849
Chris Lattnerea1c4542004-12-08 23:43:58 +000012850 if (UserParent != BB) {
12851 bool UserIsSuccessor = false;
12852 // See if the user is one of our successors.
12853 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12854 if (*SI == UserParent) {
12855 UserIsSuccessor = true;
12856 break;
12857 }
12858
12859 // If the user is one of our immediate successors, and if that successor
12860 // only has us as a predecessors (we'd have to split the critical edge
12861 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000012862 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012863 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012864 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012865 }
12866 }
12867
Chris Lattner74381062009-08-30 07:44:24 +000012868 // Now that we have an instruction, try combining it to simplify it.
12869 Builder->SetInsertPoint(I->getParent(), I);
12870
Reid Spencera9b81012007-03-26 17:44:01 +000012871#ifndef NDEBUG
12872 std::string OrigI;
12873#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012874 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000012875 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12876
Chris Lattner90ac28c2002-08-02 19:29:35 +000012877 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012878 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012879 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012880 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012881 DEBUG(errs() << "IC: Old = " << *I << '\n'
12882 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012883
Chris Lattnerf523d062004-06-09 05:08:07 +000012884 // Everything uses the new instruction now.
12885 I->replaceAllUsesWith(Result);
12886
12887 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012888 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012889 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012890
Chris Lattner6934a042007-02-11 01:23:03 +000012891 // Move the name to the new instruction first.
12892 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012893
12894 // Insert the new instruction into the basic block...
12895 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012896 BasicBlock::iterator InsertPos = I;
12897
12898 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12899 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12900 ++InsertPos;
12901
12902 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012903
Chris Lattner7a1e9242009-08-30 06:13:40 +000012904 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012905 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012906#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012907 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12908 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012909#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012910
Chris Lattner90ac28c2002-08-02 19:29:35 +000012911 // If the instruction was modified, it's possible that it is now dead.
12912 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012913 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012914 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012915 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012916 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012917 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012918 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012919 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012920 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012921 }
12922 }
12923
Chris Lattner873ff012009-08-30 05:55:36 +000012924 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012925 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012926}
12927
Chris Lattnerec9c3582007-03-03 02:04:50 +000012928
12929bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012930 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012931 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012932 TD = getAnalysisIfAvailable<TargetData>();
12933
Chris Lattner74381062009-08-30 07:44:24 +000012934
12935 /// Builder - This is an IRBuilder that automatically inserts new
12936 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012937 IRBuilder<true, TargetFolder, InstCombineIRInserter>
12938 TheBuilder(F.getContext(), TargetFolder(TD, F.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +000012939 InstCombineIRInserter(Worklist));
12940 Builder = &TheBuilder;
12941
Chris Lattnerec9c3582007-03-03 02:04:50 +000012942 bool EverMadeChange = false;
12943
12944 // Iterate while there is work to do.
12945 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012946 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012947 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012948
12949 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012950 return EverMadeChange;
12951}
12952
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012953FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012954 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012955}