blob: 1088684b0a6085fc5837d82c193c36dc7f8bf8ef [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
Torok Edwin0739bd02009-10-21 10:49:00 +00001988// Check whether all the operands of the PHI dominate the PHI node,
1989// knowing that the PHI's operands either dominate BB, or are defined in the BB.
1990static bool checkPHI(PHINode *PN, BasicBlock *BB)
1991{
1992 BasicBlock *phiBB = PN->getParent();
1993 for (unsigned i=0;i<PN->getNumIncomingValues();i++) {
1994 Instruction *I = dyn_cast<Instruction>(PN->getIncomingValue(i));
1995 if (!I)
1996 continue;
1997 BasicBlock *pBB = I->getParent();
1998 if (pBB == BB) {
1999 // another PHI in same BB is always before PN (PN is last phi).
2000 if (isa<PHINode>(I))
2001 continue;
2002 // An instruction in the same BB, and not a phi, this is after PN.
2003 return false;
2004 }
2005 if (phiBB == BB)
2006 continue;
2007 // We don't have dominator info, so just check that the instruction
2008 // is not defined in on of the BB on the unique path between BB and phiBB.
2009 // If there is no such unique path, or pBB equals to one of the BBs on that
2010 // path we know that this operand doesn't dominate the PHI node.
2011 BasicBlock *B = PN->getIncomingBlock(i);
2012 while ((B = B->getUniquePredecessor())) {
2013 if (pBB == B)
2014 return false;
2015 if (B == phiBB)
2016 break;
2017 }
2018 // No unique path -> doesn't dominate
2019 if (!B)
2020 return false;
2021 }
2022 return true;
2023}
Chris Lattner4e998b22004-09-29 05:07:12 +00002024
Chris Lattner5d1704d2009-09-27 19:57:57 +00002025/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2026/// has a PHI node as operand #0, see if we can fold the instruction into the
2027/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002028///
2029/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2030/// that would normally be unprofitable because they strongly encourage jump
2031/// threading.
2032Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2033 bool AllowAggressive) {
2034 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002035 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002036 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002037 if (NumPHIValues == 0 ||
2038 // We normally only transform phis with a single use, unless we're trying
2039 // hard to make jump threading happen.
2040 (!PN->hasOneUse() && !AllowAggressive))
2041 return 0;
2042
2043
Chris Lattner5d1704d2009-09-27 19:57:57 +00002044 // Check to see if all of the operands of the PHI are simple constants
2045 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002046 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2047 // bail out. We don't do arbitrary constant expressions here because moving
2048 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002049 BasicBlock *NonConstBB = 0;
2050 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002051 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2052 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002053 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002054 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002055 NonConstBB = PN->getIncomingBlock(i);
2056
2057 // If the incoming non-constant value is in I's block, we have an infinite
2058 // loop.
2059 if (NonConstBB == I.getParent())
2060 return 0;
2061 }
2062
2063 // If there is exactly one non-constant value, we can insert a copy of the
2064 // operation in that block. However, if this is a critical edge, we would be
2065 // inserting the computation one some other paths (e.g. inside a loop). Only
2066 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002067 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002068 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2069 if (!BI || !BI->isUnconditional()) return 0;
2070 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002071
2072 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002073 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002074 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Torok Edwin0739bd02009-10-21 10:49:00 +00002075 // We must the PHI node as the last PHI, because it may use one of the other
2076 // PHIs.
2077 BasicBlock::iterator BBIt = PN;
2078 while (isa<PHINode>(BBIt)) ++BBIt;
2079 InsertNewInstBefore(NewPN, *BBIt);
Chris Lattner4e998b22004-09-29 05:07:12 +00002080
Torok Edwin0739bd02009-10-21 10:49:00 +00002081 SmallVector<Instruction*, 2> tmpWorklist;
Chris Lattner4e998b22004-09-29 05:07:12 +00002082 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002083 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2084 // We only currently try to fold the condition of a select when it is a phi,
2085 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002086 Value *TrueV = SI->getTrueValue();
2087 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002088 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002089 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002090 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002091 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2092 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002093 Value *InV = 0;
2094 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002095 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002096 } else {
2097 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002098 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2099 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002100 "phitmp", NonConstBB->getTerminator());
Torok Edwin0739bd02009-10-21 10:49:00 +00002101 tmpWorklist.push_back(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002102 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002103 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002104 }
2105 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002106 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002107 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002108 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002109 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002110 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002111 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002112 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002113 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002114 } else {
2115 assert(PN->getIncomingBlock(i) == NonConstBB);
2116 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002117 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002118 PN->getIncomingValue(i), C, "phitmp",
2119 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002120 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002121 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002122 CI->getPredicate(),
2123 PN->getIncomingValue(i), C, "phitmp",
2124 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002125 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002126 llvm_unreachable("Unknown binop!");
Torok Edwin0739bd02009-10-21 10:49:00 +00002127 tmpWorklist.push_back(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002128 }
2129 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002130 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002131 } else {
2132 CastInst *CI = cast<CastInst>(&I);
2133 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002134 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002135 Value *InV;
2136 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002137 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002138 } else {
2139 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002140 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002141 I.getType(), "phitmp",
2142 NonConstBB->getTerminator());
Torok Edwin0739bd02009-10-21 10:49:00 +00002143 tmpWorklist.push_back(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002144 }
2145 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002146 }
2147 }
Torok Edwin0739bd02009-10-21 10:49:00 +00002148 // The PHI's operands must dominate the PHI, if we can't prove that
2149 // undo this transformation.
2150 if (!checkPHI(NewPN, I.getParent())) {
2151 Worklist.Remove(NewPN);
2152 NewPN->eraseFromParent();
2153 while (!tmpWorklist.empty()) {
2154 tmpWorklist.pop_back_val()->eraseFromParent();
2155 }
2156 return 0;
2157 }
2158 while (!tmpWorklist.empty()) {
2159 Worklist.Add(tmpWorklist.pop_back_val());
2160 }
2161 NewPN->takeName(PN);
2162 Worklist.Add(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002163 return ReplaceInstUsesWith(I, NewPN);
2164}
2165
Chris Lattner2454a2e2008-01-29 06:52:45 +00002166
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002167/// WillNotOverflowSignedAdd - Return true if we can prove that:
2168/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2169/// This basically requires proving that the add in the original type would not
2170/// overflow to change the sign bit or have a carry out.
2171bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2172 // There are different heuristics we can use for this. Here are some simple
2173 // ones.
2174
2175 // Add has the property that adding any two 2's complement numbers can only
2176 // have one carry bit which can change a sign. As such, if LHS and RHS each
2177 // have at least two sign bits, we know that the addition of the two values will
2178 // sign extend fine.
2179 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2180 return true;
2181
2182
2183 // If one of the operands only has one non-zero bit, and if the other operand
2184 // has a known-zero bit in a more significant place than it (not including the
2185 // sign bit) the ripple may go up to and fill the zero, but won't change the
2186 // sign. For example, (X & ~4) + 1.
2187
2188 // TODO: Implement.
2189
2190 return false;
2191}
2192
Chris Lattner2454a2e2008-01-29 06:52:45 +00002193
Chris Lattner7e708292002-06-25 16:13:24 +00002194Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002195 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002196 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002197
Chris Lattner66331a42004-04-10 22:01:55 +00002198 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002199 // X + undef -> undef
2200 if (isa<UndefValue>(RHS))
2201 return ReplaceInstUsesWith(I, RHS);
2202
Chris Lattner66331a42004-04-10 22:01:55 +00002203 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002204 if (RHSC->isNullValue())
2205 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002206
Chris Lattner66331a42004-04-10 22:01:55 +00002207 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002208 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002209 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002210 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002211 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002212 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002213
2214 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2215 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002216 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002217 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002218
Eli Friedman709b33d2009-07-13 22:27:52 +00002219 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002220 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002221 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002222 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002223 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002224
2225 if (isa<PHINode>(LHS))
2226 if (Instruction *NV = FoldOpIntoPhi(I))
2227 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002228
Chris Lattner4f637d42006-01-06 17:59:59 +00002229 ConstantInt *XorRHS = 0;
2230 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002231 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002232 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002233 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002234 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002235
Zhou Sheng4351c642007-04-02 08:20:41 +00002236 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002237 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2238 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002239 do {
2240 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002241 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2242 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002243 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2244 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002245 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002246 if (!MaskedValueIsZero(XorLHS,
2247 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002248 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002249 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002250 }
2251 }
2252 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002253 C0080Val = APIntOps::lshr(C0080Val, Size);
2254 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2255 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002256
Reid Spencer35c38852007-03-28 01:36:16 +00002257 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002258 // with funny bit widths then this switch statement should be removed. It
2259 // is just here to get the size of the "middle" type back up to something
2260 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002261 const Type *MiddleType = 0;
2262 switch (Size) {
2263 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002264 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2265 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2266 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002267 }
2268 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002269 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002270 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002271 }
2272 }
Chris Lattner66331a42004-04-10 22:01:55 +00002273 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002274
Owen Anderson1d0be152009-08-13 21:58:54 +00002275 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002276 return BinaryOperator::CreateXor(LHS, RHS);
2277
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002278 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002279 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002280 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002281 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002282
2283 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2284 if (RHSI->getOpcode() == Instruction::Sub)
2285 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2286 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2287 }
2288 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2289 if (LHSI->getOpcode() == Instruction::Sub)
2290 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2291 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2292 }
Robert Bocchino71698282004-07-27 21:02:21 +00002293 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002294
Chris Lattner5c4afb92002-05-08 22:46:53 +00002295 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002296 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002297 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002298 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002299 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002300 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002301 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002302 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002303 }
2304
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002305 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002306 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002307
2308 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002309 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002310 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002311 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002312
Misha Brukmanfd939082005-04-21 23:48:37 +00002313
Chris Lattner50af16a2004-11-13 19:50:12 +00002314 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002315 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002316 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002317 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002318
2319 // X*C1 + X*C2 --> X * (C1+C2)
2320 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002321 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002322 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002323 }
2324
2325 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002326 if (dyn_castFoldableMul(RHS, C2) == LHS)
2327 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002328
Chris Lattnere617c9e2007-01-05 02:17:46 +00002329 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002330 if (dyn_castNotVal(LHS) == RHS ||
2331 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002332 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002333
Chris Lattnerad3448c2003-02-18 19:57:07 +00002334
Chris Lattner564a7272003-08-13 19:01:45 +00002335 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002336 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2337 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002338 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002339
2340 // A+B --> A|B iff A and B have no bits set in common.
2341 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2342 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2343 APInt LHSKnownOne(IT->getBitWidth(), 0);
2344 APInt LHSKnownZero(IT->getBitWidth(), 0);
2345 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2346 if (LHSKnownZero != 0) {
2347 APInt RHSKnownOne(IT->getBitWidth(), 0);
2348 APInt RHSKnownZero(IT->getBitWidth(), 0);
2349 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2350
2351 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002352 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002353 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002354 }
2355 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002356
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002357 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002358 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002359 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002360 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2361 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002362 if (W != Y) {
2363 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002364 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002365 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002366 std::swap(W, X);
2367 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002368 std::swap(Y, Z);
2369 std::swap(W, X);
2370 }
2371 }
2372
2373 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002374 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002375 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002376 }
2377 }
2378 }
2379
Chris Lattner6b032052003-10-02 15:11:26 +00002380 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002381 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002382 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002383 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002384
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002385 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002386 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002387 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002388 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002389 if (Anded == CRHS) {
2390 // See if all bits from the first bit set in the Add RHS up are included
2391 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002392 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002393
2394 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002395 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002396
2397 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002398 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002399
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002400 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2401 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002402 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002403 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002404 }
2405 }
2406 }
2407
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002408 // Try to fold constant add into select arguments.
2409 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002410 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002411 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002412 }
2413
Chris Lattner42790482007-12-20 01:56:58 +00002414 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002415 {
2416 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002417 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002418 if (!SI) {
2419 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002420 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002421 }
Chris Lattner42790482007-12-20 01:56:58 +00002422 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002423 Value *TV = SI->getTrueValue();
2424 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002425 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002426
2427 // Can we fold the add into the argument of the select?
2428 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002429 if (match(FV, m_Zero()) &&
2430 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002431 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002432 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002433 if (match(TV, m_Zero()) &&
2434 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002435 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002436 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002437 }
2438 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002439
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002440 // Check for (add (sext x), y), see if we can merge this into an
2441 // integer add followed by a sext.
2442 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2443 // (add (sext x), cst) --> (sext (add x, cst'))
2444 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2445 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002446 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002447 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002448 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002449 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2450 // Insert the new, smaller add.
Chris Lattner74381062009-08-30 07:44:24 +00002451 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2452 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002453 return new SExtInst(NewAdd, I.getType());
2454 }
2455 }
2456
2457 // (add (sext x), (sext y)) --> (sext (add int x, y))
2458 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2459 // Only do this if x/y have the same type, if at last one of them has a
2460 // single use (so we don't increase the number of sexts), and if the
2461 // integer add will not overflow.
2462 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2463 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2464 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2465 RHSConv->getOperand(0))) {
2466 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002467 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2468 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002469 return new SExtInst(NewAdd, I.getType());
2470 }
2471 }
2472 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002473
2474 return Changed ? &I : 0;
2475}
2476
2477Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2478 bool Changed = SimplifyCommutative(I);
2479 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2480
2481 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2482 // X + 0 --> X
2483 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002484 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002485 (I.getType())->getValueAPF()))
2486 return ReplaceInstUsesWith(I, LHS);
2487 }
2488
2489 if (isa<PHINode>(LHS))
2490 if (Instruction *NV = FoldOpIntoPhi(I))
2491 return NV;
2492 }
2493
2494 // -A + B --> B - A
2495 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002496 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002497 return BinaryOperator::CreateFSub(RHS, LHSV);
2498
2499 // A + -B --> A - B
2500 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002501 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002502 return BinaryOperator::CreateFSub(LHS, V);
2503
2504 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2505 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2506 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2507 return ReplaceInstUsesWith(I, LHS);
2508
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002509 // Check for (add double (sitofp x), y), see if we can merge this into an
2510 // integer add followed by a promotion.
2511 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2512 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2513 // ... if the constant fits in the integer value. This is useful for things
2514 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2515 // requires a constant pool load, and generally allows the add to be better
2516 // instcombined.
2517 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2518 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002519 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002520 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002521 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002522 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2523 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002524 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2525 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002526 return new SIToFPInst(NewAdd, I.getType());
2527 }
2528 }
2529
2530 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2531 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2532 // Only do this if x/y have the same type, if at last one of them has a
2533 // single use (so we don't increase the number of int->fp conversions),
2534 // and if the integer add will not overflow.
2535 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2536 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2537 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2538 RHSConv->getOperand(0))) {
2539 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002540 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2541 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002542 return new SIToFPInst(NewAdd, I.getType());
2543 }
2544 }
2545 }
2546
Chris Lattner7e708292002-06-25 16:13:24 +00002547 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002548}
2549
Chris Lattner7e708292002-06-25 16:13:24 +00002550Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002551 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002552
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002553 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002554 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002555
Chris Lattner233f7dc2002-08-12 21:17:25 +00002556 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002557 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002558 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002559
Chris Lattnere87597f2004-10-16 18:11:37 +00002560 if (isa<UndefValue>(Op0))
2561 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2562 if (isa<UndefValue>(Op1))
2563 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2564
Chris Lattnerd65460f2003-11-05 01:06:05 +00002565 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2566 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002567 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002568 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002569
Chris Lattnerd65460f2003-11-05 01:06:05 +00002570 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002571 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002572 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002573 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002574
Chris Lattner76b7a062007-01-15 07:02:54 +00002575 // -(X >>u 31) -> (X >>s 31)
2576 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002577 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002578 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002579 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002580 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002581 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002582 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002583 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002584 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002585 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002586 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002587 }
2588 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002589 }
2590 else if (SI->getOpcode() == Instruction::AShr) {
2591 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2592 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002593 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002594 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002595 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002596 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002597 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002598 }
2599 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002600 }
2601 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002602 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002603
2604 // Try to fold constant sub into select arguments.
2605 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002606 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002607 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002608
2609 // C - zext(bool) -> bool ? C - 1 : C
2610 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002611 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002612 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002613 }
2614
Owen Anderson1d0be152009-08-13 21:58:54 +00002615 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002616 return BinaryOperator::CreateXor(Op0, Op1);
2617
Chris Lattner43d84d62005-04-07 16:15:25 +00002618 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002619 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002620 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002621 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002622 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002623 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002624 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002625 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002626 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2627 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2628 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002629 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002630 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002631 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002632 }
2633
Chris Lattnerfd059242003-10-15 16:48:29 +00002634 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002635 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2636 // is not used by anyone else...
2637 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002638 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002639 // Swap the two operands of the subexpr...
2640 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2641 Op1I->setOperand(0, IIOp1);
2642 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002643
Chris Lattnera2881962003-02-18 19:28:33 +00002644 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002645 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002646 }
2647
2648 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2649 //
2650 if (Op1I->getOpcode() == Instruction::And &&
2651 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2652 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2653
Chris Lattner74381062009-08-30 07:44:24 +00002654 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002655 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002656 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002657
Reid Spencerac5209e2006-10-16 23:08:08 +00002658 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002659 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002660 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002661 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002662 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002663 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002664 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002665
Chris Lattnerad3448c2003-02-18 19:57:07 +00002666 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002667 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002668 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002669 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002670 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002671 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002672 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002673 }
Chris Lattner40371712002-05-09 01:29:19 +00002674 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002675 }
Chris Lattnera2881962003-02-18 19:28:33 +00002676
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002677 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2678 if (Op0I->getOpcode() == Instruction::Add) {
2679 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2680 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2681 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2682 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2683 } else if (Op0I->getOpcode() == Instruction::Sub) {
2684 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002685 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002686 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002687 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002688 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002689
Chris Lattner50af16a2004-11-13 19:50:12 +00002690 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002691 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002692 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002693 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002694
Chris Lattner50af16a2004-11-13 19:50:12 +00002695 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002696 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002697 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002698 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002699 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002700}
2701
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002702Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2703 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2704
2705 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002706 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002707 return BinaryOperator::CreateFAdd(Op0, V);
2708
2709 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2710 if (Op1I->getOpcode() == Instruction::FAdd) {
2711 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002712 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002713 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002714 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002715 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002716 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002717 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002718 }
2719
2720 return 0;
2721}
2722
Chris Lattnera0141b92007-07-15 20:42:37 +00002723/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2724/// comparison only checks the sign bit. If it only checks the sign bit, set
2725/// TrueIfSigned if the result of the comparison is true when the input value is
2726/// signed.
2727static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2728 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002729 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002730 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2731 TrueIfSigned = true;
2732 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002733 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2734 TrueIfSigned = true;
2735 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002736 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2737 TrueIfSigned = false;
2738 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002739 case ICmpInst::ICMP_UGT:
2740 // True if LHS u> RHS and RHS == high-bit-mask - 1
2741 TrueIfSigned = true;
2742 return RHS->getValue() ==
2743 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2744 case ICmpInst::ICMP_UGE:
2745 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2746 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002747 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002748 default:
2749 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002750 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002751}
2752
Chris Lattner7e708292002-06-25 16:13:24 +00002753Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002754 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002755 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002756
Chris Lattnera2498472009-10-11 21:36:10 +00002757 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002758 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002759
Chris Lattner8af304a2009-10-11 07:53:15 +00002760 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002761 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2762 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002763
2764 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002765 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002766 if (SI->getOpcode() == Instruction::Shl)
2767 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002768 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002769 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002770
Zhou Sheng843f07672007-04-19 05:39:12 +00002771 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002772 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002773 if (CI->equalsInt(1)) // X * 1 == X
2774 return ReplaceInstUsesWith(I, Op0);
2775 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002776 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002777
Zhou Sheng97b52c22007-03-29 01:57:21 +00002778 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002779 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002780 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002781 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002782 }
Chris Lattnera2498472009-10-11 21:36:10 +00002783 } else if (isa<VectorType>(Op1C->getType())) {
2784 if (Op1C->isNullValue())
2785 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002786
Chris Lattnera2498472009-10-11 21:36:10 +00002787 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002788 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002789 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002790
2791 // As above, vector X*splat(1.0) -> X in all defined cases.
2792 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002793 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2794 if (CI->equalsInt(1))
2795 return ReplaceInstUsesWith(I, Op0);
2796 }
2797 }
Chris Lattnera2881962003-02-18 19:28:33 +00002798 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002799
2800 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2801 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002802 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002803 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00002804 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2805 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002806 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002807
2808 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002809
2810 // Try to fold constant mul into select arguments.
2811 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002812 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002813 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002814
2815 if (isa<PHINode>(Op0))
2816 if (Instruction *NV = FoldOpIntoPhi(I))
2817 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002818 }
2819
Dan Gohman186a6362009-08-12 16:04:34 +00002820 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002821 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002822 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002823
Nick Lewycky0c730792008-11-21 07:33:58 +00002824 // (X / Y) * Y = X - (X % Y)
2825 // (X / Y) * -Y = (X % Y) - X
2826 {
Chris Lattnera2498472009-10-11 21:36:10 +00002827 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00002828 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2829 if (!BO ||
2830 (BO->getOpcode() != Instruction::UDiv &&
2831 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00002832 Op1C = Op0;
2833 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002834 }
Chris Lattnera2498472009-10-11 21:36:10 +00002835 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00002836 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002837 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00002838 (BO->getOpcode() == Instruction::UDiv ||
2839 BO->getOpcode() == Instruction::SDiv)) {
2840 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2841
Dan Gohmanfa94b942009-08-12 16:33:09 +00002842 // If the division is exact, X % Y is zero.
2843 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2844 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00002845 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00002846 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00002847 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00002848 }
2849
Chris Lattner74381062009-08-30 07:44:24 +00002850 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002851 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002852 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002853 else
Chris Lattner74381062009-08-30 07:44:24 +00002854 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002855 Rem->takeName(BO);
2856
Chris Lattnera2498472009-10-11 21:36:10 +00002857 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00002858 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002859 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002860 }
2861 }
2862
Chris Lattner8af304a2009-10-11 07:53:15 +00002863 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00002864 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00002865 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002866
Chris Lattner8af304a2009-10-11 07:53:15 +00002867 // X*(1 << Y) --> X << Y
2868 // (1 << Y)*X --> X << Y
2869 {
2870 Value *Y;
2871 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00002872 return BinaryOperator::CreateShl(Op1, Y);
2873 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00002874 return BinaryOperator::CreateShl(Op0, Y);
2875 }
2876
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002877 // If one of the operands of the multiply is a cast from a boolean value, then
2878 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00002879 // X * Y (where Y is 0 or 1) -> X & (0-Y)
2880 if (!isa<VectorType>(I.getType())) {
2881 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00002882 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00002883
Chris Lattnerd2c58362009-10-11 21:29:45 +00002884 Value *BoolCast = 0, *OtherOp = 0;
2885 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00002886 BoolCast = Op0, OtherOp = Op1;
2887 else if (MaskedValueIsZero(Op1, Negative2))
2888 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00002889
Chris Lattner0036e3a2009-10-11 21:22:21 +00002890 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00002891 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2892 BoolCast, "tmp");
2893 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002894 }
2895 }
2896
Chris Lattner7e708292002-06-25 16:13:24 +00002897 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002898}
2899
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002900Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2901 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002902 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002903
2904 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00002905 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2906 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002907 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2908 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2909 if (Op1F->isExactlyValue(1.0))
2910 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00002911 } else if (isa<VectorType>(Op1C->getType())) {
2912 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002913 // As above, vector X*splat(1.0) -> X in all defined cases.
2914 if (Constant *Splat = Op1V->getSplatValue()) {
2915 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2916 if (F->isExactlyValue(1.0))
2917 return ReplaceInstUsesWith(I, Op0);
2918 }
2919 }
2920 }
2921
2922 // Try to fold constant mul into select arguments.
2923 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2924 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2925 return R;
2926
2927 if (isa<PHINode>(Op0))
2928 if (Instruction *NV = FoldOpIntoPhi(I))
2929 return NV;
2930 }
2931
Dan Gohman186a6362009-08-12 16:04:34 +00002932 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002933 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002934 return BinaryOperator::CreateFMul(Op0v, Op1v);
2935
2936 return Changed ? &I : 0;
2937}
2938
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002939/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2940/// instruction.
2941bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2942 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2943
2944 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2945 int NonNullOperand = -1;
2946 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2947 if (ST->isNullValue())
2948 NonNullOperand = 2;
2949 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2950 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2951 if (ST->isNullValue())
2952 NonNullOperand = 1;
2953
2954 if (NonNullOperand == -1)
2955 return false;
2956
2957 Value *SelectCond = SI->getOperand(0);
2958
2959 // Change the div/rem to use 'Y' instead of the select.
2960 I.setOperand(1, SI->getOperand(NonNullOperand));
2961
2962 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2963 // problem. However, the select, or the condition of the select may have
2964 // multiple uses. Based on our knowledge that the operand must be non-zero,
2965 // propagate the known value for the select into other uses of it, and
2966 // propagate a known value of the condition into its other users.
2967
2968 // If the select and condition only have a single use, don't bother with this,
2969 // early exit.
2970 if (SI->use_empty() && SelectCond->hasOneUse())
2971 return true;
2972
2973 // Scan the current block backward, looking for other uses of SI.
2974 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2975
2976 while (BBI != BBFront) {
2977 --BBI;
2978 // If we found a call to a function, we can't assume it will return, so
2979 // information from below it cannot be propagated above it.
2980 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2981 break;
2982
2983 // Replace uses of the select or its condition with the known values.
2984 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2985 I != E; ++I) {
2986 if (*I == SI) {
2987 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002988 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002989 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002990 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2991 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002992 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002993 }
2994 }
2995
2996 // If we past the instruction, quit looking for it.
2997 if (&*BBI == SI)
2998 SI = 0;
2999 if (&*BBI == SelectCond)
3000 SelectCond = 0;
3001
3002 // If we ran out of things to eliminate, break out of the loop.
3003 if (SelectCond == 0 && SI == 0)
3004 break;
3005
3006 }
3007 return true;
3008}
3009
3010
Reid Spencer1628cec2006-10-26 06:15:43 +00003011/// This function implements the transforms on div instructions that work
3012/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3013/// used by the visitors to those instructions.
3014/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003015Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003016 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003017
Chris Lattner50b2ca42008-02-19 06:12:18 +00003018 // undef / X -> 0 for integer.
3019 // undef / X -> undef for FP (the undef could be a snan).
3020 if (isa<UndefValue>(Op0)) {
3021 if (Op0->getType()->isFPOrFPVector())
3022 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00003023 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003024 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003025
3026 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003027 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003028 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003029
Reid Spencer1628cec2006-10-26 06:15:43 +00003030 return 0;
3031}
Misha Brukmanfd939082005-04-21 23:48:37 +00003032
Reid Spencer1628cec2006-10-26 06:15:43 +00003033/// This function implements the transforms common to both integer division
3034/// instructions (udiv and sdiv). It is called by the visitors to those integer
3035/// division instructions.
3036/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003037Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003038 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3039
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003040 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003041 if (Op0 == Op1) {
3042 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003043 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003044 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003045 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003046 }
3047
Owen Andersoneed707b2009-07-24 23:12:02 +00003048 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003049 return ReplaceInstUsesWith(I, CI);
3050 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003051
Reid Spencer1628cec2006-10-26 06:15:43 +00003052 if (Instruction *Common = commonDivTransforms(I))
3053 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003054
3055 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3056 // This does not apply for fdiv.
3057 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3058 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003059
3060 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3061 // div X, 1 == X
3062 if (RHS->equalsInt(1))
3063 return ReplaceInstUsesWith(I, Op0);
3064
3065 // (X / C1) / C2 -> X / (C1*C2)
3066 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3067 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3068 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003069 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003070 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003071 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003072 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003073 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003074 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003075 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003076
Reid Spencerbca0e382007-03-23 20:05:17 +00003077 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003078 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3079 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3080 return R;
3081 if (isa<PHINode>(Op0))
3082 if (Instruction *NV = FoldOpIntoPhi(I))
3083 return NV;
3084 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003085 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003086
Chris Lattnera2881962003-02-18 19:28:33 +00003087 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003088 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003089 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003090 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003091
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003092 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003093 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003094 return ReplaceInstUsesWith(I, Op0);
3095
Nick Lewycky895f0852008-11-27 20:21:08 +00003096 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3097 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3098 // div X, 1 == X
3099 if (X->isOne())
3100 return ReplaceInstUsesWith(I, Op0);
3101 }
3102
Reid Spencer1628cec2006-10-26 06:15:43 +00003103 return 0;
3104}
3105
3106Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3107 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3108
3109 // Handle the integer div common cases
3110 if (Instruction *Common = commonIDivTransforms(I))
3111 return Common;
3112
Reid Spencer1628cec2006-10-26 06:15:43 +00003113 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003114 // X udiv C^2 -> X >> C
3115 // Check to see if this is an unsigned division with an exact power of 2,
3116 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003117 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003118 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003119 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003120
3121 // X udiv C, where C >= signbit
3122 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003123 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003124 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003125 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003126 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003127 }
3128
3129 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003130 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003131 if (RHSI->getOpcode() == Instruction::Shl &&
3132 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003133 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003134 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003135 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003136 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003137 if (uint32_t C2 = C1.logBase2())
3138 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003139 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003140 }
3141 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003142 }
3143
Reid Spencer1628cec2006-10-26 06:15:43 +00003144 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3145 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003146 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003147 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003148 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003149 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003150 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003151 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003152 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003153 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003154 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003155 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003156
3157 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003158 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003159 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003160
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003161 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003162 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003163 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003164 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003165 return 0;
3166}
3167
Reid Spencer1628cec2006-10-26 06:15:43 +00003168Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3169 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3170
3171 // Handle the integer div common cases
3172 if (Instruction *Common = commonIDivTransforms(I))
3173 return Common;
3174
3175 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3176 // sdiv X, -1 == -X
3177 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003178 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003179
Dan Gohmanfa94b942009-08-12 16:33:09 +00003180 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003181 if (cast<SDivOperator>(&I)->isExact() &&
3182 RHS->getValue().isNonNegative() &&
3183 RHS->getValue().isPowerOf2()) {
3184 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3185 RHS->getValue().exactLogBase2());
3186 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3187 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003188
3189 // -X/C --> X/-C provided the negation doesn't overflow.
3190 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3191 if (isa<Constant>(Sub->getOperand(0)) &&
3192 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003193 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003194 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3195 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003196 }
3197
3198 // If the sign bits of both operands are zero (i.e. we can prove they are
3199 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003200 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003201 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003202 if (MaskedValueIsZero(Op0, Mask)) {
3203 if (MaskedValueIsZero(Op1, Mask)) {
3204 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3205 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3206 }
3207 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003208 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003209 ShiftedInt->getValue().isPowerOf2()) {
3210 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3211 // Safe because the only negative value (1 << Y) can take on is
3212 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3213 // the sign bit set.
3214 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3215 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003216 }
Eli Friedman8be17392009-07-18 09:53:21 +00003217 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003218
3219 return 0;
3220}
3221
3222Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3223 return commonDivTransforms(I);
3224}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003225
Reid Spencer0a783f72006-11-02 01:53:59 +00003226/// This function implements the transforms on rem instructions that work
3227/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3228/// is used by the visitors to those instructions.
3229/// @brief Transforms common to all three rem instructions
3230Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003231 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003232
Chris Lattner50b2ca42008-02-19 06:12:18 +00003233 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3234 if (I.getType()->isFPOrFPVector())
3235 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003236 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003237 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003238 if (isa<UndefValue>(Op1))
3239 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003240
3241 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003242 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3243 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003244
Reid Spencer0a783f72006-11-02 01:53:59 +00003245 return 0;
3246}
3247
3248/// This function implements the transforms common to both integer remainder
3249/// instructions (urem and srem). It is called by the visitors to those integer
3250/// remainder instructions.
3251/// @brief Common integer remainder transforms
3252Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3253 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3254
3255 if (Instruction *common = commonRemTransforms(I))
3256 return common;
3257
Dale Johannesened6af242009-01-21 00:35:19 +00003258 // 0 % X == 0 for integer, we don't need to preserve faults!
3259 if (Constant *LHS = dyn_cast<Constant>(Op0))
3260 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003261 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003262
Chris Lattner857e8cd2004-12-12 21:48:58 +00003263 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003264 // X % 0 == undef, we don't need to preserve faults!
3265 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003266 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003267
Chris Lattnera2881962003-02-18 19:28:33 +00003268 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003269 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003270
Chris Lattner97943922006-02-28 05:49:21 +00003271 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3272 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3273 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3274 return R;
3275 } else if (isa<PHINode>(Op0I)) {
3276 if (Instruction *NV = FoldOpIntoPhi(I))
3277 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003278 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003279
3280 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003281 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003282 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003283 }
Chris Lattnera2881962003-02-18 19:28:33 +00003284 }
3285
Reid Spencer0a783f72006-11-02 01:53:59 +00003286 return 0;
3287}
3288
3289Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3290 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3291
3292 if (Instruction *common = commonIRemTransforms(I))
3293 return common;
3294
3295 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3296 // X urem C^2 -> X and C
3297 // Check to see if this is an unsigned remainder with an exact power of 2,
3298 // if so, convert to a bitwise and.
3299 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003300 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003301 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003302 }
3303
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003304 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003305 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3306 if (RHSI->getOpcode() == Instruction::Shl &&
3307 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003308 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003309 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003310 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003311 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003312 }
3313 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003314 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003315
Reid Spencer0a783f72006-11-02 01:53:59 +00003316 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3317 // where C1&C2 are powers of two.
3318 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3319 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3320 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3321 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003322 if ((STO->getValue().isPowerOf2()) &&
3323 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003324 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3325 SI->getName()+".t");
3326 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3327 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003328 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003329 }
3330 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003331 }
3332
Chris Lattner3f5b8772002-05-06 16:14:14 +00003333 return 0;
3334}
3335
Reid Spencer0a783f72006-11-02 01:53:59 +00003336Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3337 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3338
Dan Gohmancff55092007-11-05 23:16:33 +00003339 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003340 if (Instruction *Common = commonIRemTransforms(I))
3341 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003342
Dan Gohman186a6362009-08-12 16:04:34 +00003343 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003344 if (!isa<Constant>(RHSNeg) ||
3345 (isa<ConstantInt>(RHSNeg) &&
3346 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003347 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003348 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003349 I.setOperand(1, RHSNeg);
3350 return &I;
3351 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003352
Dan Gohmancff55092007-11-05 23:16:33 +00003353 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003354 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003355 if (I.getType()->isInteger()) {
3356 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3357 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3358 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003359 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003360 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003361 }
3362
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003363 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003364 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3365 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003366
Nick Lewycky9dce8732008-12-20 16:48:00 +00003367 bool hasNegative = false;
3368 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3369 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3370 if (RHS->getValue().isNegative())
3371 hasNegative = true;
3372
3373 if (hasNegative) {
3374 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003375 for (unsigned i = 0; i != VWidth; ++i) {
3376 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3377 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003378 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003379 else
3380 Elts[i] = RHS;
3381 }
3382 }
3383
Owen Andersonaf7ec972009-07-28 21:19:26 +00003384 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003385 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003386 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003387 I.setOperand(1, NewRHSV);
3388 return &I;
3389 }
3390 }
3391 }
3392
Reid Spencer0a783f72006-11-02 01:53:59 +00003393 return 0;
3394}
3395
3396Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003397 return commonRemTransforms(I);
3398}
3399
Chris Lattner457dd822004-06-09 07:59:58 +00003400// isOneBitSet - Return true if there is exactly one bit set in the specified
3401// constant.
3402static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003403 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003404}
3405
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003406// isHighOnes - Return true if the constant is of the form 1+0+.
3407// This is the same as lowones(~X).
3408static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003409 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003410}
3411
Reid Spencere4d87aa2006-12-23 06:05:41 +00003412/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003413/// are carefully arranged to allow folding of expressions such as:
3414///
3415/// (A < B) | (A > B) --> (A != B)
3416///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003417/// Note that this is only valid if the first and second predicates have the
3418/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003419///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003420/// Three bits are used to represent the condition, as follows:
3421/// 0 A > B
3422/// 1 A == B
3423/// 2 A < B
3424///
3425/// <=> Value Definition
3426/// 000 0 Always false
3427/// 001 1 A > B
3428/// 010 2 A == B
3429/// 011 3 A >= B
3430/// 100 4 A < B
3431/// 101 5 A != B
3432/// 110 6 A <= B
3433/// 111 7 Always true
3434///
3435static unsigned getICmpCode(const ICmpInst *ICI) {
3436 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003437 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003438 case ICmpInst::ICMP_UGT: return 1; // 001
3439 case ICmpInst::ICMP_SGT: return 1; // 001
3440 case ICmpInst::ICMP_EQ: return 2; // 010
3441 case ICmpInst::ICMP_UGE: return 3; // 011
3442 case ICmpInst::ICMP_SGE: return 3; // 011
3443 case ICmpInst::ICMP_ULT: return 4; // 100
3444 case ICmpInst::ICMP_SLT: return 4; // 100
3445 case ICmpInst::ICMP_NE: return 5; // 101
3446 case ICmpInst::ICMP_ULE: return 6; // 110
3447 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003448 // True -> 7
3449 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003450 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003451 return 0;
3452 }
3453}
3454
Evan Cheng8db90722008-10-14 17:15:11 +00003455/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3456/// predicate into a three bit mask. It also returns whether it is an ordered
3457/// predicate by reference.
3458static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3459 isOrdered = false;
3460 switch (CC) {
3461 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3462 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003463 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3464 case FCmpInst::FCMP_UGT: return 1; // 001
3465 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3466 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003467 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3468 case FCmpInst::FCMP_UGE: return 3; // 011
3469 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3470 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003471 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3472 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003473 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3474 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003475 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003476 default:
3477 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003478 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003479 return 0;
3480 }
3481}
3482
Reid Spencere4d87aa2006-12-23 06:05:41 +00003483/// getICmpValue - This is the complement of getICmpCode, which turns an
3484/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003485/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003486/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003487static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003488 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003489 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003490 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003491 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003492 case 1:
3493 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003494 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003495 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003496 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3497 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003498 case 3:
3499 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003500 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003501 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003502 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003503 case 4:
3504 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003505 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003506 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003507 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3508 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003509 case 6:
3510 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003511 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003512 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003513 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003514 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003515 }
3516}
3517
Evan Cheng8db90722008-10-14 17:15:11 +00003518/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3519/// opcode and two operands into either a FCmp instruction. isordered is passed
3520/// in to determine which kind of predicate to use in the new fcmp instruction.
3521static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003522 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003523 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003524 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003525 case 0:
3526 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003527 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003528 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003529 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003530 case 1:
3531 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003532 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003533 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003534 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003535 case 2:
3536 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003537 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003538 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003539 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003540 case 3:
3541 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003542 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003543 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003544 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003545 case 4:
3546 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003547 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003548 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003549 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003550 case 5:
3551 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003552 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003553 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003554 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003555 case 6:
3556 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003557 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003558 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003559 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003560 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003561 }
3562}
3563
Chris Lattnerb9553d62008-11-16 04:55:20 +00003564/// PredicatesFoldable - Return true if both predicates match sign or if at
3565/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003566static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3567 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003568 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3569 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003570}
3571
3572namespace {
3573// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3574struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003575 InstCombiner &IC;
3576 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003577 ICmpInst::Predicate pred;
3578 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3579 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3580 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003581 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003582 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3583 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003584 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3585 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003586 return false;
3587 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003588 Instruction *apply(Instruction &Log) const {
3589 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3590 if (ICI->getOperand(0) != LHS) {
3591 assert(ICI->getOperand(1) == LHS);
3592 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003593 }
3594
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003595 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003596 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003597 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003598 unsigned Code;
3599 switch (Log.getOpcode()) {
3600 case Instruction::And: Code = LHSCode & RHSCode; break;
3601 case Instruction::Or: Code = LHSCode | RHSCode; break;
3602 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003603 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003604 }
3605
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003606 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3607 ICmpInst::isSignedPredicate(ICI->getPredicate());
3608
Owen Andersond672ecb2009-07-03 00:17:18 +00003609 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003610 if (Instruction *I = dyn_cast<Instruction>(RV))
3611 return I;
3612 // Otherwise, it's a constant boolean value...
3613 return IC.ReplaceInstUsesWith(Log, RV);
3614 }
3615};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003616} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003617
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003618// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3619// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003620// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003621Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003622 ConstantInt *OpRHS,
3623 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003624 BinaryOperator &TheAnd) {
3625 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003626 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003627 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003628 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003629
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003630 switch (Op->getOpcode()) {
3631 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003632 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003633 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003634 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003635 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003636 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003637 }
3638 break;
3639 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003640 if (Together == AndRHS) // (X | C) & C --> C
3641 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003642
Chris Lattner6e7ba452005-01-01 16:22:27 +00003643 if (Op->hasOneUse() && Together != OpRHS) {
3644 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003645 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003646 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003647 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003648 }
3649 break;
3650 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003651 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003652 // Adding a one to a single bit bit-field should be turned into an XOR
3653 // of the bit. First thing to check is to see if this AND is with a
3654 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003655 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003656
3657 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003658 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003659 // Ok, at this point, we know that we are masking the result of the
3660 // ADD down to exactly one bit. If the constant we are adding has
3661 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003662 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003663
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003664 // Check to see if any bits below the one bit set in AndRHSV are set.
3665 if ((AddRHS & (AndRHSV-1)) == 0) {
3666 // If not, the only thing that can effect the output of the AND is
3667 // the bit specified by AndRHSV. If that bit is set, the effect of
3668 // the XOR is to toggle the bit. If it is clear, then the ADD has
3669 // no effect.
3670 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3671 TheAnd.setOperand(0, X);
3672 return &TheAnd;
3673 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003674 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003675 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003676 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003677 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003678 }
3679 }
3680 }
3681 }
3682 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003683
3684 case Instruction::Shl: {
3685 // We know that the AND will not produce any of the bits shifted in, so if
3686 // the anded constant includes them, clear them now!
3687 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003688 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003689 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003690 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003691 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003692
Zhou Sheng290bec52007-03-29 08:15:12 +00003693 if (CI->getValue() == ShlMask) {
3694 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003695 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3696 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003697 TheAnd.setOperand(1, CI);
3698 return &TheAnd;
3699 }
3700 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003701 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003702 case Instruction::LShr:
3703 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003704 // We know that the AND will not produce any of the bits shifted in, so if
3705 // the anded constant includes them, clear them now! This only applies to
3706 // unsigned shifts, because a signed shr may bring in set bits!
3707 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003708 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003709 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003710 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003711 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003712
Zhou Sheng290bec52007-03-29 08:15:12 +00003713 if (CI->getValue() == ShrMask) {
3714 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003715 return ReplaceInstUsesWith(TheAnd, Op);
3716 } else if (CI != AndRHS) {
3717 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3718 return &TheAnd;
3719 }
3720 break;
3721 }
3722 case Instruction::AShr:
3723 // Signed shr.
3724 // See if this is shifting in some sign extension, then masking it out
3725 // with an and.
3726 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003727 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003728 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003729 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003730 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003731 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003732 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003733 // Make the argument unsigned.
3734 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003735 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003736 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003737 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003738 }
3739 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003740 }
3741 return 0;
3742}
3743
Chris Lattner8b170942002-08-09 23:47:40 +00003744
Chris Lattnera96879a2004-09-29 17:40:11 +00003745/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3746/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003747/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3748/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003749/// insert new instructions.
3750Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003751 bool isSigned, bool Inside,
3752 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003753 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003754 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003755 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003756
Chris Lattnera96879a2004-09-29 17:40:11 +00003757 if (Inside) {
3758 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003759 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003760
Reid Spencere4d87aa2006-12-23 06:05:41 +00003761 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003762 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003763 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003764 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003765 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003766 }
3767
3768 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003769 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003770 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003771 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003772 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003773 }
3774
3775 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003776 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003777
Reid Spencere4e40032007-03-21 23:19:50 +00003778 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003779 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003780 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003781 ICmpInst::Predicate pred = (isSigned ?
3782 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003783 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003784 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003785
Reid Spencere4e40032007-03-21 23:19:50 +00003786 // Emit V-Lo >u Hi-1-Lo
3787 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003788 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003789 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003790 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003791 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003792}
3793
Chris Lattner7203e152005-09-18 07:22:02 +00003794// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3795// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3796// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3797// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003798static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003799 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003800 uint32_t BitWidth = Val->getType()->getBitWidth();
3801 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003802
3803 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003804 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003805 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003806 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003807 return true;
3808}
3809
Chris Lattner7203e152005-09-18 07:22:02 +00003810/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3811/// where isSub determines whether the operator is a sub. If we can fold one of
3812/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003813///
3814/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3815/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3816/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3817///
3818/// return (A +/- B).
3819///
3820Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003821 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003822 Instruction &I) {
3823 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3824 if (!LHSI || LHSI->getNumOperands() != 2 ||
3825 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3826
3827 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3828
3829 switch (LHSI->getOpcode()) {
3830 default: return 0;
3831 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003832 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003833 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003834 if ((Mask->getValue().countLeadingZeros() +
3835 Mask->getValue().countPopulation()) ==
3836 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003837 break;
3838
3839 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3840 // part, we don't need any explicit masks to take them out of A. If that
3841 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003842 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003843 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003844 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003845 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003846 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003847 break;
3848 }
3849 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003850 return 0;
3851 case Instruction::Or:
3852 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003853 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003854 if ((Mask->getValue().countLeadingZeros() +
3855 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003856 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003857 break;
3858 return 0;
3859 }
3860
Chris Lattnerc8e77562005-09-18 04:24:45 +00003861 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003862 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3863 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003864}
3865
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003866/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3867Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3868 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003869 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003870 ConstantInt *LHSCst, *RHSCst;
3871 ICmpInst::Predicate LHSCC, RHSCC;
3872
Chris Lattnerea065fb2008-11-16 05:10:52 +00003873 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003874 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003875 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003876 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003877 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003878 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003879
3880 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3881 // where C is a power of 2
3882 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3883 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003884 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003885 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003886 }
3887
3888 // From here on, we only handle:
3889 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3890 if (Val != Val2) return 0;
3891
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003892 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3893 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3894 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3895 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3896 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3897 return 0;
3898
3899 // We can't fold (ugt x, C) & (sgt x, C2).
3900 if (!PredicatesFoldable(LHSCC, RHSCC))
3901 return 0;
3902
3903 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003904 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003905 if (ICmpInst::isSignedPredicate(LHSCC) ||
3906 (ICmpInst::isEquality(LHSCC) &&
3907 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003908 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003909 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003910 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3911
3912 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003913 std::swap(LHS, RHS);
3914 std::swap(LHSCst, RHSCst);
3915 std::swap(LHSCC, RHSCC);
3916 }
3917
3918 // At this point, we know we have have two icmp instructions
3919 // comparing a value against two constants and and'ing the result
3920 // together. Because of the above check, we know that we only have
3921 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3922 // (from the FoldICmpLogical check above), that the two constants
3923 // are not equal and that the larger constant is on the RHS
3924 assert(LHSCst != RHSCst && "Compares not folded above?");
3925
3926 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003927 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003928 case ICmpInst::ICMP_EQ:
3929 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003930 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003931 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3932 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3933 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003934 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003935 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3936 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3937 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3938 return ReplaceInstUsesWith(I, LHS);
3939 }
3940 case ICmpInst::ICMP_NE:
3941 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003942 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003943 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003944 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003945 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003946 break; // (X != 13 & X u< 15) -> no change
3947 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003948 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003949 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003950 break; // (X != 13 & X s< 15) -> no change
3951 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3952 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3953 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3954 return ReplaceInstUsesWith(I, RHS);
3955 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003956 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003957 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003958 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003959 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003960 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003961 }
3962 break; // (X != 13 & X != 15) -> no change
3963 }
3964 break;
3965 case ICmpInst::ICMP_ULT:
3966 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003967 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003968 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3969 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003970 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003971 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3972 break;
3973 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3974 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3975 return ReplaceInstUsesWith(I, LHS);
3976 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3977 break;
3978 }
3979 break;
3980 case ICmpInst::ICMP_SLT:
3981 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003982 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003983 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3984 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003985 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003986 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3987 break;
3988 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3989 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3990 return ReplaceInstUsesWith(I, LHS);
3991 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3992 break;
3993 }
3994 break;
3995 case ICmpInst::ICMP_UGT:
3996 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003997 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003998 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3999 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4000 return ReplaceInstUsesWith(I, RHS);
4001 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4002 break;
4003 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004004 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004005 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004006 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004007 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00004008 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004009 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004010 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4011 break;
4012 }
4013 break;
4014 case ICmpInst::ICMP_SGT:
4015 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004016 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004017 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4018 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4019 return ReplaceInstUsesWith(I, RHS);
4020 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4021 break;
4022 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004023 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004024 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004025 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004026 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00004027 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004028 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004029 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4030 break;
4031 }
4032 break;
4033 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004034
4035 return 0;
4036}
4037
Chris Lattner42d1be02009-07-23 05:14:02 +00004038Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4039 FCmpInst *RHS) {
4040
4041 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4042 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4043 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4044 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4045 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4046 // If either of the constants are nans, then the whole thing returns
4047 // false.
4048 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004049 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004050 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004051 LHS->getOperand(0), RHS->getOperand(0));
4052 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004053
4054 // Handle vector zeros. This occurs because the canonical form of
4055 // "fcmp ord x,x" is "fcmp ord x, 0".
4056 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4057 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004058 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004059 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004060 return 0;
4061 }
4062
4063 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4064 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4065 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4066
4067
4068 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4069 // Swap RHS operands to match LHS.
4070 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4071 std::swap(Op1LHS, Op1RHS);
4072 }
4073
4074 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4075 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4076 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004077 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004078
4079 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004080 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004081 if (Op0CC == FCmpInst::FCMP_TRUE)
4082 return ReplaceInstUsesWith(I, RHS);
4083 if (Op1CC == FCmpInst::FCMP_TRUE)
4084 return ReplaceInstUsesWith(I, LHS);
4085
4086 bool Op0Ordered;
4087 bool Op1Ordered;
4088 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4089 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4090 if (Op1Pred == 0) {
4091 std::swap(LHS, RHS);
4092 std::swap(Op0Pred, Op1Pred);
4093 std::swap(Op0Ordered, Op1Ordered);
4094 }
4095 if (Op0Pred == 0) {
4096 // uno && ueq -> uno && (uno || eq) -> ueq
4097 // ord && olt -> ord && (ord && lt) -> olt
4098 if (Op0Ordered == Op1Ordered)
4099 return ReplaceInstUsesWith(I, RHS);
4100
4101 // uno && oeq -> uno && (ord && eq) -> false
4102 // uno && ord -> false
4103 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004104 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004105 // ord && ueq -> ord && (uno || eq) -> oeq
4106 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4107 Op0LHS, Op0RHS, Context));
4108 }
4109 }
4110
4111 return 0;
4112}
4113
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004114
Chris Lattner7e708292002-06-25 16:13:24 +00004115Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004116 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004117 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004118
Chris Lattnere87597f2004-10-16 18:11:37 +00004119 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004120 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004121
Chris Lattner6e7ba452005-01-01 16:22:27 +00004122 // and X, X = X
4123 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004124 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004125
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004126 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004127 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004128 if (SimplifyDemandedInstructionBits(I))
4129 return &I;
4130 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004131 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004132 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004133 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004134 } else if (isa<ConstantAggregateZero>(Op1)) {
4135 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004136 }
4137 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004138
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004139 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004140 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004141 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004142
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004143 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004144 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004145 Value *Op0LHS = Op0I->getOperand(0);
4146 Value *Op0RHS = Op0I->getOperand(1);
4147 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004148 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004149 case Instruction::Xor:
4150 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004151 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004152 if (!Op0I->hasOneUse()) break;
4153
4154 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4155 // Not masking anything out for the LHS, move to RHS.
4156 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4157 Op0RHS->getName()+".masked");
4158 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4159 }
4160 if (!isa<Constant>(Op0RHS) &&
4161 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4162 // Not masking anything out for the RHS, move to LHS.
4163 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4164 Op0LHS->getName()+".masked");
4165 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004166 }
4167
Chris Lattner6e7ba452005-01-01 16:22:27 +00004168 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004169 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004170 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4171 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4172 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4173 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004174 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004175 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004176 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004177 break;
4178
4179 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004180 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4181 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4182 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4183 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004184 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004185
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004186 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4187 // has 1's for all bits that the subtraction with A might affect.
4188 if (Op0I->hasOneUse()) {
4189 uint32_t BitWidth = AndRHSMask.getBitWidth();
4190 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4191 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4192
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004193 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004194 if (!(A && A->isZero()) && // avoid infinite recursion.
4195 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004196 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004197 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4198 }
4199 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004200 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004201
4202 case Instruction::Shl:
4203 case Instruction::LShr:
4204 // (1 << x) & 1 --> zext(x == 0)
4205 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004206 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004207 Value *NewICmp =
4208 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004209 return new ZExtInst(NewICmp, I.getType());
4210 }
4211 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004212 }
4213
Chris Lattner58403262003-07-23 19:25:52 +00004214 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004215 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004216 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004217 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004218 // If this is an integer truncation or change from signed-to-unsigned, and
4219 // if the source is an and/or with immediate, transform it. This
4220 // frequently occurs for bitfield accesses.
4221 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004222 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004223 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004224 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004225 if (CastOp->getOpcode() == Instruction::And) {
4226 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004227 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4228 // This will fold the two constants together, which may allow
4229 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004230 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004231 CastOp->getOperand(0), I.getType(),
4232 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004233 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004234 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004235 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004236 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004237 } else if (CastOp->getOpcode() == Instruction::Or) {
4238 // Change: and (cast (or X, C1) to T), C2
4239 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004240 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004241 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004242 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004243 return ReplaceInstUsesWith(I, AndRHS);
4244 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004245 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004246 }
Chris Lattner06782f82003-07-23 19:36:21 +00004247 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004248
4249 // Try to fold constant and into select arguments.
4250 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004251 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004252 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004253 if (isa<PHINode>(Op0))
4254 if (Instruction *NV = FoldOpIntoPhi(I))
4255 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004256 }
4257
Dan Gohman186a6362009-08-12 16:04:34 +00004258 Value *Op0NotVal = dyn_castNotVal(Op0);
4259 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004260
Chris Lattner5b62aa72004-06-18 06:07:51 +00004261 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004262 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004263
Misha Brukmancb6267b2004-07-30 12:50:08 +00004264 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004265 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004266 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4267 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004268 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004269 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004270
4271 {
Chris Lattner003b6202007-06-15 05:58:24 +00004272 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004273 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004274 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4275 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004276
4277 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004278 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004279 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004280 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004281 }
4282 }
4283
Dan Gohman4ae51262009-08-12 16:23:25 +00004284 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004285 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4286 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004287
4288 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004289 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004290 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004291 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004292 }
4293 }
Chris Lattner64daab52006-04-01 08:03:55 +00004294
4295 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004296 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004297 if (A == Op1) { // (A^B)&A -> A&(A^B)
4298 I.swapOperands(); // Simplify below
4299 std::swap(Op0, Op1);
4300 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4301 cast<BinaryOperator>(Op0)->swapOperands();
4302 I.swapOperands(); // Simplify below
4303 std::swap(Op0, Op1);
4304 }
4305 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004306
Chris Lattner64daab52006-04-01 08:03:55 +00004307 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004308 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004309 if (B == Op0) { // B&(A^B) -> B&(B^A)
4310 cast<BinaryOperator>(Op1)->swapOperands();
4311 std::swap(A, B);
4312 }
Chris Lattner74381062009-08-30 07:44:24 +00004313 if (A == Op0) // A&(A^B) -> A & ~B
4314 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004315 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004316
4317 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004318 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4319 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004320 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004321 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4322 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004323 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004324 }
4325
Reid Spencere4d87aa2006-12-23 06:05:41 +00004326 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4327 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004328 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004329 return R;
4330
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004331 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4332 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4333 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004334 }
4335
Chris Lattner6fc205f2006-05-05 06:39:07 +00004336 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004337 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4338 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4339 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4340 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004341 if (SrcTy == Op1C->getOperand(0)->getType() &&
4342 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004343 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004344 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4345 I.getType(), TD) &&
4346 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4347 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004348 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4349 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004350 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004351 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004352 }
Chris Lattnere511b742006-11-14 07:46:50 +00004353
4354 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004355 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4356 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4357 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004358 SI0->getOperand(1) == SI1->getOperand(1) &&
4359 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004360 Value *NewOp =
4361 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4362 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004363 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004364 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004365 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004366 }
4367
Evan Cheng8db90722008-10-14 17:15:11 +00004368 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004369 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004370 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4371 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4372 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004373 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004374
Chris Lattner7e708292002-06-25 16:13:24 +00004375 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004376}
4377
Chris Lattner8c34cd22008-10-05 02:13:19 +00004378/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4379/// capable of providing pieces of a bswap. The subexpression provides pieces
4380/// of a bswap if it is proven that each of the non-zero bytes in the output of
4381/// the expression came from the corresponding "byte swapped" byte in some other
4382/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4383/// we know that the expression deposits the low byte of %X into the high byte
4384/// of the bswap result and that all other bytes are zero. This expression is
4385/// accepted, the high byte of ByteValues is set to X to indicate a correct
4386/// match.
4387///
4388/// This function returns true if the match was unsuccessful and false if so.
4389/// On entry to the function the "OverallLeftShift" is a signed integer value
4390/// indicating the number of bytes that the subexpression is later shifted. For
4391/// example, if the expression is later right shifted by 16 bits, the
4392/// OverallLeftShift value would be -2 on entry. This is used to specify which
4393/// byte of ByteValues is actually being set.
4394///
4395/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4396/// byte is masked to zero by a user. For example, in (X & 255), X will be
4397/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4398/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4399/// always in the local (OverallLeftShift) coordinate space.
4400///
4401static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4402 SmallVector<Value*, 8> &ByteValues) {
4403 if (Instruction *I = dyn_cast<Instruction>(V)) {
4404 // If this is an or instruction, it may be an inner node of the bswap.
4405 if (I->getOpcode() == Instruction::Or) {
4406 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4407 ByteValues) ||
4408 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4409 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004410 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004411
4412 // If this is a logical shift by a constant multiple of 8, recurse with
4413 // OverallLeftShift and ByteMask adjusted.
4414 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4415 unsigned ShAmt =
4416 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4417 // Ensure the shift amount is defined and of a byte value.
4418 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4419 return true;
4420
4421 unsigned ByteShift = ShAmt >> 3;
4422 if (I->getOpcode() == Instruction::Shl) {
4423 // X << 2 -> collect(X, +2)
4424 OverallLeftShift += ByteShift;
4425 ByteMask >>= ByteShift;
4426 } else {
4427 // X >>u 2 -> collect(X, -2)
4428 OverallLeftShift -= ByteShift;
4429 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004430 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004431 }
4432
4433 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4434 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4435
4436 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4437 ByteValues);
4438 }
4439
4440 // If this is a logical 'and' with a mask that clears bytes, clear the
4441 // corresponding bytes in ByteMask.
4442 if (I->getOpcode() == Instruction::And &&
4443 isa<ConstantInt>(I->getOperand(1))) {
4444 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4445 unsigned NumBytes = ByteValues.size();
4446 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4447 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4448
4449 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4450 // If this byte is masked out by a later operation, we don't care what
4451 // the and mask is.
4452 if ((ByteMask & (1 << i)) == 0)
4453 continue;
4454
4455 // If the AndMask is all zeros for this byte, clear the bit.
4456 APInt MaskB = AndMask & Byte;
4457 if (MaskB == 0) {
4458 ByteMask &= ~(1U << i);
4459 continue;
4460 }
4461
4462 // If the AndMask is not all ones for this byte, it's not a bytezap.
4463 if (MaskB != Byte)
4464 return true;
4465
4466 // Otherwise, this byte is kept.
4467 }
4468
4469 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4470 ByteValues);
4471 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004472 }
4473
Chris Lattner8c34cd22008-10-05 02:13:19 +00004474 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4475 // the input value to the bswap. Some observations: 1) if more than one byte
4476 // is demanded from this input, then it could not be successfully assembled
4477 // into a byteswap. At least one of the two bytes would not be aligned with
4478 // their ultimate destination.
4479 if (!isPowerOf2_32(ByteMask)) return true;
4480 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004481
Chris Lattner8c34cd22008-10-05 02:13:19 +00004482 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4483 // is demanded, it needs to go into byte 0 of the result. This means that the
4484 // byte needs to be shifted until it lands in the right byte bucket. The
4485 // shift amount depends on the position: if the byte is coming from the high
4486 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4487 // low part, it must be shifted left.
4488 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4489 if (InputByteNo < ByteValues.size()/2) {
4490 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4491 return true;
4492 } else {
4493 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4494 return true;
4495 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004496
4497 // If the destination byte value is already defined, the values are or'd
4498 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004499 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004500 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004501 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004502 return false;
4503}
4504
4505/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4506/// If so, insert the new bswap intrinsic and return it.
4507Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004508 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004509 if (!ITy || ITy->getBitWidth() % 16 ||
4510 // ByteMask only allows up to 32-byte values.
4511 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004512 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004513
4514 /// ByteValues - For each byte of the result, we keep track of which value
4515 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004516 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004517 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004518
4519 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004520 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4521 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004522 return 0;
4523
4524 // Check to see if all of the bytes come from the same value.
4525 Value *V = ByteValues[0];
4526 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4527
4528 // Check to make sure that all of the bytes come from the same value.
4529 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4530 if (ByteValues[i] != V)
4531 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004532 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004533 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004534 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004535 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004536}
4537
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004538/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4539/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4540/// we can simplify this expression to "cond ? C : D or B".
4541static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004542 Value *C, Value *D,
4543 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004544 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004545 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004546 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004547 return 0;
4548
Chris Lattnera6a474d2008-11-16 04:26:55 +00004549 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004550 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004551 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004552 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004553 return SelectInst::Create(Cond, C, B);
4554 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004555 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004556 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004557 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004558 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004559 return 0;
4560}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004561
Chris Lattner69d4ced2008-11-16 05:20:07 +00004562/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4563Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4564 ICmpInst *LHS, ICmpInst *RHS) {
4565 Value *Val, *Val2;
4566 ConstantInt *LHSCst, *RHSCst;
4567 ICmpInst::Predicate LHSCC, RHSCC;
4568
4569 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004570 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004571 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004572 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004573 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004574 return 0;
4575
4576 // From here on, we only handle:
4577 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4578 if (Val != Val2) return 0;
4579
4580 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4581 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4582 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4583 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4584 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4585 return 0;
4586
4587 // We can't fold (ugt x, C) | (sgt x, C2).
4588 if (!PredicatesFoldable(LHSCC, RHSCC))
4589 return 0;
4590
4591 // Ensure that the larger constant is on the RHS.
4592 bool ShouldSwap;
4593 if (ICmpInst::isSignedPredicate(LHSCC) ||
4594 (ICmpInst::isEquality(LHSCC) &&
4595 ICmpInst::isSignedPredicate(RHSCC)))
4596 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4597 else
4598 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4599
4600 if (ShouldSwap) {
4601 std::swap(LHS, RHS);
4602 std::swap(LHSCst, RHSCst);
4603 std::swap(LHSCC, RHSCC);
4604 }
4605
4606 // At this point, we know we have have two icmp instructions
4607 // comparing a value against two constants and or'ing the result
4608 // together. Because of the above check, we know that we only have
4609 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4610 // FoldICmpLogical check above), that the two constants are not
4611 // equal.
4612 assert(LHSCst != RHSCst && "Compares not folded above?");
4613
4614 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004615 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004616 case ICmpInst::ICMP_EQ:
4617 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004618 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004619 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004620 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004621 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004622 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004623 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004624 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004625 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004626 }
4627 break; // (X == 13 | X == 15) -> no change
4628 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4629 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4630 break;
4631 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4632 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4633 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4634 return ReplaceInstUsesWith(I, RHS);
4635 }
4636 break;
4637 case ICmpInst::ICMP_NE:
4638 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004639 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004640 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4641 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4642 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4643 return ReplaceInstUsesWith(I, LHS);
4644 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4645 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4646 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004647 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004648 }
4649 break;
4650 case ICmpInst::ICMP_ULT:
4651 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004652 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004653 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4654 break;
4655 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4656 // If RHSCst is [us]MAXINT, it is always false. Not handling
4657 // this can cause overflow.
4658 if (RHSCst->isMaxValue(false))
4659 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004660 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004661 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004662 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4663 break;
4664 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4665 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4666 return ReplaceInstUsesWith(I, RHS);
4667 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4668 break;
4669 }
4670 break;
4671 case ICmpInst::ICMP_SLT:
4672 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004673 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004674 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4675 break;
4676 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4677 // If RHSCst is [us]MAXINT, it is always false. Not handling
4678 // this can cause overflow.
4679 if (RHSCst->isMaxValue(true))
4680 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004681 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004682 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004683 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4684 break;
4685 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4686 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4687 return ReplaceInstUsesWith(I, RHS);
4688 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4689 break;
4690 }
4691 break;
4692 case ICmpInst::ICMP_UGT:
4693 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004694 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004695 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4696 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4697 return ReplaceInstUsesWith(I, LHS);
4698 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4699 break;
4700 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4701 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004702 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004703 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4704 break;
4705 }
4706 break;
4707 case ICmpInst::ICMP_SGT:
4708 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004709 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004710 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4711 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4712 return ReplaceInstUsesWith(I, LHS);
4713 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4714 break;
4715 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4716 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004717 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004718 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4719 break;
4720 }
4721 break;
4722 }
4723 return 0;
4724}
4725
Chris Lattner5414cc52009-07-23 05:46:22 +00004726Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4727 FCmpInst *RHS) {
4728 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4729 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4730 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4731 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4732 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4733 // If either of the constants are nans, then the whole thing returns
4734 // true.
4735 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004736 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004737
4738 // Otherwise, no need to compare the two constants, compare the
4739 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004740 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004741 LHS->getOperand(0), RHS->getOperand(0));
4742 }
4743
4744 // Handle vector zeros. This occurs because the canonical form of
4745 // "fcmp uno x,x" is "fcmp uno x, 0".
4746 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4747 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004748 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004749 LHS->getOperand(0), RHS->getOperand(0));
4750
4751 return 0;
4752 }
4753
4754 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4755 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4756 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4757
4758 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4759 // Swap RHS operands to match LHS.
4760 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4761 std::swap(Op1LHS, Op1RHS);
4762 }
4763 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4764 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4765 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004766 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004767 Op0LHS, Op0RHS);
4768 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004769 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004770 if (Op0CC == FCmpInst::FCMP_FALSE)
4771 return ReplaceInstUsesWith(I, RHS);
4772 if (Op1CC == FCmpInst::FCMP_FALSE)
4773 return ReplaceInstUsesWith(I, LHS);
4774 bool Op0Ordered;
4775 bool Op1Ordered;
4776 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4777 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4778 if (Op0Ordered == Op1Ordered) {
4779 // If both are ordered or unordered, return a new fcmp with
4780 // or'ed predicates.
4781 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4782 Op0LHS, Op0RHS, Context);
4783 if (Instruction *I = dyn_cast<Instruction>(RV))
4784 return I;
4785 // Otherwise, it's a constant boolean value...
4786 return ReplaceInstUsesWith(I, RV);
4787 }
4788 }
4789 return 0;
4790}
4791
Bill Wendlinga698a472008-12-01 08:23:25 +00004792/// FoldOrWithConstants - This helper function folds:
4793///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004794/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004795///
4796/// into:
4797///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004798/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004799///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004800/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004801Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004802 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004803 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4804 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004805
Bill Wendling286a0542008-12-02 06:24:20 +00004806 Value *V1 = 0;
4807 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004808 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004809
Bill Wendling29976b92008-12-02 06:18:11 +00004810 APInt Xor = CI1->getValue() ^ CI2->getValue();
4811 if (!Xor.isAllOnesValue()) return 0;
4812
Bill Wendling286a0542008-12-02 06:24:20 +00004813 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004814 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004815 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004816 }
4817
4818 return 0;
4819}
4820
Chris Lattner7e708292002-06-25 16:13:24 +00004821Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004822 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004823 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004824
Chris Lattner42593e62007-03-24 23:56:43 +00004825 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004826 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004827
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004828 // or X, X = X
4829 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004830 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004831
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004832 // See if we can simplify any instructions used by the instruction whose sole
4833 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004834 if (SimplifyDemandedInstructionBits(I))
4835 return &I;
4836 if (isa<VectorType>(I.getType())) {
4837 if (isa<ConstantAggregateZero>(Op1)) {
4838 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4839 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4840 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4841 return ReplaceInstUsesWith(I, I.getOperand(1));
4842 }
Chris Lattner42593e62007-03-24 23:56:43 +00004843 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004844
Chris Lattner3f5b8772002-05-06 16:14:14 +00004845 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004846 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004847 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004848 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004849 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004850 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004851 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004852 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004853 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004854 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004855 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004856
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004857 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004858 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004859 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004860 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004861 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004862 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004863 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004864 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004865
4866 // Try to fold constant and into select arguments.
4867 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004868 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004869 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004870 if (isa<PHINode>(Op0))
4871 if (Instruction *NV = FoldOpIntoPhi(I))
4872 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004873 }
4874
Chris Lattner4f637d42006-01-06 17:59:59 +00004875 Value *A = 0, *B = 0;
4876 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004877
Dan Gohman4ae51262009-08-12 16:23:25 +00004878 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004879 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4880 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004881 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004882 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4883 return ReplaceInstUsesWith(I, Op0);
4884
Chris Lattner6423d4c2006-07-10 20:25:24 +00004885 // (A | B) | C and A | (B | C) -> bswap if possible.
4886 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004887 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4888 match(Op1, m_Or(m_Value(), m_Value())) ||
4889 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4890 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004891 if (Instruction *BSwap = MatchBSwap(I))
4892 return BSwap;
4893 }
4894
Chris Lattner6e4c6492005-05-09 04:58:36 +00004895 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004896 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004897 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004898 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004899 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004900 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004901 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004902 }
4903
4904 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004905 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004906 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004907 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004908 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004909 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004910 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004911 }
4912
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004913 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004914 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004915 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4916 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004917 Value *V1 = 0, *V2 = 0, *V3 = 0;
4918 C1 = dyn_cast<ConstantInt>(C);
4919 C2 = dyn_cast<ConstantInt>(D);
4920 if (C1 && C2) { // (A & C1)|(B & C2)
4921 // If we have: ((V + N) & C1) | (V & C2)
4922 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4923 // replace with V+N.
4924 if (C1->getValue() == ~C2->getValue()) {
4925 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004926 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004927 // Add commutes, try both ways.
4928 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4929 return ReplaceInstUsesWith(I, A);
4930 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4931 return ReplaceInstUsesWith(I, A);
4932 }
4933 // Or commutes, try both ways.
4934 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004935 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004936 // Add commutes, try both ways.
4937 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4938 return ReplaceInstUsesWith(I, B);
4939 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4940 return ReplaceInstUsesWith(I, B);
4941 }
4942 }
Chris Lattner044e5332007-04-08 08:01:49 +00004943 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004944 }
4945
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004946 // Check to see if we have any common things being and'ed. If so, find the
4947 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004948 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4949 if (A == B) // (A & C)|(A & D) == A & (C|D)
4950 V1 = A, V2 = C, V3 = D;
4951 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4952 V1 = A, V2 = B, V3 = C;
4953 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4954 V1 = C, V2 = A, V3 = D;
4955 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4956 V1 = C, V2 = A, V3 = B;
4957
4958 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004959 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004960 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004961 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004962 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004963
Dan Gohman1975d032008-10-30 20:40:10 +00004964 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004965 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004966 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004967 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004968 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004969 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004970 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004971 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004972 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004973
Bill Wendlingb01865c2008-11-30 13:52:49 +00004974 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004975 if ((match(C, m_Not(m_Specific(D))) &&
4976 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004977 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004978 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004979 if ((match(A, m_Not(m_Specific(D))) &&
4980 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004981 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004982 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004983 if ((match(C, m_Not(m_Specific(B))) &&
4984 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004985 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004986 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004987 if ((match(A, m_Not(m_Specific(B))) &&
4988 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004989 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004990 }
Chris Lattnere511b742006-11-14 07:46:50 +00004991
4992 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004993 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4994 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4995 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004996 SI0->getOperand(1) == SI1->getOperand(1) &&
4997 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004998 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4999 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005000 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00005001 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00005002 }
5003 }
Chris Lattner67ca7682003-08-12 19:11:07 +00005004
Bill Wendlingb3833d12008-12-01 01:07:11 +00005005 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005006 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5007 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005008 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005009 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005010 }
5011 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005012 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5013 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005014 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005015 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005016 }
5017
Dan Gohman4ae51262009-08-12 16:23:25 +00005018 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005019 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00005020 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005021 } else {
5022 A = 0;
5023 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005024 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00005025 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005026 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00005027 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00005028
Misha Brukmancb6267b2004-07-30 12:50:08 +00005029 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005030 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00005031 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00005032 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005033 }
Chris Lattnera27231a2003-03-10 23:13:59 +00005034 }
Chris Lattnera2881962003-02-18 19:28:33 +00005035
Reid Spencere4d87aa2006-12-23 06:05:41 +00005036 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5037 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005038 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005039 return R;
5040
Chris Lattner69d4ced2008-11-16 05:20:07 +00005041 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5042 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5043 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005044 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005045
5046 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005047 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005048 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005049 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005050 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5051 !isa<ICmpInst>(Op1C->getOperand(0))) {
5052 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005053 if (SrcTy == Op1C->getOperand(0)->getType() &&
5054 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005055 // Only do this if the casts both really cause code to be
5056 // generated.
5057 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5058 I.getType(), TD) &&
5059 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5060 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005061 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5062 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005063 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005064 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005065 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005066 }
Chris Lattner99c65742007-10-24 05:38:08 +00005067 }
5068
5069
5070 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5071 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005072 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5073 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5074 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005075 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005076
Chris Lattner7e708292002-06-25 16:13:24 +00005077 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005078}
5079
Dan Gohman844731a2008-05-13 00:00:25 +00005080namespace {
5081
Chris Lattnerc317d392004-02-16 01:20:27 +00005082// XorSelf - Implements: X ^ X --> 0
5083struct XorSelf {
5084 Value *RHS;
5085 XorSelf(Value *rhs) : RHS(rhs) {}
5086 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5087 Instruction *apply(BinaryOperator &Xor) const {
5088 return &Xor;
5089 }
5090};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005091
Dan Gohman844731a2008-05-13 00:00:25 +00005092}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005093
Chris Lattner7e708292002-06-25 16:13:24 +00005094Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005095 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005096 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005097
Evan Chengd34af782008-03-25 20:07:13 +00005098 if (isa<UndefValue>(Op1)) {
5099 if (isa<UndefValue>(Op0))
5100 // Handle undef ^ undef -> 0 special case. This is a common
5101 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005102 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005103 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005104 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005105
Chris Lattnerc317d392004-02-16 01:20:27 +00005106 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005107 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005108 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005109 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005110 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005111
5112 // See if we can simplify any instructions used by the instruction whose sole
5113 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005114 if (SimplifyDemandedInstructionBits(I))
5115 return &I;
5116 if (isa<VectorType>(I.getType()))
5117 if (isa<ConstantAggregateZero>(Op1))
5118 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005119
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005120 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005121 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005122 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5123 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5124 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5125 if (Op0I->getOpcode() == Instruction::And ||
5126 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005127 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5128 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005129 Value *NotY =
5130 Builder->CreateNot(Op0I->getOperand(1),
5131 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005132 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005133 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005134 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005135 }
5136 }
5137 }
5138 }
5139
5140
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005141 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005142 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005143 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005144 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005145 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005146 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005147
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005148 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005149 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005150 FCI->getOperand(0), FCI->getOperand(1));
5151 }
5152
Nick Lewycky517e1f52008-05-31 19:01:33 +00005153 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5154 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5155 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5156 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5157 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005158 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5159 (RHS == ConstantExpr::getCast(Opcode,
5160 ConstantInt::getTrue(*Context),
5161 Op0C->getDestTy()))) {
5162 CI->setPredicate(CI->getInversePredicate());
5163 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005164 }
5165 }
5166 }
5167 }
5168
Reid Spencere4d87aa2006-12-23 06:05:41 +00005169 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005170 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005171 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5172 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005173 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5174 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005175 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005176 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005177 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005178
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005179 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005180 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005181 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005182 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005183 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005184 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005185 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005186 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005187 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005188 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005189 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005190 Constant *C = ConstantInt::get(*Context,
5191 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005192 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005193
Chris Lattner7c4049c2004-01-12 19:35:11 +00005194 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005195 } else if (Op0I->getOpcode() == Instruction::Or) {
5196 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005197 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005198 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005199 // Anything in both C1 and C2 is known to be zero, remove it from
5200 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005201 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5202 NewRHS = ConstantExpr::getAnd(NewRHS,
5203 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005204 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005205 I.setOperand(0, Op0I->getOperand(0));
5206 I.setOperand(1, NewRHS);
5207 return &I;
5208 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005209 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005210 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005211 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005212
5213 // Try to fold constant and into select arguments.
5214 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005215 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005216 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005217 if (isa<PHINode>(Op0))
5218 if (Instruction *NV = FoldOpIntoPhi(I))
5219 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005220 }
5221
Dan Gohman186a6362009-08-12 16:04:34 +00005222 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005223 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005224 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005225
Dan Gohman186a6362009-08-12 16:04:34 +00005226 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005227 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005228 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005229
Chris Lattner318bf792007-03-18 22:51:34 +00005230
5231 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5232 if (Op1I) {
5233 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005234 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005235 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005236 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005237 I.swapOperands();
5238 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005239 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005240 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005241 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005242 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005243 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005244 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005245 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005246 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005247 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005248 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005249 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005250 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005251 std::swap(A, B);
5252 }
Chris Lattner318bf792007-03-18 22:51:34 +00005253 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005254 I.swapOperands(); // Simplified below.
5255 std::swap(Op0, Op1);
5256 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005257 }
Chris Lattner318bf792007-03-18 22:51:34 +00005258 }
5259
5260 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5261 if (Op0I) {
5262 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005263 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005264 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005265 if (A == Op1) // (B|A)^B == (A|B)^B
5266 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005267 if (B == Op1) // (A|B)^B == A & ~B
5268 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005269 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005270 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005271 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005272 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005273 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005274 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005275 if (A == Op1) // (A&B)^A -> (B&A)^A
5276 std::swap(A, B);
5277 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005278 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005279 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005280 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005281 }
Chris Lattner318bf792007-03-18 22:51:34 +00005282 }
5283
5284 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5285 if (Op0I && Op1I && Op0I->isShift() &&
5286 Op0I->getOpcode() == Op1I->getOpcode() &&
5287 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5288 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005289 Value *NewOp =
5290 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5291 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005292 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005293 Op1I->getOperand(1));
5294 }
5295
5296 if (Op0I && Op1I) {
5297 Value *A, *B, *C, *D;
5298 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005299 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5300 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005301 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005302 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005303 }
5304 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005305 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5306 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005307 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005308 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005309 }
5310
5311 // (A & B)^(C & D)
5312 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005313 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5314 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005315 // (X & Y)^(X & Y) -> (Y^Z) & X
5316 Value *X = 0, *Y = 0, *Z = 0;
5317 if (A == C)
5318 X = A, Y = B, Z = D;
5319 else if (A == D)
5320 X = A, Y = B, Z = C;
5321 else if (B == C)
5322 X = B, Y = A, Z = D;
5323 else if (B == D)
5324 X = B, Y = A, Z = C;
5325
5326 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005327 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005328 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005329 }
5330 }
5331 }
5332
Reid Spencere4d87aa2006-12-23 06:05:41 +00005333 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5334 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005335 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005336 return R;
5337
Chris Lattner6fc205f2006-05-05 06:39:07 +00005338 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005339 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005340 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005341 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5342 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005343 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005344 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005345 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5346 I.getType(), TD) &&
5347 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5348 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005349 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5350 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005351 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005352 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005353 }
Chris Lattner99c65742007-10-24 05:38:08 +00005354 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005355
Chris Lattner7e708292002-06-25 16:13:24 +00005356 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005357}
5358
Owen Andersond672ecb2009-07-03 00:17:18 +00005359static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005360 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005361 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005362}
Chris Lattnera96879a2004-09-29 17:40:11 +00005363
Dan Gohman6de29f82009-06-15 22:12:54 +00005364static bool HasAddOverflow(ConstantInt *Result,
5365 ConstantInt *In1, ConstantInt *In2,
5366 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005367 if (IsSigned)
5368 if (In2->getValue().isNegative())
5369 return Result->getValue().sgt(In1->getValue());
5370 else
5371 return Result->getValue().slt(In1->getValue());
5372 else
5373 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005374}
5375
Dan Gohman6de29f82009-06-15 22:12:54 +00005376/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005377/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005378static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005379 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005380 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005381 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005382
Dan Gohman6de29f82009-06-15 22:12:54 +00005383 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5384 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005385 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005386 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5387 ExtractElement(In1, Idx, Context),
5388 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005389 IsSigned))
5390 return true;
5391 }
5392 return false;
5393 }
5394
5395 return HasAddOverflow(cast<ConstantInt>(Result),
5396 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5397 IsSigned);
5398}
5399
5400static bool HasSubOverflow(ConstantInt *Result,
5401 ConstantInt *In1, ConstantInt *In2,
5402 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005403 if (IsSigned)
5404 if (In2->getValue().isNegative())
5405 return Result->getValue().slt(In1->getValue());
5406 else
5407 return Result->getValue().sgt(In1->getValue());
5408 else
5409 return Result->getValue().ugt(In1->getValue());
5410}
5411
Dan Gohman6de29f82009-06-15 22:12:54 +00005412/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5413/// overflowed for this type.
5414static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005415 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005416 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005417 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005418
5419 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5420 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005421 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005422 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5423 ExtractElement(In1, Idx, Context),
5424 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005425 IsSigned))
5426 return true;
5427 }
5428 return false;
5429 }
5430
5431 return HasSubOverflow(cast<ConstantInt>(Result),
5432 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5433 IsSigned);
5434}
5435
Chris Lattner574da9b2005-01-13 20:14:25 +00005436/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5437/// code necessary to compute the offset from the base pointer (without adding
5438/// in the base pointer). Return the result as a signed integer of intptr size.
5439static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005440 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005441 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005442 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005443 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005444
5445 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005446 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005447 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005448
Gabor Greif177dd3f2008-06-12 21:37:33 +00005449 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5450 ++i, ++GTI) {
5451 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005452 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005453 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5454 if (OpC->isZero()) continue;
5455
5456 // Handle a struct index, which adds its field offset to the pointer.
5457 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5458 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5459
Chris Lattner74381062009-08-30 07:44:24 +00005460 Result = IC.Builder->CreateAdd(Result,
5461 ConstantInt::get(IntPtrTy, Size),
5462 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005463 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005464 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005465
Owen Andersoneed707b2009-07-24 23:12:02 +00005466 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005467 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005468 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5469 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005470 // Emit an add instruction.
5471 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005472 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005473 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005474 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005475 if (Op->getType() != IntPtrTy)
5476 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005477 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005478 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005479 // We'll let instcombine(mul) convert this to a shl if possible.
5480 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005481 }
5482
5483 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005484 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005485 }
5486 return Result;
5487}
5488
Chris Lattner10c0d912008-04-22 02:53:33 +00005489
Dan Gohman8f080f02009-07-17 22:16:21 +00005490/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5491/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5492/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5493/// be complex, and scales are involved. The above expression would also be
5494/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5495/// This later form is less amenable to optimization though, and we are allowed
5496/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005497///
5498/// If we can't emit an optimized form for this expression, this returns null.
5499///
5500static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5501 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005502 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005503 gep_type_iterator GTI = gep_type_begin(GEP);
5504
5505 // Check to see if this gep only has a single variable index. If so, and if
5506 // any constant indices are a multiple of its scale, then we can compute this
5507 // in terms of the scale of the variable index. For example, if the GEP
5508 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5509 // because the expression will cross zero at the same point.
5510 unsigned i, e = GEP->getNumOperands();
5511 int64_t Offset = 0;
5512 for (i = 1; i != e; ++i, ++GTI) {
5513 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5514 // Compute the aggregate offset of constant indices.
5515 if (CI->isZero()) continue;
5516
5517 // Handle a struct index, which adds its field offset to the pointer.
5518 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5519 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5520 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005521 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005522 Offset += Size*CI->getSExtValue();
5523 }
5524 } else {
5525 // Found our variable index.
5526 break;
5527 }
5528 }
5529
5530 // If there are no variable indices, we must have a constant offset, just
5531 // evaluate it the general way.
5532 if (i == e) return 0;
5533
5534 Value *VariableIdx = GEP->getOperand(i);
5535 // Determine the scale factor of the variable element. For example, this is
5536 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005537 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005538
5539 // Verify that there are no other variable indices. If so, emit the hard way.
5540 for (++i, ++GTI; i != e; ++i, ++GTI) {
5541 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5542 if (!CI) return 0;
5543
5544 // Compute the aggregate offset of constant indices.
5545 if (CI->isZero()) continue;
5546
5547 // Handle a struct index, which adds its field offset to the pointer.
5548 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5549 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5550 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005551 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005552 Offset += Size*CI->getSExtValue();
5553 }
5554 }
5555
5556 // Okay, we know we have a single variable index, which must be a
5557 // pointer/array/vector index. If there is no offset, life is simple, return
5558 // the index.
5559 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5560 if (Offset == 0) {
5561 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5562 // we don't need to bother extending: the extension won't affect where the
5563 // computation crosses zero.
5564 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005565 VariableIdx = new TruncInst(VariableIdx,
5566 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005567 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005568 return VariableIdx;
5569 }
5570
5571 // Otherwise, there is an index. The computation we will do will be modulo
5572 // the pointer size, so get it.
5573 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5574
5575 Offset &= PtrSizeMask;
5576 VariableScale &= PtrSizeMask;
5577
5578 // To do this transformation, any constant index must be a multiple of the
5579 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5580 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5581 // multiple of the variable scale.
5582 int64_t NewOffs = Offset / (int64_t)VariableScale;
5583 if (Offset != NewOffs*(int64_t)VariableScale)
5584 return 0;
5585
5586 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005587 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005588 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005589 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005590 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005591 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005592 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005593 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005594}
5595
5596
Reid Spencere4d87aa2006-12-23 06:05:41 +00005597/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005598/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005599Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005600 ICmpInst::Predicate Cond,
5601 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005602 // Look through bitcasts.
5603 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5604 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005605
Chris Lattner574da9b2005-01-13 20:14:25 +00005606 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005607 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005608 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005609 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005610 // know pointers can't overflow since the gep is inbounds. See if we can
5611 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005612 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5613
5614 // If not, synthesize the offset the hard way.
5615 if (Offset == 0)
5616 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005617 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005618 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005619 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005620 // If the base pointers are different, but the indices are the same, just
5621 // compare the base pointer.
5622 if (PtrBase != GEPRHS->getOperand(0)) {
5623 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005624 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005625 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005626 if (IndicesTheSame)
5627 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5628 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5629 IndicesTheSame = false;
5630 break;
5631 }
5632
5633 // If all indices are the same, just compare the base pointers.
5634 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005635 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005636 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005637
5638 // Otherwise, the base pointers are different and the indices are
5639 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005640 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005641 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005642
Chris Lattnere9d782b2005-01-13 22:25:21 +00005643 // If one of the GEPs has all zero indices, recurse.
5644 bool AllZeros = true;
5645 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5646 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5647 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5648 AllZeros = false;
5649 break;
5650 }
5651 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005652 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5653 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005654
5655 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005656 AllZeros = true;
5657 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5658 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5659 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5660 AllZeros = false;
5661 break;
5662 }
5663 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005664 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005665
Chris Lattner4401c9c2005-01-14 00:20:05 +00005666 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5667 // If the GEPs only differ by one index, compare it.
5668 unsigned NumDifferences = 0; // Keep track of # differences.
5669 unsigned DiffOperand = 0; // The operand that differs.
5670 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5671 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005672 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5673 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005674 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005675 NumDifferences = 2;
5676 break;
5677 } else {
5678 if (NumDifferences++) break;
5679 DiffOperand = i;
5680 }
5681 }
5682
5683 if (NumDifferences == 0) // SAME GEP?
5684 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005685 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005686 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005687
Chris Lattner4401c9c2005-01-14 00:20:05 +00005688 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005689 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5690 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005691 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005692 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005693 }
5694 }
5695
Reid Spencere4d87aa2006-12-23 06:05:41 +00005696 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005697 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005698 if (TD &&
5699 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005700 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5701 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5702 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5703 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005704 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005705 }
5706 }
5707 return 0;
5708}
5709
Chris Lattnera5406232008-05-19 20:18:56 +00005710/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5711///
5712Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5713 Instruction *LHSI,
5714 Constant *RHSC) {
5715 if (!isa<ConstantFP>(RHSC)) return 0;
5716 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5717
5718 // Get the width of the mantissa. We don't want to hack on conversions that
5719 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005720 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005721 if (MantissaWidth == -1) return 0; // Unknown.
5722
5723 // Check to see that the input is converted from an integer type that is small
5724 // enough that preserves all bits. TODO: check here for "known" sign bits.
5725 // 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 +00005726 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005727
5728 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005729 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5730 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005731 ++InputSize;
5732
5733 // If the conversion would lose info, don't hack on this.
5734 if ((int)InputSize > MantissaWidth)
5735 return 0;
5736
5737 // Otherwise, we can potentially simplify the comparison. We know that it
5738 // will always come through as an integer value and we know the constant is
5739 // not a NAN (it would have been previously simplified).
5740 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5741
5742 ICmpInst::Predicate Pred;
5743 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005744 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005745 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005746 case FCmpInst::FCMP_OEQ:
5747 Pred = ICmpInst::ICMP_EQ;
5748 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005749 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005750 case FCmpInst::FCMP_OGT:
5751 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5752 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005753 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005754 case FCmpInst::FCMP_OGE:
5755 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5756 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005757 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005758 case FCmpInst::FCMP_OLT:
5759 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5760 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005761 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005762 case FCmpInst::FCMP_OLE:
5763 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5764 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005765 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005766 case FCmpInst::FCMP_ONE:
5767 Pred = ICmpInst::ICMP_NE;
5768 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005769 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005770 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005771 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005772 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005773 }
5774
5775 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5776
5777 // Now we know that the APFloat is a normal number, zero or inf.
5778
Chris Lattner85162782008-05-20 03:50:52 +00005779 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005780 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005781 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005782
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005783 if (!LHSUnsigned) {
5784 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5785 // and large values.
5786 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5787 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5788 APFloat::rmNearestTiesToEven);
5789 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5790 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5791 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005792 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5793 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005794 }
5795 } else {
5796 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5797 // +INF and large values.
5798 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5799 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5800 APFloat::rmNearestTiesToEven);
5801 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5802 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5803 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005804 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5805 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005806 }
Chris Lattnera5406232008-05-19 20:18:56 +00005807 }
5808
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005809 if (!LHSUnsigned) {
5810 // See if the RHS value is < SignedMin.
5811 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5812 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5813 APFloat::rmNearestTiesToEven);
5814 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5815 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5816 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005817 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5818 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005819 }
Chris Lattnera5406232008-05-19 20:18:56 +00005820 }
5821
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005822 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5823 // [0, UMAX], but it may still be fractional. See if it is fractional by
5824 // casting the FP value to the integer value and back, checking for equality.
5825 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005826 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005827 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5828 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005829 if (!RHS.isZero()) {
5830 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005831 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5832 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005833 if (!Equal) {
5834 // If we had a comparison against a fractional value, we have to adjust
5835 // the compare predicate and sometimes the value. RHSC is rounded towards
5836 // zero at this point.
5837 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005838 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005839 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005840 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005841 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005842 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005843 case ICmpInst::ICMP_ULE:
5844 // (float)int <= 4.4 --> int <= 4
5845 // (float)int <= -4.4 --> false
5846 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005847 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005848 break;
5849 case ICmpInst::ICMP_SLE:
5850 // (float)int <= 4.4 --> int <= 4
5851 // (float)int <= -4.4 --> int < -4
5852 if (RHS.isNegative())
5853 Pred = ICmpInst::ICMP_SLT;
5854 break;
5855 case ICmpInst::ICMP_ULT:
5856 // (float)int < -4.4 --> false
5857 // (float)int < 4.4 --> int <= 4
5858 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005859 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005860 Pred = ICmpInst::ICMP_ULE;
5861 break;
5862 case ICmpInst::ICMP_SLT:
5863 // (float)int < -4.4 --> int < -4
5864 // (float)int < 4.4 --> int <= 4
5865 if (!RHS.isNegative())
5866 Pred = ICmpInst::ICMP_SLE;
5867 break;
5868 case ICmpInst::ICMP_UGT:
5869 // (float)int > 4.4 --> int > 4
5870 // (float)int > -4.4 --> true
5871 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005872 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005873 break;
5874 case ICmpInst::ICMP_SGT:
5875 // (float)int > 4.4 --> int > 4
5876 // (float)int > -4.4 --> int >= -4
5877 if (RHS.isNegative())
5878 Pred = ICmpInst::ICMP_SGE;
5879 break;
5880 case ICmpInst::ICMP_UGE:
5881 // (float)int >= -4.4 --> true
5882 // (float)int >= 4.4 --> int > 4
5883 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005884 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005885 Pred = ICmpInst::ICMP_UGT;
5886 break;
5887 case ICmpInst::ICMP_SGE:
5888 // (float)int >= -4.4 --> int >= -4
5889 // (float)int >= 4.4 --> int > 4
5890 if (!RHS.isNegative())
5891 Pred = ICmpInst::ICMP_SGT;
5892 break;
5893 }
Chris Lattnera5406232008-05-19 20:18:56 +00005894 }
5895 }
5896
5897 // Lower this FP comparison into an appropriate integer version of the
5898 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005899 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005900}
5901
Reid Spencere4d87aa2006-12-23 06:05:41 +00005902Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5903 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005904 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005905
Chris Lattner58e97462007-01-14 19:42:17 +00005906 // Fold trivial predicates.
5907 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005908 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005909 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005910 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005911
5912 // Simplify 'fcmp pred X, X'
5913 if (Op0 == Op1) {
5914 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005915 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005916 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5917 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5918 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner9e17b632009-09-02 05:12:37 +00005919 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005920 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5921 case FCmpInst::FCMP_OLT: // True if ordered and less than
5922 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner9e17b632009-09-02 05:12:37 +00005923 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005924
5925 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5926 case FCmpInst::FCMP_ULT: // True if unordered or less than
5927 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5928 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5929 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5930 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005931 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005932 return &I;
5933
5934 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5935 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5936 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5937 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5938 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5939 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005940 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005941 return &I;
5942 }
5943 }
5944
Reid Spencere4d87aa2006-12-23 06:05:41 +00005945 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005946 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005947
Reid Spencere4d87aa2006-12-23 06:05:41 +00005948 // Handle fcmp with constant RHS
5949 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005950 // If the constant is a nan, see if we can fold the comparison based on it.
5951 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5952 if (CFP->getValueAPF().isNaN()) {
5953 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005954 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005955 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5956 "Comparison must be either ordered or unordered!");
5957 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005958 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005959 }
5960 }
5961
Reid Spencere4d87aa2006-12-23 06:05:41 +00005962 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5963 switch (LHSI->getOpcode()) {
5964 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005965 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5966 // block. If in the same block, we're encouraging jump threading. If
5967 // not, we are just pessimizing the code by making an i1 phi.
5968 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00005969 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005970 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005971 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005972 case Instruction::SIToFP:
5973 case Instruction::UIToFP:
5974 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5975 return NV;
5976 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005977 case Instruction::Select:
5978 // If either operand of the select is a constant, we can fold the
5979 // comparison into the select arms, which will cause one to be
5980 // constant folded and the select turned into a bitwise or.
5981 Value *Op1 = 0, *Op2 = 0;
5982 if (LHSI->hasOneUse()) {
5983 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5984 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005985 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005986 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005987 Op2 = Builder->CreateFCmp(I.getPredicate(),
5988 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005989 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5990 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005991 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005992 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005993 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5994 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005995 }
5996 }
5997
5998 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005999 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006000 break;
6001 }
6002 }
6003
6004 return Changed ? &I : 0;
6005}
6006
6007Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6008 bool Changed = SimplifyCompare(I);
6009 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6010 const Type *Ty = Op0->getType();
6011
6012 // icmp X, X
6013 if (Op0 == Op1)
Chris Lattner9e17b632009-09-02 05:12:37 +00006014 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006015 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00006016
6017 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00006018 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006019
Reid Spencere4d87aa2006-12-23 06:05:41 +00006020 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00006021 // addresses never equal each other! We already know that Op0 != Op1.
Chris Lattnerbbc33852009-10-05 02:47:47 +00006022 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
Misha Brukmanfd939082005-04-21 23:48:37 +00006023 isa<ConstantPointerNull>(Op0)) &&
Chris Lattnerbbc33852009-10-05 02:47:47 +00006024 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00006025 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00006026 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006027 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00006028
Reid Spencere4d87aa2006-12-23 06:05:41 +00006029 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006030 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006031 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006032 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006033 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006034 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006035 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006036 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006037 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006038 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006039
Reid Spencere4d87aa2006-12-23 06:05:41 +00006040 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006041 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006042 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006043 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006044 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006045 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006046 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006047 case ICmpInst::ICMP_SGT:
6048 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006049 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006050 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006051 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006052 return BinaryOperator::CreateAnd(Not, Op0);
6053 }
6054 case ICmpInst::ICMP_UGE:
6055 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6056 // FALL THROUGH
6057 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006058 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006059 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006060 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006061 case ICmpInst::ICMP_SGE:
6062 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6063 // FALL THROUGH
6064 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006065 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006066 return BinaryOperator::CreateOr(Not, Op0);
6067 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006068 }
Chris Lattner8b170942002-08-09 23:47:40 +00006069 }
6070
Dan Gohman1c8491e2009-04-25 17:12:48 +00006071 unsigned BitWidth = 0;
6072 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006073 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6074 else if (Ty->isIntOrIntVector())
6075 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006076
6077 bool isSignBit = false;
6078
Dan Gohman81b28ce2008-09-16 18:46:06 +00006079 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006080 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006081 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006082
Chris Lattnerb6566012008-01-05 01:18:20 +00006083 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6084 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006085 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006086 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006087 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006088 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006089
Dan Gohman81b28ce2008-09-16 18:46:06 +00006090 // If we have an icmp le or icmp ge instruction, turn it into the
6091 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6092 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006093 switch (I.getPredicate()) {
6094 default: break;
6095 case ICmpInst::ICMP_ULE:
6096 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006097 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006098 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006099 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006100 case ICmpInst::ICMP_SLE:
6101 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006102 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006103 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006104 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006105 case ICmpInst::ICMP_UGE:
6106 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006107 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006108 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006109 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006110 case ICmpInst::ICMP_SGE:
6111 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006112 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006113 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006114 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006115 }
6116
Chris Lattner183661e2008-07-11 05:40:05 +00006117 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006118 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006119 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006120 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6121 }
6122
6123 // See if we can fold the comparison based on range information we can get
6124 // by checking whether bits are known to be zero or one in the input.
6125 if (BitWidth != 0) {
6126 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6127 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6128
6129 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006130 isSignBit ? APInt::getSignBit(BitWidth)
6131 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006132 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006133 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006134 if (SimplifyDemandedBits(I.getOperandUse(1),
6135 APInt::getAllOnesValue(BitWidth),
6136 Op1KnownZero, Op1KnownOne, 0))
6137 return &I;
6138
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006139 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006140 // in. Compute the Min, Max and RHS values based on the known bits. For the
6141 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006142 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6143 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6144 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6145 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6146 Op0Min, Op0Max);
6147 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6148 Op1Min, Op1Max);
6149 } else {
6150 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6151 Op0Min, Op0Max);
6152 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6153 Op1Min, Op1Max);
6154 }
6155
Chris Lattner183661e2008-07-11 05:40:05 +00006156 // If Min and Max are known to be the same, then SimplifyDemandedBits
6157 // figured out that the LHS is a constant. Just constant fold this now so
6158 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006160 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006161 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006162 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006163 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006164 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006165
Chris Lattner183661e2008-07-11 05:40:05 +00006166 // Based on the range information we know about the LHS, see if we can
6167 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006168 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006169 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006170 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006171 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006172 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006173 break;
6174 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006175 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006176 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006177 break;
6178 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006179 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006180 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006181 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006182 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006183 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006184 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006185 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6186 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006187 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006188 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006189
6190 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6191 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006192 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006193 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006194 }
Chris Lattner84dff672008-07-11 05:08:55 +00006195 break;
6196 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006197 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006198 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006199 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(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
6202 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006203 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006204 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6205 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006206 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006207 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006208
6209 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6210 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006211 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006212 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006213 }
Chris Lattner84dff672008-07-11 05:08:55 +00006214 break;
6215 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006216 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006217 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006218 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006219 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006220 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006221 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006222 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6223 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006224 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006225 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006226 }
Chris Lattner84dff672008-07-11 05:08:55 +00006227 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006228 case ICmpInst::ICMP_SGT:
6229 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006230 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006231 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006232 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006233
6234 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006235 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006236 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6237 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006238 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006239 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006240 }
6241 break;
6242 case ICmpInst::ICMP_SGE:
6243 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6244 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006245 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006246 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006247 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006248 break;
6249 case ICmpInst::ICMP_SLE:
6250 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6251 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006252 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006253 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006254 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006255 break;
6256 case ICmpInst::ICMP_UGE:
6257 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6258 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006259 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006260 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006261 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006262 break;
6263 case ICmpInst::ICMP_ULE:
6264 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6265 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006266 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006267 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006268 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006269 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006270 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006271
6272 // Turn a signed comparison into an unsigned one if both operands
6273 // are known to have the same sign.
6274 if (I.isSignedPredicate() &&
6275 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6276 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006277 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006278 }
6279
6280 // Test if the ICmpInst instruction is used exclusively by a select as
6281 // part of a minimum or maximum operation. If so, refrain from doing
6282 // any other folding. This helps out other analyses which understand
6283 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6284 // and CodeGen. And in this case, at least one of the comparison
6285 // operands has at least one user besides the compare (the select),
6286 // which would often largely negate the benefit of folding anyway.
6287 if (I.hasOneUse())
6288 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6289 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6290 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6291 return 0;
6292
6293 // See if we are doing a comparison between a constant and an instruction that
6294 // can be folded into the comparison.
6295 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006296 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006297 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006298 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006299 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006300 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6301 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006302 }
6303
Chris Lattner01deb9d2007-04-03 17:43:25 +00006304 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006305 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6306 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6307 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006308 case Instruction::GetElementPtr:
6309 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006310 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006311 bool isAllZeros = true;
6312 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6313 if (!isa<Constant>(LHSI->getOperand(i)) ||
6314 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6315 isAllZeros = false;
6316 break;
6317 }
6318 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006319 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006320 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006321 }
6322 break;
6323
Chris Lattner6970b662005-04-23 15:31:55 +00006324 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006325 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006326 // block. If in the same block, we're encouraging jump threading. If
6327 // not, we are just pessimizing the code by making an i1 phi.
6328 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006329 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006330 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006331 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006332 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006333 // If either operand of the select is a constant, we can fold the
6334 // comparison into the select arms, which will cause one to be
6335 // constant folded and the select turned into a bitwise or.
6336 Value *Op1 = 0, *Op2 = 0;
6337 if (LHSI->hasOneUse()) {
6338 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6339 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006340 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006341 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006342 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6343 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006344 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6345 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006346 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006347 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006348 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6349 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006350 }
6351 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006352
Chris Lattner6970b662005-04-23 15:31:55 +00006353 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006354 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006355 break;
6356 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006357 case Instruction::Call:
6358 // If we have (malloc != null), and if the malloc has a single use, we
6359 // can assume it is successful and remove the malloc.
6360 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6361 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006362 // Need to explicitly erase malloc call here, instead of adding it to
6363 // Worklist, because it won't get DCE'd from the Worklist since
6364 // isInstructionTriviallyDead() returns false for function calls.
6365 // It is OK to replace LHSI/MallocCall with Undef because the
6366 // instruction that uses it will be erased via Worklist.
6367 if (extractMallocCall(LHSI)) {
6368 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6369 EraseInstFromFunction(*LHSI);
6370 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006371 ConstantInt::get(Type::getInt1Ty(*Context),
6372 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006373 }
6374 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6375 if (MallocCall->hasOneUse()) {
6376 MallocCall->replaceAllUsesWith(
6377 UndefValue::get(MallocCall->getType()));
6378 EraseInstFromFunction(*MallocCall);
6379 Worklist.Add(LHSI); // The malloc's bitcast use.
6380 return ReplaceInstUsesWith(I,
6381 ConstantInt::get(Type::getInt1Ty(*Context),
6382 !I.isTrueWhenEqual()));
6383 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006384 }
6385 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006386 }
Chris Lattner6970b662005-04-23 15:31:55 +00006387 }
6388
Reid Spencere4d87aa2006-12-23 06:05:41 +00006389 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006390 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006391 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006392 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006393 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006394 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6395 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006396 return NI;
6397
Reid Spencere4d87aa2006-12-23 06:05:41 +00006398 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006399 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6400 // now.
6401 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6402 if (isa<PointerType>(Op0->getType()) &&
6403 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006404 // We keep moving the cast from the left operand over to the right
6405 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006406 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006407
Chris Lattner57d86372007-01-06 01:45:59 +00006408 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6409 // so eliminate it as well.
6410 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6411 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006412
Chris Lattnerde90b762003-11-03 04:25:02 +00006413 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006414 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006415 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006416 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006417 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006418 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006419 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006420 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006421 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006422 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006423 }
Chris Lattner57d86372007-01-06 01:45:59 +00006424 }
6425
6426 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006427 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006428 // This comes up when you have code like
6429 // int X = A < B;
6430 // if (X) ...
6431 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006432 // with a constant or another cast from the same type.
6433 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006434 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006435 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006436 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006437
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006438 // See if it's the same type of instruction on the left and right.
6439 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6440 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006441 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006442 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006443 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006444 default: break;
6445 case Instruction::Add:
6446 case Instruction::Sub:
6447 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006448 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006449 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006450 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006451 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6452 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6453 if (CI->getValue().isSignBit()) {
6454 ICmpInst::Predicate Pred = I.isSignedPredicate()
6455 ? I.getUnsignedPredicate()
6456 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006457 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006458 Op1I->getOperand(0));
6459 }
6460
6461 if (CI->getValue().isMaxSignedValue()) {
6462 ICmpInst::Predicate Pred = I.isSignedPredicate()
6463 ? I.getUnsignedPredicate()
6464 : I.getSignedPredicate();
6465 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006466 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006467 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006468 }
6469 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006470 break;
6471 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006472 if (!I.isEquality())
6473 break;
6474
Nick Lewycky5d52c452008-08-21 05:56:10 +00006475 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6476 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6477 // Mask = -1 >> count-trailing-zeros(Cst).
6478 if (!CI->isZero() && !CI->isOne()) {
6479 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006480 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006481 APInt::getLowBitsSet(AP.getBitWidth(),
6482 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006483 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006484 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6485 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006486 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006487 }
6488 }
6489 break;
6490 }
6491 }
6492 }
6493 }
6494
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006495 // ~x < ~y --> y < x
6496 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006497 if (match(Op0, m_Not(m_Value(A))) &&
6498 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006499 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006500 }
6501
Chris Lattner65b72ba2006-09-18 04:22:48 +00006502 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006503 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006504
6505 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006506 if (match(Op0, m_Neg(m_Value(A))) &&
6507 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006508 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006509
Dan Gohman4ae51262009-08-12 16:23:25 +00006510 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006511 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6512 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006513 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006514 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006515 }
6516
Dan Gohman4ae51262009-08-12 16:23:25 +00006517 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006518 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006519 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006520 if (match(B, m_ConstantInt(C1)) &&
6521 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006522 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006523 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006524 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6525 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006526 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006527
6528 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006529 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6530 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6531 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6532 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006533 }
6534 }
6535
Dan Gohman4ae51262009-08-12 16:23:25 +00006536 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006537 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006538 // A == (A^B) -> B == 0
6539 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006540 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006541 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006542 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006543
6544 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006545 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006546 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006547 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006548
6549 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006550 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006551 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006552 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006553
Chris Lattner9c2328e2006-11-14 06:06:06 +00006554 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6555 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006556 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6557 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006558 Value *X = 0, *Y = 0, *Z = 0;
6559
6560 if (A == C) {
6561 X = B; Y = D; Z = A;
6562 } else if (A == D) {
6563 X = B; Y = C; Z = A;
6564 } else if (B == C) {
6565 X = A; Y = D; Z = B;
6566 } else if (B == D) {
6567 X = A; Y = C; Z = B;
6568 }
6569
6570 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006571 Op1 = Builder->CreateXor(X, Y, "tmp");
6572 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006573 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006574 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006575 return &I;
6576 }
6577 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006578 }
Chris Lattner7e708292002-06-25 16:13:24 +00006579 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006580}
6581
Chris Lattner562ef782007-06-20 23:46:26 +00006582
6583/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6584/// and CmpRHS are both known to be integer constants.
6585Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6586 ConstantInt *DivRHS) {
6587 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6588 const APInt &CmpRHSV = CmpRHS->getValue();
6589
6590 // FIXME: If the operand types don't match the type of the divide
6591 // then don't attempt this transform. The code below doesn't have the
6592 // logic to deal with a signed divide and an unsigned compare (and
6593 // vice versa). This is because (x /s C1) <s C2 produces different
6594 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6595 // (x /u C1) <u C2. Simply casting the operands and result won't
6596 // work. :( The if statement below tests that condition and bails
6597 // if it finds it.
6598 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6599 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6600 return 0;
6601 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006602 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006603 if (DivIsSigned && DivRHS->isAllOnesValue())
6604 return 0; // The overflow computation also screws up here
6605 if (DivRHS->isOne())
6606 return 0; // Not worth bothering, and eliminates some funny cases
6607 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006608
6609 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6610 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6611 // C2 (CI). By solving for X we can turn this into a range check
6612 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006613 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006614
6615 // Determine if the product overflows by seeing if the product is
6616 // not equal to the divide. Make sure we do the same kind of divide
6617 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006618 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6619 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006620
6621 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006622 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006623
Chris Lattner1dbfd482007-06-21 18:11:19 +00006624 // Figure out the interval that is being checked. For example, a comparison
6625 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6626 // Compute this interval based on the constants involved and the signedness of
6627 // the compare/divide. This computes a half-open interval, keeping track of
6628 // whether either value in the interval overflows. After analysis each
6629 // overflow variable is set to 0 if it's corresponding bound variable is valid
6630 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6631 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006632 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006633
Chris Lattner562ef782007-06-20 23:46:26 +00006634 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006635 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006636 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006637 HiOverflow = LoOverflow = ProdOV;
6638 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006639 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006640 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006641 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006642 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006643 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006644 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006645 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006646 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6647 HiOverflow = LoOverflow = ProdOV;
6648 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006649 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006650 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006651 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006652 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006653 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6654 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006655 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006656 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006657 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006658 true) ? -1 : 0;
6659 }
Chris Lattner562ef782007-06-20 23:46:26 +00006660 }
Dan Gohman76491272008-02-13 22:09:18 +00006661 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006662 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006663 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006664 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006665 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006666 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6667 HiOverflow = 1; // [INTMIN+1, overflow)
6668 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6669 }
Dan Gohman76491272008-02-13 22:09:18 +00006670 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006671 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006672 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006673 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006674 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006675 LoOverflow = AddWithOverflow(LoBound, HiBound,
6676 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006677 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006678 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6679 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006680 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006681 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006682 }
6683
Chris Lattner1dbfd482007-06-21 18:11:19 +00006684 // Dividing by a negative swaps the condition. LT <-> GT
6685 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006686 }
6687
6688 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006689 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006690 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006691 case ICmpInst::ICMP_EQ:
6692 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006693 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006694 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006695 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006696 ICmpInst::ICMP_UGE, X, LoBound);
6697 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006698 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006699 ICmpInst::ICMP_ULT, X, HiBound);
6700 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006701 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006702 case ICmpInst::ICMP_NE:
6703 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006704 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006705 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006706 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006707 ICmpInst::ICMP_ULT, X, LoBound);
6708 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006709 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006710 ICmpInst::ICMP_UGE, X, HiBound);
6711 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006712 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006713 case ICmpInst::ICMP_ULT:
6714 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006715 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006716 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006717 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006718 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006719 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006720 case ICmpInst::ICMP_UGT:
6721 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006722 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006723 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006724 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006725 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006726 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006727 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006728 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006729 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006730 }
6731}
6732
6733
Chris Lattner01deb9d2007-04-03 17:43:25 +00006734/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6735///
6736Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6737 Instruction *LHSI,
6738 ConstantInt *RHS) {
6739 const APInt &RHSV = RHS->getValue();
6740
6741 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006742 case Instruction::Trunc:
6743 if (ICI.isEquality() && LHSI->hasOneUse()) {
6744 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6745 // of the high bits truncated out of x are known.
6746 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6747 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6748 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6749 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6750 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6751
6752 // If all the high bits are known, we can do this xform.
6753 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6754 // Pull in the high bits from known-ones set.
6755 APInt NewRHS(RHS->getValue());
6756 NewRHS.zext(SrcBits);
6757 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006758 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006759 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006760 }
6761 }
6762 break;
6763
Duncan Sands0091bf22007-04-04 06:42:45 +00006764 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006765 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6766 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6767 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006768 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6769 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006770 Value *CompareVal = LHSI->getOperand(0);
6771
6772 // If the sign bit of the XorCST is not set, there is no change to
6773 // the operation, just stop using the Xor.
6774 if (!XorCST->getValue().isNegative()) {
6775 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006776 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006777 return &ICI;
6778 }
6779
6780 // Was the old condition true if the operand is positive?
6781 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6782
6783 // If so, the new one isn't.
6784 isTrueIfPositive ^= true;
6785
6786 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006787 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006788 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006789 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006790 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006791 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006792 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006793
6794 if (LHSI->hasOneUse()) {
6795 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6796 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6797 const APInt &SignBit = XorCST->getValue();
6798 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6799 ? ICI.getUnsignedPredicate()
6800 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006801 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006802 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006803 }
6804
6805 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006806 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006807 const APInt &NotSignBit = XorCST->getValue();
6808 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6809 ? ICI.getUnsignedPredicate()
6810 : ICI.getSignedPredicate();
6811 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006812 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006813 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006814 }
6815 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006816 }
6817 break;
6818 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6819 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6820 LHSI->getOperand(0)->hasOneUse()) {
6821 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6822
6823 // If the LHS is an AND of a truncating cast, we can widen the
6824 // and/compare to be the input width without changing the value
6825 // produced, eliminating a cast.
6826 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6827 // We can do this transformation if either the AND constant does not
6828 // have its sign bit set or if it is an equality comparison.
6829 // Extending a relational comparison when we're checking the sign
6830 // bit would not work.
6831 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006832 (ICI.isEquality() ||
6833 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006834 uint32_t BitWidth =
6835 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6836 APInt NewCST = AndCST->getValue();
6837 NewCST.zext(BitWidth);
6838 APInt NewCI = RHSV;
6839 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006840 Value *NewAnd =
6841 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006842 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006843 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006844 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006845 }
6846 }
6847
6848 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6849 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6850 // happens a LOT in code produced by the C front-end, for bitfield
6851 // access.
6852 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6853 if (Shift && !Shift->isShift())
6854 Shift = 0;
6855
6856 ConstantInt *ShAmt;
6857 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6858 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6859 const Type *AndTy = AndCST->getType(); // Type of the and.
6860
6861 // We can fold this as long as we can't shift unknown bits
6862 // into the mask. This can only happen with signed shift
6863 // rights, as they sign-extend.
6864 if (ShAmt) {
6865 bool CanFold = Shift->isLogicalShift();
6866 if (!CanFold) {
6867 // To test for the bad case of the signed shr, see if any
6868 // of the bits shifted in could be tested after the mask.
6869 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6870 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6871
6872 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6873 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6874 AndCST->getValue()) == 0)
6875 CanFold = true;
6876 }
6877
6878 if (CanFold) {
6879 Constant *NewCst;
6880 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006881 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006882 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006883 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006884
6885 // Check to see if we are shifting out any of the bits being
6886 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006887 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006888 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006889 // If we shifted bits out, the fold is not going to work out.
6890 // As a special case, check to see if this means that the
6891 // result is always true or false now.
6892 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006893 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006894 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006895 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006896 } else {
6897 ICI.setOperand(1, NewCst);
6898 Constant *NewAndCST;
6899 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006900 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006901 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006902 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006903 LHSI->setOperand(1, NewAndCST);
6904 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006905 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006906 return &ICI;
6907 }
6908 }
6909 }
6910
6911 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6912 // preferable because it allows the C<<Y expression to be hoisted out
6913 // of a loop if Y is invariant and X is not.
6914 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006915 ICI.isEquality() && !Shift->isArithmeticShift() &&
6916 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006917 // Compute C << Y.
6918 Value *NS;
6919 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006920 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006921 } else {
6922 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006923 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006924 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006925
6926 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006927 Value *NewAnd =
6928 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006929
6930 ICI.setOperand(0, NewAnd);
6931 return &ICI;
6932 }
6933 }
6934 break;
6935
Chris Lattnera0141b92007-07-15 20:42:37 +00006936 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6937 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6938 if (!ShAmt) break;
6939
6940 uint32_t TypeBits = RHSV.getBitWidth();
6941
6942 // Check that the shift amount is in range. If not, don't perform
6943 // undefined shifts. When the shift is visited it will be
6944 // simplified.
6945 if (ShAmt->uge(TypeBits))
6946 break;
6947
6948 if (ICI.isEquality()) {
6949 // If we are comparing against bits always shifted out, the
6950 // comparison cannot succeed.
6951 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006952 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006953 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006954 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6955 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006956 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006957 return ReplaceInstUsesWith(ICI, Cst);
6958 }
6959
6960 if (LHSI->hasOneUse()) {
6961 // Otherwise strength reduce the shift into an and.
6962 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6963 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006964 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006965 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006966
Chris Lattner74381062009-08-30 07:44:24 +00006967 Value *And =
6968 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006969 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006970 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006971 }
6972 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006973
6974 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6975 bool TrueIfSigned = false;
6976 if (LHSI->hasOneUse() &&
6977 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6978 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006979 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006980 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006981 Value *And =
6982 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006983 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006984 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006985 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006986 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006987 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006988
6989 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006990 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006991 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006992 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006993 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006994
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006995 // Check that the shift amount is in range. If not, don't perform
6996 // undefined shifts. When the shift is visited it will be
6997 // simplified.
6998 uint32_t TypeBits = RHSV.getBitWidth();
6999 if (ShAmt->uge(TypeBits))
7000 break;
7001
7002 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007003
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007004 // If we are comparing against bits always shifted out, the
7005 // comparison cannot succeed.
7006 APInt Comp = RHSV << ShAmtVal;
7007 if (LHSI->getOpcode() == Instruction::LShr)
7008 Comp = Comp.lshr(ShAmtVal);
7009 else
7010 Comp = Comp.ashr(ShAmtVal);
7011
7012 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7013 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007014 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007015 return ReplaceInstUsesWith(ICI, Cst);
7016 }
7017
7018 // Otherwise, check to see if the bits shifted out are known to be zero.
7019 // If so, we can compare against the unshifted value:
7020 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007021 if (LHSI->hasOneUse() &&
7022 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007023 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007024 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007025 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007026 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007027
Evan Chengf30752c2008-04-23 00:38:06 +00007028 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007029 // Otherwise strength reduce the shift into an and.
7030 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007031 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007032
Chris Lattner74381062009-08-30 07:44:24 +00007033 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7034 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007035 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007036 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007037 }
7038 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007039 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007040
7041 case Instruction::SDiv:
7042 case Instruction::UDiv:
7043 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7044 // Fold this div into the comparison, producing a range check.
7045 // Determine, based on the divide type, what the range is being
7046 // checked. If there is an overflow on the low or high side, remember
7047 // it, otherwise compute the range [low, hi) bounding the new value.
7048 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007049 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7050 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7051 DivRHS))
7052 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007053 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007054
7055 case Instruction::Add:
7056 // Fold: icmp pred (add, X, C1), C2
7057
7058 if (!ICI.isEquality()) {
7059 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7060 if (!LHSC) break;
7061 const APInt &LHSV = LHSC->getValue();
7062
7063 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7064 .subtract(LHSV);
7065
7066 if (ICI.isSignedPredicate()) {
7067 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007068 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007069 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007070 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007071 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007072 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007073 }
7074 } else {
7075 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007076 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007077 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007078 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007079 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007080 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007081 }
7082 }
7083 }
7084 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007085 }
7086
7087 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7088 if (ICI.isEquality()) {
7089 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7090
7091 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7092 // the second operand is a constant, simplify a bit.
7093 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7094 switch (BO->getOpcode()) {
7095 case Instruction::SRem:
7096 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7097 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7098 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7099 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007100 Value *NewRem =
7101 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7102 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007103 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007104 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007105 }
7106 }
7107 break;
7108 case Instruction::Add:
7109 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7110 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7111 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007112 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007113 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007114 } else if (RHSV == 0) {
7115 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7116 // efficiently invertible, or if the add has just this one use.
7117 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7118
Dan Gohman186a6362009-08-12 16:04:34 +00007119 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007120 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007121 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007122 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007123 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007124 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007125 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007126 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007127 }
7128 }
7129 break;
7130 case Instruction::Xor:
7131 // For the xor case, we can xor two constants together, eliminating
7132 // the explicit xor.
7133 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007134 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007135 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007136
7137 // FALLTHROUGH
7138 case Instruction::Sub:
7139 // Replace (([sub|xor] A, B) != 0) with (A != B)
7140 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007141 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007142 BO->getOperand(1));
7143 break;
7144
7145 case Instruction::Or:
7146 // If bits are being or'd in that are not present in the constant we
7147 // are comparing against, then the comparison could never succeed!
7148 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007149 Constant *NotCI = ConstantExpr::getNot(RHS);
7150 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007151 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007152 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007153 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007154 }
7155 break;
7156
7157 case Instruction::And:
7158 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7159 // If bits are being compared against that are and'd out, then the
7160 // comparison can never succeed!
7161 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007162 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007163 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007164 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007165
7166 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7167 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007168 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007169 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007170 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007171
7172 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007173 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007174 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007175 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007176 ICmpInst::Predicate pred = isICMP_NE ?
7177 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007178 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007179 }
7180
7181 // ((X & ~7) == 0) --> X < 8
7182 if (RHSV == 0 && isHighOnes(BOC)) {
7183 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007184 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007185 ICmpInst::Predicate pred = isICMP_NE ?
7186 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007187 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007188 }
7189 }
7190 default: break;
7191 }
7192 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7193 // Handle icmp {eq|ne} <intrinsic>, intcst.
7194 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007195 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007196 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007197 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007198 return &ICI;
7199 }
7200 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007201 }
7202 return 0;
7203}
7204
7205/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7206/// We only handle extending casts so far.
7207///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007208Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7209 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007210 Value *LHSCIOp = LHSCI->getOperand(0);
7211 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007212 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007213 Value *RHSCIOp;
7214
Chris Lattner8c756c12007-05-05 22:41:33 +00007215 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7216 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007217 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7218 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007219 cast<IntegerType>(DestTy)->getBitWidth()) {
7220 Value *RHSOp = 0;
7221 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007222 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007223 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7224 RHSOp = RHSC->getOperand(0);
7225 // If the pointer types don't match, insert a bitcast.
7226 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007227 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007228 }
7229
7230 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007231 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007232 }
7233
7234 // The code below only handles extension cast instructions, so far.
7235 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007236 if (LHSCI->getOpcode() != Instruction::ZExt &&
7237 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007238 return 0;
7239
Reid Spencere4d87aa2006-12-23 06:05:41 +00007240 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7241 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007242
Reid Spencere4d87aa2006-12-23 06:05:41 +00007243 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007244 // Not an extension from the same type?
7245 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007246 if (RHSCIOp->getType() != LHSCIOp->getType())
7247 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007248
Nick Lewycky4189a532008-01-28 03:48:02 +00007249 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007250 // and the other is a zext), then we can't handle this.
7251 if (CI->getOpcode() != LHSCI->getOpcode())
7252 return 0;
7253
Nick Lewycky4189a532008-01-28 03:48:02 +00007254 // Deal with equality cases early.
7255 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007256 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007257
7258 // A signed comparison of sign extended values simplifies into a
7259 // signed comparison.
7260 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007261 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007262
7263 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007264 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007265 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007266
Reid Spencere4d87aa2006-12-23 06:05:41 +00007267 // If we aren't dealing with a constant on the RHS, exit early
7268 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7269 if (!CI)
7270 return 0;
7271
7272 // Compute the constant that would happen if we truncated to SrcTy then
7273 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007274 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7275 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007276 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007277
7278 // If the re-extended constant didn't change...
7279 if (Res2 == CI) {
7280 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7281 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007282 // %A = sext i16 %X to i32
7283 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007284 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007285 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007286 // because %A may have negative value.
7287 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007288 // However, we allow this when the compare is EQ/NE, because they are
7289 // signless.
7290 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007291 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007292 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007293 }
7294
7295 // The re-extended constant changed so the constant cannot be represented
7296 // in the shorter type. Consequently, we cannot emit a simple comparison.
7297
7298 // First, handle some easy cases. We know the result cannot be equal at this
7299 // point so handle the ICI.isEquality() cases
7300 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007301 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007302 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007303 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007304
7305 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7306 // should have been folded away previously and not enter in here.
7307 Value *Result;
7308 if (isSignedCmp) {
7309 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007310 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007311 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007312 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007313 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007314 } else {
7315 // We're performing an unsigned comparison.
7316 if (isSignedExt) {
7317 // We're performing an unsigned comp with a sign extended value.
7318 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007319 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007320 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007321 } else {
7322 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007323 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007324 }
7325 }
7326
7327 // Finally, return the value computed.
7328 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007329 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007330 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007331
7332 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7333 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7334 "ICmp should be folded!");
7335 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007336 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007337 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007338}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007339
Reid Spencer832254e2007-02-02 02:16:23 +00007340Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7341 return commonShiftTransforms(I);
7342}
7343
7344Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7345 return commonShiftTransforms(I);
7346}
7347
7348Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007349 if (Instruction *R = commonShiftTransforms(I))
7350 return R;
7351
7352 Value *Op0 = I.getOperand(0);
7353
7354 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7355 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7356 if (CSI->isAllOnesValue())
7357 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007358
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007359 // See if we can turn a signed shr into an unsigned shr.
7360 if (MaskedValueIsZero(Op0,
7361 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7362 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7363
7364 // Arithmetic shifting an all-sign-bit value is a no-op.
7365 unsigned NumSignBits = ComputeNumSignBits(Op0);
7366 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7367 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007368
Chris Lattner348f6652007-12-06 01:59:46 +00007369 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007370}
7371
7372Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7373 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007374 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007375
7376 // shl X, 0 == X and shr X, 0 == X
7377 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007378 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7379 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007380 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007381
Reid Spencere4d87aa2006-12-23 06:05:41 +00007382 if (isa<UndefValue>(Op0)) {
7383 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007384 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007385 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007386 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007387 }
7388 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007389 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7390 return ReplaceInstUsesWith(I, Op0);
7391 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007392 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007393 }
7394
Dan Gohman9004c8a2009-05-21 02:28:33 +00007395 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007396 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007397 return &I;
7398
Chris Lattner2eefe512004-04-09 19:05:30 +00007399 // Try to fold constant and into select arguments.
7400 if (isa<Constant>(Op0))
7401 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007402 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007403 return R;
7404
Reid Spencerb83eb642006-10-20 07:07:24 +00007405 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007406 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7407 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007408 return 0;
7409}
7410
Reid Spencerb83eb642006-10-20 07:07:24 +00007411Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007412 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007413 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007414
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007415 // See if we can simplify any instructions used by the instruction whose sole
7416 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007417 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007418
Dan Gohmana119de82009-06-14 23:30:43 +00007419 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7420 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007421 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007422 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007423 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007424 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007425 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007426 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007427 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007428 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007429 }
7430
7431 // ((X*C1) << C2) == (X * (C1 << C2))
7432 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7433 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7434 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007435 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007436 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007437
7438 // Try to fold constant and into select arguments.
7439 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7440 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7441 return R;
7442 if (isa<PHINode>(Op0))
7443 if (Instruction *NV = FoldOpIntoPhi(I))
7444 return NV;
7445
Chris Lattner8999dd32007-12-22 09:07:47 +00007446 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7447 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7448 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7449 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7450 // place. Don't try to do this transformation in this case. Also, we
7451 // require that the input operand is a shift-by-constant so that we have
7452 // confidence that the shifts will get folded together. We could do this
7453 // xform in more cases, but it is unlikely to be profitable.
7454 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7455 isa<ConstantInt>(TrOp->getOperand(1))) {
7456 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007457 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007458 // (shift2 (shift1 & 0x00FF), c2)
7459 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007460
7461 // For logical shifts, the truncation has the effect of making the high
7462 // part of the register be zeros. Emulate this by inserting an AND to
7463 // clear the top bits as needed. This 'and' will usually be zapped by
7464 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007465 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7466 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007467 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7468
7469 // The mask we constructed says what the trunc would do if occurring
7470 // between the shifts. We want to know the effect *after* the second
7471 // shift. We know that it is a logical shift by a constant, so adjust the
7472 // mask as appropriate.
7473 if (I.getOpcode() == Instruction::Shl)
7474 MaskV <<= Op1->getZExtValue();
7475 else {
7476 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7477 MaskV = MaskV.lshr(Op1->getZExtValue());
7478 }
7479
Chris Lattner74381062009-08-30 07:44:24 +00007480 // shift1 & 0x00FF
7481 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7482 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007483
7484 // Return the value truncated to the interesting size.
7485 return new TruncInst(And, I.getType());
7486 }
7487 }
7488
Chris Lattner4d5542c2006-01-06 07:12:35 +00007489 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007490 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7491 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7492 Value *V1, *V2;
7493 ConstantInt *CC;
7494 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007495 default: break;
7496 case Instruction::Add:
7497 case Instruction::And:
7498 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007499 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007500 // These operators commute.
7501 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007502 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007503 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007504 m_Specific(Op1)))) {
7505 Value *YS = // (Y << C)
7506 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7507 // (X + (Y << C))
7508 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7509 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007510 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007511 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007512 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007513 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007514
Chris Lattner150f12a2005-09-18 06:30:59 +00007515 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007516 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007517 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007518 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007519 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007520 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007521 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007522 Value *YS = // (Y << C)
7523 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7524 Op0BO->getName());
7525 // X & (CC << C)
7526 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7527 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007528 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007529 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007530 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007531
Reid Spencera07cb7d2007-02-02 14:41:37 +00007532 // FALL THROUGH.
7533 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007534 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007535 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007536 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007537 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007538 Value *YS = // (Y << C)
7539 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7540 // (X + (Y << C))
7541 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7542 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007543 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007544 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007545 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007546 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007547
Chris Lattner13d4ab42006-05-31 21:14:00 +00007548 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007549 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7550 match(Op0BO->getOperand(0),
7551 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007552 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007553 cast<BinaryOperator>(Op0BO->getOperand(0))
7554 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007555 Value *YS = // (Y << C)
7556 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7557 // X & (CC << C)
7558 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7559 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007560
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007561 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007562 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007563
Chris Lattner11021cb2005-09-18 05:12:10 +00007564 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007565 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007566 }
7567
7568
7569 // If the operand is an bitwise operator with a constant RHS, and the
7570 // shift is the only use, we can pull it out of the shift.
7571 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7572 bool isValid = true; // Valid only for And, Or, Xor
7573 bool highBitSet = false; // Transform if high bit of constant set?
7574
7575 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007576 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007577 case Instruction::Add:
7578 isValid = isLeftShift;
7579 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007580 case Instruction::Or:
7581 case Instruction::Xor:
7582 highBitSet = false;
7583 break;
7584 case Instruction::And:
7585 highBitSet = true;
7586 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007587 }
7588
7589 // If this is a signed shift right, and the high bit is modified
7590 // by the logical operation, do not perform the transformation.
7591 // The highBitSet boolean indicates the value of the high bit of
7592 // the constant which would cause it to be modified for this
7593 // operation.
7594 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007595 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007596 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007597
7598 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007599 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007600
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007601 Value *NewShift =
7602 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007603 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007604
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007605 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007606 NewRHS);
7607 }
7608 }
7609 }
7610 }
7611
Chris Lattnerad0124c2006-01-06 07:52:12 +00007612 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007613 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7614 if (ShiftOp && !ShiftOp->isShift())
7615 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007616
Reid Spencerb83eb642006-10-20 07:07:24 +00007617 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007618 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007619 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7620 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007621 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7622 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7623 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007624
Zhou Sheng4351c642007-04-02 08:20:41 +00007625 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007626
7627 const IntegerType *Ty = cast<IntegerType>(I.getType());
7628
7629 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007630 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007631 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7632 // saturates.
7633 if (AmtSum >= TypeBits) {
7634 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007635 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007636 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7637 }
7638
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007639 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007640 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007641 }
7642
7643 if (ShiftOp->getOpcode() == Instruction::LShr &&
7644 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007645 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007646 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007647
Chris Lattnerb87056f2007-02-05 00:57:54 +00007648 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007649 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007650 }
7651
7652 if (ShiftOp->getOpcode() == Instruction::AShr &&
7653 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007654 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007655 if (AmtSum >= TypeBits)
7656 AmtSum = TypeBits-1;
7657
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007658 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007659
Zhou Shenge9e03f62007-03-28 15:02:20 +00007660 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007661 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007662 }
7663
Chris Lattnerb87056f2007-02-05 00:57:54 +00007664 // Okay, if we get here, one shift must be left, and the other shift must be
7665 // right. See if the amounts are equal.
7666 if (ShiftAmt1 == ShiftAmt2) {
7667 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7668 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007669 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007670 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007671 }
7672 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7673 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007674 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007675 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007676 }
7677 // We can simplify ((X << C) >>s C) into a trunc + sext.
7678 // NOTE: we could do this for any C, but that would make 'unusual' integer
7679 // types. For now, just stick to ones well-supported by the code
7680 // generators.
7681 const Type *SExtType = 0;
7682 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007683 case 1 :
7684 case 8 :
7685 case 16 :
7686 case 32 :
7687 case 64 :
7688 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007689 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007690 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007691 default: break;
7692 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007693 if (SExtType)
7694 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007695 // Otherwise, we can't handle it yet.
7696 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007697 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007698
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007699 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007700 if (I.getOpcode() == Instruction::Shl) {
7701 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7702 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007703 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007704
Reid Spencer55702aa2007-03-25 21:11:44 +00007705 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007706 return BinaryOperator::CreateAnd(Shift,
7707 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007708 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007709
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007710 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007711 if (I.getOpcode() == Instruction::LShr) {
7712 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007713 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007714
Reid Spencerd5e30f02007-03-26 17:18:58 +00007715 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007716 return BinaryOperator::CreateAnd(Shift,
7717 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007718 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007719
7720 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7721 } else {
7722 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007723 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007724
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007725 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007726 if (I.getOpcode() == Instruction::Shl) {
7727 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7728 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007729 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7730 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007731
Reid Spencer55702aa2007-03-25 21:11:44 +00007732 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007733 return BinaryOperator::CreateAnd(Shift,
7734 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007735 }
7736
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007737 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007738 if (I.getOpcode() == Instruction::LShr) {
7739 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007740 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007741
Reid Spencer68d27cf2007-03-26 23:45:51 +00007742 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007743 return BinaryOperator::CreateAnd(Shift,
7744 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007745 }
7746
7747 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007748 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007749 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007750 return 0;
7751}
7752
Chris Lattnera1be5662002-05-02 17:06:02 +00007753
Chris Lattnercfd65102005-10-29 04:36:15 +00007754/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7755/// expression. If so, decompose it, returning some value X, such that Val is
7756/// X*Scale+Offset.
7757///
7758static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007759 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007760 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7761 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007762 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007763 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007764 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007765 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007766 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7767 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7768 if (I->getOpcode() == Instruction::Shl) {
7769 // This is a value scaled by '1 << the shift amt'.
7770 Scale = 1U << RHS->getZExtValue();
7771 Offset = 0;
7772 return I->getOperand(0);
7773 } else if (I->getOpcode() == Instruction::Mul) {
7774 // This value is scaled by 'RHS'.
7775 Scale = RHS->getZExtValue();
7776 Offset = 0;
7777 return I->getOperand(0);
7778 } else if (I->getOpcode() == Instruction::Add) {
7779 // We have X+C. Check to see if we really have (X*C2)+C1,
7780 // where C1 is divisible by C2.
7781 unsigned SubScale;
7782 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007783 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7784 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007785 Offset += RHS->getZExtValue();
7786 Scale = SubScale;
7787 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007788 }
7789 }
7790 }
7791
7792 // Otherwise, we can't look past this.
7793 Scale = 1;
7794 Offset = 0;
7795 return Val;
7796}
7797
7798
Chris Lattnerb3f83972005-10-24 06:03:58 +00007799/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7800/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007801Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007802 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007803 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007804
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007805 BuilderTy AllocaBuilder(*Builder);
7806 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7807
Chris Lattnerb53c2382005-10-24 06:22:12 +00007808 // Remove any uses of AI that are dead.
7809 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007810
Chris Lattnerb53c2382005-10-24 06:22:12 +00007811 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7812 Instruction *User = cast<Instruction>(*UI++);
7813 if (isInstructionTriviallyDead(User)) {
7814 while (UI != E && *UI == User)
7815 ++UI; // If this instruction uses AI more than once, don't break UI.
7816
Chris Lattnerb53c2382005-10-24 06:22:12 +00007817 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007818 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007819 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007820 }
7821 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007822
7823 // This requires TargetData to get the alloca alignment and size information.
7824 if (!TD) return 0;
7825
Chris Lattnerb3f83972005-10-24 06:03:58 +00007826 // Get the type really allocated and the type casted to.
7827 const Type *AllocElTy = AI.getAllocatedType();
7828 const Type *CastElTy = PTy->getElementType();
7829 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007830
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007831 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7832 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007833 if (CastElTyAlign < AllocElTyAlign) return 0;
7834
Chris Lattner39387a52005-10-24 06:35:18 +00007835 // If the allocation has multiple uses, only promote it if we are strictly
7836 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007837 // same, we open the door to infinite loops of various kinds. (A reference
7838 // from a dbg.declare doesn't count as a use for this purpose.)
7839 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7840 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007841
Duncan Sands777d2302009-05-09 07:06:46 +00007842 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7843 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007844 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007845
Chris Lattner455fcc82005-10-29 03:19:53 +00007846 // See if we can satisfy the modulus by pulling a scale out of the array
7847 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007848 unsigned ArraySizeScale;
7849 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007850 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007851 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7852 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007853
Chris Lattner455fcc82005-10-29 03:19:53 +00007854 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7855 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007856 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7857 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007858
Chris Lattner455fcc82005-10-29 03:19:53 +00007859 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7860 Value *Amt = 0;
7861 if (Scale == 1) {
7862 Amt = NumElements;
7863 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007864 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007865 // Insert before the alloca, not before the cast.
7866 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007867 }
7868
Jeff Cohen86796be2007-04-04 16:58:57 +00007869 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007870 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007871 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007872 }
7873
Victor Hernandeza276c602009-10-17 01:18:07 +00007874 AllocationInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007875 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007876 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007877
Dale Johannesena0a66372009-03-05 00:39:02 +00007878 // If the allocation has one real use plus a dbg.declare, just remove the
7879 // declare.
7880 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7881 EraseInstFromFunction(*DI);
7882 }
7883 // If the allocation has multiple real uses, insert a cast and change all
7884 // things that used it to use the new cast. This will also hack on CI, but it
7885 // will die soon.
7886 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007887 // New is the allocation instruction, pointer typed. AI is the original
7888 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007889 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007890 AI.replaceAllUsesWith(NewCast);
7891 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007892 return ReplaceInstUsesWith(CI, New);
7893}
7894
Chris Lattner70074e02006-05-13 02:06:03 +00007895/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007896/// and return it as type Ty without inserting any new casts and without
7897/// changing the computed value. This is used by code that tries to decide
7898/// whether promoting or shrinking integer operations to wider or smaller types
7899/// will allow us to eliminate a truncate or extend.
7900///
7901/// This is a truncation operation if Ty is smaller than V->getType(), or an
7902/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007903///
7904/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7905/// should return true if trunc(V) can be computed by computing V in the smaller
7906/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7907/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7908/// efficiently truncated.
7909///
7910/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7911/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7912/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007913bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007914 unsigned CastOpc,
7915 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007916 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007917 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007918 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007919
7920 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007921 if (!I) return false;
7922
Dan Gohman6de29f82009-06-15 22:12:54 +00007923 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007924
Chris Lattner951626b2007-08-02 06:11:14 +00007925 // If this is an extension or truncate, we can often eliminate it.
7926 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7927 // If this is a cast from the destination type, we can trivially eliminate
7928 // it, and this will remove a cast overall.
7929 if (I->getOperand(0)->getType() == Ty) {
7930 // If the first operand is itself a cast, and is eliminable, do not count
7931 // this as an eliminable cast. We would prefer to eliminate those two
7932 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007933 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007934 ++NumCastsRemoved;
7935 return true;
7936 }
7937 }
7938
7939 // We can't extend or shrink something that has multiple uses: doing so would
7940 // require duplicating the instruction in general, which isn't profitable.
7941 if (!I->hasOneUse()) return false;
7942
Evan Chengf35fd542009-01-15 17:01:23 +00007943 unsigned Opc = I->getOpcode();
7944 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007945 case Instruction::Add:
7946 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007947 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007948 case Instruction::And:
7949 case Instruction::Or:
7950 case Instruction::Xor:
7951 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007952 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007953 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007954 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007955 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007956
Eli Friedman070a9812009-07-13 22:46:01 +00007957 case Instruction::UDiv:
7958 case Instruction::URem: {
7959 // UDiv and URem can be truncated if all the truncated bits are zero.
7960 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7961 uint32_t BitWidth = Ty->getScalarSizeInBits();
7962 if (BitWidth < OrigBitWidth) {
7963 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7964 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7965 MaskedValueIsZero(I->getOperand(1), Mask)) {
7966 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7967 NumCastsRemoved) &&
7968 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7969 NumCastsRemoved);
7970 }
7971 }
7972 break;
7973 }
Chris Lattner46b96052006-11-29 07:18:39 +00007974 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007975 // If we are truncating the result of this SHL, and if it's a shift of a
7976 // constant amount, we can always perform a SHL in a smaller type.
7977 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007978 uint32_t BitWidth = Ty->getScalarSizeInBits();
7979 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007980 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007981 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007982 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007983 }
7984 break;
7985 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007986 // If this is a truncate of a logical shr, we can truncate it to a smaller
7987 // lshr iff we know that the bits we would otherwise be shifting in are
7988 // already zeros.
7989 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007990 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7991 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007992 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007993 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007994 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7995 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007996 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007997 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007998 }
7999 }
Chris Lattner46b96052006-11-29 07:18:39 +00008000 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008001 case Instruction::ZExt:
8002 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008003 case Instruction::Trunc:
8004 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008005 // can safely replace it. Note that replacing it does not reduce the number
8006 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008007 if (Opc == CastOpc)
8008 return true;
8009
8010 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008011 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008012 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008013 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008014 case Instruction::Select: {
8015 SelectInst *SI = cast<SelectInst>(I);
8016 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008017 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008018 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008019 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008020 }
Chris Lattner8114b712008-06-18 04:00:49 +00008021 case Instruction::PHI: {
8022 // We can change a phi if we can change all operands.
8023 PHINode *PN = cast<PHINode>(I);
8024 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8025 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008026 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008027 return false;
8028 return true;
8029 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008030 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008031 // TODO: Can handle more cases here.
8032 break;
8033 }
8034
8035 return false;
8036}
8037
8038/// EvaluateInDifferentType - Given an expression that
8039/// CanEvaluateInDifferentType returns true for, actually insert the code to
8040/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008041Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008042 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008043 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00008044 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00008045 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008046
8047 // Otherwise, it must be an instruction.
8048 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008049 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008050 unsigned Opc = I->getOpcode();
8051 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008052 case Instruction::Add:
8053 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008054 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008055 case Instruction::And:
8056 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008057 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008058 case Instruction::AShr:
8059 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008060 case Instruction::Shl:
8061 case Instruction::UDiv:
8062 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008063 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008064 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008065 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008066 break;
8067 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008068 case Instruction::Trunc:
8069 case Instruction::ZExt:
8070 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008071 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008072 // just return the source. There's no need to insert it because it is not
8073 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008074 if (I->getOperand(0)->getType() == Ty)
8075 return I->getOperand(0);
8076
Chris Lattner8114b712008-06-18 04:00:49 +00008077 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008078 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008079 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008080 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008081 case Instruction::Select: {
8082 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8083 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8084 Res = SelectInst::Create(I->getOperand(0), True, False);
8085 break;
8086 }
Chris Lattner8114b712008-06-18 04:00:49 +00008087 case Instruction::PHI: {
8088 PHINode *OPN = cast<PHINode>(I);
8089 PHINode *NPN = PHINode::Create(Ty);
8090 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8091 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8092 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8093 }
8094 Res = NPN;
8095 break;
8096 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008097 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008098 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008099 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008100 break;
8101 }
8102
Chris Lattner8114b712008-06-18 04:00:49 +00008103 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008104 return InsertNewInstBefore(Res, *I);
8105}
8106
Reid Spencer3da59db2006-11-27 01:05:10 +00008107/// @brief Implement the transforms common to all CastInst visitors.
8108Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008109 Value *Src = CI.getOperand(0);
8110
Dan Gohman23d9d272007-05-11 21:10:54 +00008111 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008112 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008113 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008114 if (Instruction::CastOps opc =
8115 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8116 // The first cast (CSrc) is eliminable so we need to fix up or replace
8117 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008118 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008119 }
8120 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008121
Reid Spencer3da59db2006-11-27 01:05:10 +00008122 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008123 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8124 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8125 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008126
8127 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008128 if (isa<PHINode>(Src))
8129 if (Instruction *NV = FoldOpIntoPhi(CI))
8130 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008131
Reid Spencer3da59db2006-11-27 01:05:10 +00008132 return 0;
8133}
8134
Chris Lattner46cd5a12009-01-09 05:44:56 +00008135/// FindElementAtOffset - Given a type and a constant offset, determine whether
8136/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008137/// the specified offset. If so, fill them into NewIndices and return the
8138/// resultant element type, otherwise return null.
8139static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8140 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008141 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008142 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008143 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008144 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008145
8146 // Start with the index over the outer type. Note that the type size
8147 // might be zero (even if the offset isn't zero) if the indexed type
8148 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008149 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008150 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008151 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008152 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008153 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008154
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008155 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008156 if (Offset < 0) {
8157 --FirstIdx;
8158 Offset += TySize;
8159 assert(Offset >= 0);
8160 }
8161 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8162 }
8163
Owen Andersoneed707b2009-07-24 23:12:02 +00008164 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008165
8166 // Index into the types. If we fail, set OrigBase to null.
8167 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008168 // Indexing into tail padding between struct/array elements.
8169 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008170 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008171
Chris Lattner46cd5a12009-01-09 05:44:56 +00008172 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8173 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008174 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8175 "Offset must stay within the indexed type");
8176
Chris Lattner46cd5a12009-01-09 05:44:56 +00008177 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008178 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008179
8180 Offset -= SL->getElementOffset(Elt);
8181 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008182 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008183 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008184 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008185 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008186 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008187 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008188 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008189 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008190 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008191 }
8192 }
8193
Chris Lattner3914f722009-01-24 01:00:13 +00008194 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008195}
8196
Chris Lattnerd3e28342007-04-27 17:44:50 +00008197/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8198Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8199 Value *Src = CI.getOperand(0);
8200
Chris Lattnerd3e28342007-04-27 17:44:50 +00008201 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008202 // If casting the result of a getelementptr instruction with no offset, turn
8203 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008204 if (GEP->hasAllZeroIndices()) {
8205 // Changing the cast operand is usually not a good idea but it is safe
8206 // here because the pointer operand is being replaced with another
8207 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008208 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008209 CI.setOperand(0, GEP->getOperand(0));
8210 return &CI;
8211 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008212
8213 // If the GEP has a single use, and the base pointer is a bitcast, and the
8214 // GEP computes a constant offset, see if we can convert these three
8215 // instructions into fewer. This typically happens with unions and other
8216 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008217 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008218 if (GEP->hasAllConstantIndices()) {
8219 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008220 ConstantInt *OffsetV =
8221 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008222 int64_t Offset = OffsetV->getSExtValue();
8223
8224 // Get the base pointer input of the bitcast, and the type it points to.
8225 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8226 const Type *GEPIdxTy =
8227 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008228 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008229 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008230 // If we were able to index down into an element, create the GEP
8231 // and bitcast the result. This eliminates one bitcast, potentially
8232 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008233 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8234 Builder->CreateInBoundsGEP(OrigBase,
8235 NewIndices.begin(), NewIndices.end()) :
8236 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008237 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008238
Chris Lattner46cd5a12009-01-09 05:44:56 +00008239 if (isa<BitCastInst>(CI))
8240 return new BitCastInst(NGEP, CI.getType());
8241 assert(isa<PtrToIntInst>(CI));
8242 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008243 }
8244 }
8245 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008246 }
8247
8248 return commonCastTransforms(CI);
8249}
8250
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008251/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8252/// type like i42. We don't want to introduce operations on random non-legal
8253/// integer types where they don't already exist in the code. In the future,
8254/// we should consider making this based off target-data, so that 32-bit targets
8255/// won't get i64 operations etc.
8256static bool isSafeIntegerType(const Type *Ty) {
8257 switch (Ty->getPrimitiveSizeInBits()) {
8258 case 8:
8259 case 16:
8260 case 32:
8261 case 64:
8262 return true;
8263 default:
8264 return false;
8265 }
8266}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008267
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008268/// commonIntCastTransforms - This function implements the common transforms
8269/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008270Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8271 if (Instruction *Result = commonCastTransforms(CI))
8272 return Result;
8273
8274 Value *Src = CI.getOperand(0);
8275 const Type *SrcTy = Src->getType();
8276 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008277 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8278 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008279
Reid Spencer3da59db2006-11-27 01:05:10 +00008280 // See if we can simplify any instructions used by the LHS whose sole
8281 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008282 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008283 return &CI;
8284
8285 // If the source isn't an instruction or has more than one use then we
8286 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008287 Instruction *SrcI = dyn_cast<Instruction>(Src);
8288 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008289 return 0;
8290
Chris Lattnerc739cd62007-03-03 05:27:34 +00008291 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008292 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008293 // Only do this if the dest type is a simple type, don't convert the
8294 // expression tree to something weird like i93 unless the source is also
8295 // strange.
8296 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008297 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8298 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008299 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008300 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008301 // eliminates the cast, so it is always a win. If this is a zero-extension,
8302 // we need to do an AND to maintain the clear top-part of the computation,
8303 // so we require that the input have eliminated at least one cast. If this
8304 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008305 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008306 bool DoXForm = false;
8307 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008308 switch (CI.getOpcode()) {
8309 default:
8310 // All the others use floating point so we shouldn't actually
8311 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008312 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008313 case Instruction::Trunc:
8314 DoXForm = true;
8315 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008316 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008317 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008318 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008319 // If it's unnecessary to issue an AND to clear the high bits, it's
8320 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008321 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008322 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8323 if (MaskedValueIsZero(TryRes, Mask))
8324 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008325
8326 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008327 if (TryI->use_empty())
8328 EraseInstFromFunction(*TryI);
8329 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008330 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008331 }
Evan Chengf35fd542009-01-15 17:01:23 +00008332 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008333 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008334 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008335 // If we do not have to emit the truncate + sext pair, then it's always
8336 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008337 //
8338 // It's not safe to eliminate the trunc + sext pair if one of the
8339 // eliminated cast is a truncate. e.g.
8340 // t2 = trunc i32 t1 to i16
8341 // t3 = sext i16 t2 to i32
8342 // !=
8343 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008344 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008345 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8346 if (NumSignBits > (DestBitSize - SrcBitSize))
8347 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008348
8349 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008350 if (TryI->use_empty())
8351 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008352 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008353 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008354 }
Evan Chengf35fd542009-01-15 17:01:23 +00008355 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008356
8357 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008358 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8359 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008360 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8361 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008362 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008363 // Just replace this cast with the result.
8364 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008365
Reid Spencer3da59db2006-11-27 01:05:10 +00008366 assert(Res->getType() == DestTy);
8367 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008368 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008369 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008370 // Just replace this cast with the result.
8371 return ReplaceInstUsesWith(CI, Res);
8372 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008373 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008374
8375 // If the high bits are already zero, just replace this cast with the
8376 // result.
8377 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8378 if (MaskedValueIsZero(Res, Mask))
8379 return ReplaceInstUsesWith(CI, Res);
8380
8381 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008382 Constant *C = ConstantInt::get(*Context,
8383 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008384 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008385 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008386 case Instruction::SExt: {
8387 // If the high bits are already filled with sign bit, just replace this
8388 // cast with the result.
8389 unsigned NumSignBits = ComputeNumSignBits(Res);
8390 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008391 return ReplaceInstUsesWith(CI, Res);
8392
Reid Spencer3da59db2006-11-27 01:05:10 +00008393 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008394 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008395 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008396 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008397 }
8398 }
8399
8400 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8401 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8402
8403 switch (SrcI->getOpcode()) {
8404 case Instruction::Add:
8405 case Instruction::Mul:
8406 case Instruction::And:
8407 case Instruction::Or:
8408 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008409 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008410 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8411 // Don't insert two casts unless at least one can be eliminated.
8412 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008413 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008414 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8415 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008416 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008417 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008418 }
8419 }
8420
8421 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8422 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8423 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008424 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008425 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008426 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008427 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008428 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008429 }
8430 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008431
Eli Friedman65445c52009-07-13 21:45:57 +00008432 case Instruction::Shl: {
8433 // Canonicalize trunc inside shl, if we can.
8434 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8435 if (CI && DestBitSize < SrcBitSize &&
8436 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008437 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8438 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008439 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008440 }
8441 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008442 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008443 }
8444 return 0;
8445}
8446
Chris Lattner8a9f5712007-04-11 06:57:46 +00008447Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008448 if (Instruction *Result = commonIntCastTransforms(CI))
8449 return Result;
8450
8451 Value *Src = CI.getOperand(0);
8452 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008453 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8454 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008455
8456 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008457 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008458 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008459 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008460 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008461 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008462 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008463
Chris Lattner4f9797d2009-03-24 18:15:30 +00008464 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8465 ConstantInt *ShAmtV = 0;
8466 Value *ShiftOp = 0;
8467 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008468 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008469 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8470
8471 // Get a mask for the bits shifting in.
8472 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8473 if (MaskedValueIsZero(ShiftOp, Mask)) {
8474 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008475 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008476
8477 // Okay, we can shrink this. Truncate the input, then return a new
8478 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008479 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008480 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008481 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008482 }
8483 }
8484
8485 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008486}
8487
Evan Chengb98a10e2008-03-24 00:21:34 +00008488/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8489/// in order to eliminate the icmp.
8490Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8491 bool DoXform) {
8492 // If we are just checking for a icmp eq of a single bit and zext'ing it
8493 // to an integer, then shift the bit to the appropriate place and then
8494 // cast to integer to avoid the comparison.
8495 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8496 const APInt &Op1CV = Op1C->getValue();
8497
8498 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8499 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8500 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8501 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8502 if (!DoXform) return ICI;
8503
8504 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008505 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008506 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008507 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008508 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008509 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008510
8511 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008512 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008513 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008514 }
8515
8516 return ReplaceInstUsesWith(CI, In);
8517 }
8518
8519
8520
8521 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8522 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8523 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8524 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8525 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8526 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8527 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8528 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8529 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8530 // This only works for EQ and NE
8531 ICI->isEquality()) {
8532 // If Op1C some other power of two, convert:
8533 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8534 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8535 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8536 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8537
8538 APInt KnownZeroMask(~KnownZero);
8539 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8540 if (!DoXform) return ICI;
8541
8542 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8543 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8544 // (X&4) == 2 --> false
8545 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008546 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008547 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008548 return ReplaceInstUsesWith(CI, Res);
8549 }
8550
8551 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8552 Value *In = ICI->getOperand(0);
8553 if (ShiftAmt) {
8554 // Perform a logical shr by shiftamt.
8555 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008556 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8557 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008558 }
8559
8560 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008561 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008562 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008563 }
8564
8565 if (CI.getType() == In->getType())
8566 return ReplaceInstUsesWith(CI, In);
8567 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008568 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008569 }
8570 }
8571 }
8572
8573 return 0;
8574}
8575
Chris Lattner8a9f5712007-04-11 06:57:46 +00008576Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008577 // If one of the common conversion will work ..
8578 if (Instruction *Result = commonIntCastTransforms(CI))
8579 return Result;
8580
8581 Value *Src = CI.getOperand(0);
8582
Chris Lattnera84f47c2009-02-17 20:47:23 +00008583 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8584 // types and if the sizes are just right we can convert this into a logical
8585 // 'and' which will be much cheaper than the pair of casts.
8586 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8587 // Get the sizes of the types involved. We know that the intermediate type
8588 // will be smaller than A or C, but don't know the relation between A and C.
8589 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008590 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8591 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8592 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008593 // If we're actually extending zero bits, then if
8594 // SrcSize < DstSize: zext(a & mask)
8595 // SrcSize == DstSize: a & mask
8596 // SrcSize > DstSize: trunc(a) & mask
8597 if (SrcSize < DstSize) {
8598 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008599 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008600 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008601 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008602 }
8603
8604 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008605 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008606 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008607 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008608 }
8609 if (SrcSize > DstSize) {
8610 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008611 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008612 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008613 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008614 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008615 }
8616 }
8617
Evan Chengb98a10e2008-03-24 00:21:34 +00008618 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8619 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008620
Evan Chengb98a10e2008-03-24 00:21:34 +00008621 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8622 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8623 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8624 // of the (zext icmp) will be transformed.
8625 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8626 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8627 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8628 (transformZExtICmp(LHS, CI, false) ||
8629 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008630 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8631 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008632 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008633 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008634 }
8635
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008636 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008637 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8638 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8639 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8640 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008641 if (TI0->getType() == CI.getType())
8642 return
8643 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008644 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008645 }
8646
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008647 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8648 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8649 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8650 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8651 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8652 And->getOperand(1) == C)
8653 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8654 Value *TI0 = TI->getOperand(0);
8655 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008656 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008657 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008658 return BinaryOperator::CreateXor(NewAnd, ZC);
8659 }
8660 }
8661
Reid Spencer3da59db2006-11-27 01:05:10 +00008662 return 0;
8663}
8664
Chris Lattner8a9f5712007-04-11 06:57:46 +00008665Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008666 if (Instruction *I = commonIntCastTransforms(CI))
8667 return I;
8668
Chris Lattner8a9f5712007-04-11 06:57:46 +00008669 Value *Src = CI.getOperand(0);
8670
Dan Gohman1975d032008-10-30 20:40:10 +00008671 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008672 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008673 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008674 Constant::getAllOnesValue(CI.getType()),
8675 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008676
8677 // See if the value being truncated is already sign extended. If so, just
8678 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008679 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008680 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008681 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8682 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8683 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008684 unsigned NumSignBits = ComputeNumSignBits(Op);
8685
8686 if (OpBits == DestBits) {
8687 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8688 // bits, it is already ready.
8689 if (NumSignBits > DestBits-MidBits)
8690 return ReplaceInstUsesWith(CI, Op);
8691 } else if (OpBits < DestBits) {
8692 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8693 // bits, just sext from i32.
8694 if (NumSignBits > OpBits-MidBits)
8695 return new SExtInst(Op, CI.getType(), "tmp");
8696 } else {
8697 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8698 // bits, just truncate to i32.
8699 if (NumSignBits > OpBits-MidBits)
8700 return new TruncInst(Op, CI.getType(), "tmp");
8701 }
8702 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008703
8704 // If the input is a shl/ashr pair of a same constant, then this is a sign
8705 // extension from a smaller value. If we could trust arbitrary bitwidth
8706 // integers, we could turn this into a truncate to the smaller bit and then
8707 // use a sext for the whole extension. Since we don't, look deeper and check
8708 // for a truncate. If the source and dest are the same type, eliminate the
8709 // trunc and extend and just do shifts. For example, turn:
8710 // %a = trunc i32 %i to i8
8711 // %b = shl i8 %a, 6
8712 // %c = ashr i8 %b, 6
8713 // %d = sext i8 %c to i32
8714 // into:
8715 // %a = shl i32 %i, 30
8716 // %d = ashr i32 %a, 30
8717 Value *A = 0;
8718 ConstantInt *BA = 0, *CA = 0;
8719 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008720 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008721 BA == CA && isa<TruncInst>(A)) {
8722 Value *I = cast<TruncInst>(A)->getOperand(0);
8723 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008724 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8725 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008726 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008727 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008728 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008729 return BinaryOperator::CreateAShr(I, ShAmtV);
8730 }
8731 }
8732
Chris Lattnerba417832007-04-11 06:12:58 +00008733 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008734}
8735
Chris Lattnerb7530652008-01-27 05:29:54 +00008736/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8737/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008738static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008739 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008740 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008741 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008742 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8743 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008744 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008745 return 0;
8746}
8747
8748/// LookThroughFPExtensions - If this is an fp extension instruction, look
8749/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008750static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008751 if (Instruction *I = dyn_cast<Instruction>(V))
8752 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008753 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008754
8755 // If this value is a constant, return the constant in the smallest FP type
8756 // that can accurately represent it. This allows us to turn
8757 // (float)((double)X+2.0) into x+2.0f.
8758 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008759 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008760 return V; // No constant folding of this.
8761 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008762 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008763 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008764 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008765 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008766 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008767 return V;
8768 // Don't try to shrink to various long double types.
8769 }
8770
8771 return V;
8772}
8773
8774Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8775 if (Instruction *I = commonCastTransforms(CI))
8776 return I;
8777
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008778 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008779 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008780 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008781 // many builtins (sqrt, etc).
8782 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8783 if (OpI && OpI->hasOneUse()) {
8784 switch (OpI->getOpcode()) {
8785 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008786 case Instruction::FAdd:
8787 case Instruction::FSub:
8788 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008789 case Instruction::FDiv:
8790 case Instruction::FRem:
8791 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008792 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8793 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008794 if (LHSTrunc->getType() != SrcTy &&
8795 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008796 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008797 // If the source types were both smaller than the destination type of
8798 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008799 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8800 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008801 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8802 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008803 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008804 }
8805 }
8806 break;
8807 }
8808 }
8809 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008810}
8811
8812Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8813 return commonCastTransforms(CI);
8814}
8815
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008816Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008817 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8818 if (OpI == 0)
8819 return commonCastTransforms(FI);
8820
8821 // fptoui(uitofp(X)) --> X
8822 // fptoui(sitofp(X)) --> X
8823 // This is safe if the intermediate type has enough bits in its mantissa to
8824 // accurately represent all values of X. For example, do not do this with
8825 // i64->float->i64. This is also safe for sitofp case, because any negative
8826 // 'X' value would cause an undefined result for the fptoui.
8827 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8828 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008829 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008830 OpI->getType()->getFPMantissaWidth())
8831 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008832
8833 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008834}
8835
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008836Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008837 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8838 if (OpI == 0)
8839 return commonCastTransforms(FI);
8840
8841 // fptosi(sitofp(X)) --> X
8842 // fptosi(uitofp(X)) --> X
8843 // This is safe if the intermediate type has enough bits in its mantissa to
8844 // accurately represent all values of X. For example, do not do this with
8845 // i64->float->i64. This is also safe for sitofp case, because any negative
8846 // 'X' value would cause an undefined result for the fptoui.
8847 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8848 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008849 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008850 OpI->getType()->getFPMantissaWidth())
8851 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008852
8853 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008854}
8855
8856Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8857 return commonCastTransforms(CI);
8858}
8859
8860Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8861 return commonCastTransforms(CI);
8862}
8863
Chris Lattnera0e69692009-03-24 18:35:40 +00008864Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8865 // If the destination integer type is smaller than the intptr_t type for
8866 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8867 // trunc to be exposed to other transforms. Don't do this for extending
8868 // ptrtoint's, because we don't know if the target sign or zero extends its
8869 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008870 if (TD &&
8871 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008872 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8873 TD->getIntPtrType(CI.getContext()),
8874 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008875 return new TruncInst(P, CI.getType());
8876 }
8877
Chris Lattnerd3e28342007-04-27 17:44:50 +00008878 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008879}
8880
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008881Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008882 // If the source integer type is larger than the intptr_t type for
8883 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8884 // allows the trunc to be exposed to other transforms. Don't do this for
8885 // extending inttoptr's, because we don't know if the target sign or zero
8886 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008887 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008888 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008889 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8890 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008891 return new IntToPtrInst(P, CI.getType());
8892 }
8893
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008894 if (Instruction *I = commonCastTransforms(CI))
8895 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008896
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008897 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008898}
8899
Chris Lattnerd3e28342007-04-27 17:44:50 +00008900Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008901 // If the operands are integer typed then apply the integer transforms,
8902 // otherwise just apply the common ones.
8903 Value *Src = CI.getOperand(0);
8904 const Type *SrcTy = Src->getType();
8905 const Type *DestTy = CI.getType();
8906
Eli Friedman7e25d452009-07-13 20:53:00 +00008907 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008908 if (Instruction *I = commonPointerCastTransforms(CI))
8909 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008910 } else {
8911 if (Instruction *Result = commonCastTransforms(CI))
8912 return Result;
8913 }
8914
8915
8916 // Get rid of casts from one type to the same type. These are useless and can
8917 // be replaced by the operand.
8918 if (DestTy == Src->getType())
8919 return ReplaceInstUsesWith(CI, Src);
8920
Reid Spencer3da59db2006-11-27 01:05:10 +00008921 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008922 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8923 const Type *DstElTy = DstPTy->getElementType();
8924 const Type *SrcElTy = SrcPTy->getElementType();
8925
Nate Begeman83ad90a2008-03-31 00:22:16 +00008926 // If the address spaces don't match, don't eliminate the bitcast, which is
8927 // required for changing types.
8928 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8929 return 0;
8930
Victor Hernandez83d63912009-09-18 22:35:49 +00008931 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008932 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008933 // There is no need to modify malloc calls because it is their bitcast that
8934 // needs to be cleaned up.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008935 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8936 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8937 return V;
8938
Chris Lattnerd717c182007-05-05 22:32:24 +00008939 // If the source and destination are pointers, and this cast is equivalent
8940 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008941 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008942 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008943 unsigned NumZeros = 0;
8944 while (SrcElTy != DstElTy &&
8945 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8946 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8947 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8948 ++NumZeros;
8949 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008950
Chris Lattnerd3e28342007-04-27 17:44:50 +00008951 // If we found a path from the src to dest, create the getelementptr now.
8952 if (SrcElTy == DstElTy) {
8953 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008954 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8955 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008956 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008957 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008958
Eli Friedman2451a642009-07-18 23:06:53 +00008959 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8960 if (DestVTy->getNumElements() == 1) {
8961 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008962 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008963 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008964 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008965 }
8966 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8967 }
8968 }
8969
8970 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8971 if (SrcVTy->getNumElements() == 1) {
8972 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008973 Value *Elem =
8974 Builder->CreateExtractElement(Src,
8975 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008976 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8977 }
8978 }
8979 }
8980
Reid Spencer3da59db2006-11-27 01:05:10 +00008981 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8982 if (SVI->hasOneUse()) {
8983 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8984 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008985 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008986 cast<VectorType>(DestTy)->getNumElements() ==
8987 SVI->getType()->getNumElements() &&
8988 SVI->getType()->getNumElements() ==
8989 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008990 CastInst *Tmp;
8991 // If either of the operands is a cast from CI.getType(), then
8992 // evaluating the shuffle in the casted destination's type will allow
8993 // us to eliminate at least one cast.
8994 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8995 Tmp->getOperand(0)->getType() == DestTy) ||
8996 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8997 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008998 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8999 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00009000 // Return a new shuffle vector. Use the same element ID's, as we
9001 // know the vector types match #elts.
9002 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009003 }
9004 }
9005 }
9006 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009007 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009008}
9009
Chris Lattnere576b912004-04-09 23:46:01 +00009010/// GetSelectFoldableOperands - We want to turn code that looks like this:
9011/// %C = or %A, %B
9012/// %D = select %cond, %C, %A
9013/// into:
9014/// %C = select %cond, %B, 0
9015/// %D = or %A, %C
9016///
9017/// Assuming that the specified instruction is an operand to the select, return
9018/// a bitmask indicating which operands of this instruction are foldable if they
9019/// equal the other incoming value of the select.
9020///
9021static unsigned GetSelectFoldableOperands(Instruction *I) {
9022 switch (I->getOpcode()) {
9023 case Instruction::Add:
9024 case Instruction::Mul:
9025 case Instruction::And:
9026 case Instruction::Or:
9027 case Instruction::Xor:
9028 return 3; // Can fold through either operand.
9029 case Instruction::Sub: // Can only fold on the amount subtracted.
9030 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009031 case Instruction::LShr:
9032 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009033 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009034 default:
9035 return 0; // Cannot fold
9036 }
9037}
9038
9039/// GetSelectFoldableConstant - For the same transformation as the previous
9040/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009041static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009042 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009043 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009044 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009045 case Instruction::Add:
9046 case Instruction::Sub:
9047 case Instruction::Or:
9048 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009049 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009050 case Instruction::LShr:
9051 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009052 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009053 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009054 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009055 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009056 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009057 }
9058}
9059
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009060/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9061/// have the same opcode and only one use each. Try to simplify this.
9062Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9063 Instruction *FI) {
9064 if (TI->getNumOperands() == 1) {
9065 // If this is a non-volatile load or a cast from the same type,
9066 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009067 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009068 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9069 return 0;
9070 } else {
9071 return 0; // unknown unary op.
9072 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009073
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009074 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009075 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009076 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009077 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009078 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009079 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009080 }
9081
Reid Spencer832254e2007-02-02 02:16:23 +00009082 // Only handle binary operators here.
9083 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009084 return 0;
9085
9086 // Figure out if the operations have any operands in common.
9087 Value *MatchOp, *OtherOpT, *OtherOpF;
9088 bool MatchIsOpZero;
9089 if (TI->getOperand(0) == FI->getOperand(0)) {
9090 MatchOp = TI->getOperand(0);
9091 OtherOpT = TI->getOperand(1);
9092 OtherOpF = FI->getOperand(1);
9093 MatchIsOpZero = true;
9094 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9095 MatchOp = TI->getOperand(1);
9096 OtherOpT = TI->getOperand(0);
9097 OtherOpF = FI->getOperand(0);
9098 MatchIsOpZero = false;
9099 } else if (!TI->isCommutative()) {
9100 return 0;
9101 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9102 MatchOp = TI->getOperand(0);
9103 OtherOpT = TI->getOperand(1);
9104 OtherOpF = FI->getOperand(0);
9105 MatchIsOpZero = true;
9106 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9107 MatchOp = TI->getOperand(1);
9108 OtherOpT = TI->getOperand(0);
9109 OtherOpF = FI->getOperand(1);
9110 MatchIsOpZero = true;
9111 } else {
9112 return 0;
9113 }
9114
9115 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009116 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9117 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009118 InsertNewInstBefore(NewSI, SI);
9119
9120 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9121 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009122 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009123 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009124 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009125 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009126 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009127 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009128}
9129
Evan Chengde621922009-03-31 20:42:45 +00009130static bool isSelect01(Constant *C1, Constant *C2) {
9131 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9132 if (!C1I)
9133 return false;
9134 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9135 if (!C2I)
9136 return false;
9137 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9138}
9139
9140/// FoldSelectIntoOp - Try fold the select into one of the operands to
9141/// facilitate further optimization.
9142Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9143 Value *FalseVal) {
9144 // See the comment above GetSelectFoldableOperands for a description of the
9145 // transformation we are doing here.
9146 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9147 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9148 !isa<Constant>(FalseVal)) {
9149 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9150 unsigned OpToFold = 0;
9151 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9152 OpToFold = 1;
9153 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9154 OpToFold = 2;
9155 }
9156
9157 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009158 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009159 Value *OOp = TVI->getOperand(2-OpToFold);
9160 // Avoid creating select between 2 constants unless it's selecting
9161 // between 0 and 1.
9162 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9163 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9164 InsertNewInstBefore(NewSel, SI);
9165 NewSel->takeName(TVI);
9166 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9167 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009168 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009169 }
9170 }
9171 }
9172 }
9173 }
9174
9175 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9176 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9177 !isa<Constant>(TrueVal)) {
9178 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9179 unsigned OpToFold = 0;
9180 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9181 OpToFold = 1;
9182 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9183 OpToFold = 2;
9184 }
9185
9186 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009187 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009188 Value *OOp = FVI->getOperand(2-OpToFold);
9189 // Avoid creating select between 2 constants unless it's selecting
9190 // between 0 and 1.
9191 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9192 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9193 InsertNewInstBefore(NewSel, SI);
9194 NewSel->takeName(FVI);
9195 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9196 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009197 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009198 }
9199 }
9200 }
9201 }
9202 }
9203
9204 return 0;
9205}
9206
Dan Gohman81b28ce2008-09-16 18:46:06 +00009207/// visitSelectInstWithICmp - Visit a SelectInst that has an
9208/// ICmpInst as its first operand.
9209///
9210Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9211 ICmpInst *ICI) {
9212 bool Changed = false;
9213 ICmpInst::Predicate Pred = ICI->getPredicate();
9214 Value *CmpLHS = ICI->getOperand(0);
9215 Value *CmpRHS = ICI->getOperand(1);
9216 Value *TrueVal = SI.getTrueValue();
9217 Value *FalseVal = SI.getFalseValue();
9218
9219 // Check cases where the comparison is with a constant that
9220 // can be adjusted to fit the min/max idiom. We may edit ICI in
9221 // place here, so make sure the select is the only user.
9222 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009223 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009224 switch (Pred) {
9225 default: break;
9226 case ICmpInst::ICMP_ULT:
9227 case ICmpInst::ICMP_SLT: {
9228 // X < MIN ? T : F --> F
9229 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9230 return ReplaceInstUsesWith(SI, FalseVal);
9231 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009232 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009233 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9234 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9235 Pred = ICmpInst::getSwappedPredicate(Pred);
9236 CmpRHS = AdjustedRHS;
9237 std::swap(FalseVal, TrueVal);
9238 ICI->setPredicate(Pred);
9239 ICI->setOperand(1, CmpRHS);
9240 SI.setOperand(1, TrueVal);
9241 SI.setOperand(2, FalseVal);
9242 Changed = true;
9243 }
9244 break;
9245 }
9246 case ICmpInst::ICMP_UGT:
9247 case ICmpInst::ICMP_SGT: {
9248 // X > MAX ? T : F --> F
9249 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9250 return ReplaceInstUsesWith(SI, FalseVal);
9251 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009252 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009253 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9254 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9255 Pred = ICmpInst::getSwappedPredicate(Pred);
9256 CmpRHS = AdjustedRHS;
9257 std::swap(FalseVal, TrueVal);
9258 ICI->setPredicate(Pred);
9259 ICI->setOperand(1, CmpRHS);
9260 SI.setOperand(1, TrueVal);
9261 SI.setOperand(2, FalseVal);
9262 Changed = true;
9263 }
9264 break;
9265 }
9266 }
9267
Dan Gohman1975d032008-10-30 20:40:10 +00009268 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9269 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009270 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009271 if (match(TrueVal, m_ConstantInt<-1>()) &&
9272 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009273 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009274 else if (match(TrueVal, m_ConstantInt<0>()) &&
9275 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009276 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9277
Dan Gohman1975d032008-10-30 20:40:10 +00009278 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9279 // If we are just checking for a icmp eq of a single bit and zext'ing it
9280 // to an integer, then shift the bit to the appropriate place and then
9281 // cast to integer to avoid the comparison.
9282 const APInt &Op1CV = CI->getValue();
9283
9284 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9285 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9286 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009287 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009288 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009289 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009290 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009291 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009292 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009293 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009294 if (In->getType() != SI.getType())
9295 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009296 true/*SExt*/, "tmp", ICI);
9297
9298 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009299 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009300 In->getName()+".not"), *ICI);
9301
9302 return ReplaceInstUsesWith(SI, In);
9303 }
9304 }
9305 }
9306
Dan Gohman81b28ce2008-09-16 18:46:06 +00009307 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9308 // Transform (X == Y) ? X : Y -> Y
9309 if (Pred == ICmpInst::ICMP_EQ)
9310 return ReplaceInstUsesWith(SI, FalseVal);
9311 // Transform (X != Y) ? X : Y -> X
9312 if (Pred == ICmpInst::ICMP_NE)
9313 return ReplaceInstUsesWith(SI, TrueVal);
9314 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9315
9316 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9317 // Transform (X == Y) ? Y : X -> X
9318 if (Pred == ICmpInst::ICMP_EQ)
9319 return ReplaceInstUsesWith(SI, FalseVal);
9320 // Transform (X != Y) ? Y : X -> Y
9321 if (Pred == ICmpInst::ICMP_NE)
9322 return ReplaceInstUsesWith(SI, TrueVal);
9323 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9324 }
9325
9326 /// NOTE: if we wanted to, this is where to detect integer ABS
9327
9328 return Changed ? &SI : 0;
9329}
9330
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009331/// isDefinedInBB - Return true if the value is an instruction defined in the
9332/// specified basicblock.
9333static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9334 const Instruction *I = dyn_cast<Instruction>(V);
9335 return I != 0 && I->getParent() == BB;
9336}
9337
9338
Chris Lattner3d69f462004-03-12 05:52:32 +00009339Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009340 Value *CondVal = SI.getCondition();
9341 Value *TrueVal = SI.getTrueValue();
9342 Value *FalseVal = SI.getFalseValue();
9343
9344 // select true, X, Y -> X
9345 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009346 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009347 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009348
9349 // select C, X, X -> X
9350 if (TrueVal == FalseVal)
9351 return ReplaceInstUsesWith(SI, TrueVal);
9352
Chris Lattnere87597f2004-10-16 18:11:37 +00009353 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9354 return ReplaceInstUsesWith(SI, FalseVal);
9355 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9356 return ReplaceInstUsesWith(SI, TrueVal);
9357 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9358 if (isa<Constant>(TrueVal))
9359 return ReplaceInstUsesWith(SI, TrueVal);
9360 else
9361 return ReplaceInstUsesWith(SI, FalseVal);
9362 }
9363
Owen Anderson1d0be152009-08-13 21:58:54 +00009364 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009365 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009366 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009367 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009368 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009369 } else {
9370 // Change: A = select B, false, C --> A = and !B, C
9371 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009372 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009373 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009374 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009375 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009376 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009377 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009378 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009379 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009380 } else {
9381 // Change: A = select B, C, true --> A = or !B, C
9382 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009383 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009384 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009385 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009386 }
9387 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009388
9389 // select a, b, a -> a&b
9390 // select a, a, b -> a|b
9391 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009392 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009393 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009394 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009395 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009396
Chris Lattner2eefe512004-04-09 19:05:30 +00009397 // Selecting between two integer constants?
9398 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9399 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009400 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009401 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009402 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009403 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009404 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009405 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009406 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009407 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009408 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009409 }
Chris Lattner457dd822004-06-09 07:59:58 +00009410
Reid Spencere4d87aa2006-12-23 06:05:41 +00009411 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009412 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009413 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009414 // non-constant value, eliminate this whole mess. This corresponds to
9415 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009416 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009417 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009418 cast<Constant>(IC->getOperand(1))->isNullValue())
9419 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9420 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009421 isa<ConstantInt>(ICA->getOperand(1)) &&
9422 (ICA->getOperand(1) == TrueValC ||
9423 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009424 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9425 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009426 // know whether we have a icmp_ne or icmp_eq and whether the
9427 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009428 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009429 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009430 Value *V = ICA;
9431 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009432 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009433 Instruction::Xor, V, ICA->getOperand(1)), SI);
9434 return ReplaceInstUsesWith(SI, V);
9435 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009436 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009437 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009438
9439 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009440 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9441 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009442 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009443 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9444 // This is not safe in general for floating point:
9445 // consider X== -0, Y== +0.
9446 // It becomes safe if either operand is a nonzero constant.
9447 ConstantFP *CFPt, *CFPf;
9448 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9449 !CFPt->getValueAPF().isZero()) ||
9450 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9451 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009452 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009453 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009454 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009455 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009456 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009457 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009458
Reid Spencere4d87aa2006-12-23 06:05:41 +00009459 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009460 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009461 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9462 // This is not safe in general for floating point:
9463 // consider X== -0, Y== +0.
9464 // It becomes safe if either operand is a nonzero constant.
9465 ConstantFP *CFPt, *CFPf;
9466 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9467 !CFPt->getValueAPF().isZero()) ||
9468 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9469 !CFPf->getValueAPF().isZero()))
9470 return ReplaceInstUsesWith(SI, FalseVal);
9471 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009472 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009473 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9474 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009475 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009476 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009477 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009478 }
9479
9480 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009481 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9482 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9483 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009484
Chris Lattner87875da2005-01-13 22:52:24 +00009485 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9486 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9487 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009488 Instruction *AddOp = 0, *SubOp = 0;
9489
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009490 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9491 if (TI->getOpcode() == FI->getOpcode())
9492 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9493 return IV;
9494
9495 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9496 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009497 if ((TI->getOpcode() == Instruction::Sub &&
9498 FI->getOpcode() == Instruction::Add) ||
9499 (TI->getOpcode() == Instruction::FSub &&
9500 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009501 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009502 } else if ((FI->getOpcode() == Instruction::Sub &&
9503 TI->getOpcode() == Instruction::Add) ||
9504 (FI->getOpcode() == Instruction::FSub &&
9505 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009506 AddOp = TI; SubOp = FI;
9507 }
9508
9509 if (AddOp) {
9510 Value *OtherAddOp = 0;
9511 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9512 OtherAddOp = AddOp->getOperand(1);
9513 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9514 OtherAddOp = AddOp->getOperand(0);
9515 }
9516
9517 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009518 // So at this point we know we have (Y -> OtherAddOp):
9519 // select C, (add X, Y), (sub X, Z)
9520 Value *NegVal; // Compute -Z
9521 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009522 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009523 } else {
9524 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009525 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009526 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009527 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009528
9529 Value *NewTrueOp = OtherAddOp;
9530 Value *NewFalseOp = NegVal;
9531 if (AddOp != TI)
9532 std::swap(NewTrueOp, NewFalseOp);
9533 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009534 SelectInst::Create(CondVal, NewTrueOp,
9535 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009536
9537 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009538 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009539 }
9540 }
9541 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009542
Chris Lattnere576b912004-04-09 23:46:01 +00009543 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009544 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009545 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9546 if (FoldI)
9547 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009548 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009549
Chris Lattner5d1704d2009-09-27 19:57:57 +00009550 // See if we can fold the select into a phi node. The true/false values have
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009551 // to be live in the predecessor blocks. If they are instructions in SI's
9552 // block, we can't map to the predecessor.
Chris Lattner5d1704d2009-09-27 19:57:57 +00009553 if (isa<PHINode>(SI.getCondition()) &&
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009554 (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9555 isa<PHINode>(SI.getTrueValue())) &&
9556 (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9557 isa<PHINode>(SI.getFalseValue())))
Chris Lattner5d1704d2009-09-27 19:57:57 +00009558 if (Instruction *NV = FoldOpIntoPhi(SI))
9559 return NV;
9560
Chris Lattnera1df33c2005-04-24 07:30:14 +00009561 if (BinaryOperator::isNot(CondVal)) {
9562 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9563 SI.setOperand(1, FalseVal);
9564 SI.setOperand(2, TrueVal);
9565 return &SI;
9566 }
9567
Chris Lattner3d69f462004-03-12 05:52:32 +00009568 return 0;
9569}
9570
Dan Gohmaneee962e2008-04-10 18:43:06 +00009571/// EnforceKnownAlignment - If the specified pointer points to an object that
9572/// we control, modify the object's alignment to PrefAlign. This isn't
9573/// often possible though. If alignment is important, a more reliable approach
9574/// is to simply align all global variables and allocation instructions to
9575/// their preferred alignment from the beginning.
9576///
9577static unsigned EnforceKnownAlignment(Value *V,
9578 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009579
Dan Gohmaneee962e2008-04-10 18:43:06 +00009580 User *U = dyn_cast<User>(V);
9581 if (!U) return Align;
9582
Dan Gohmanca178902009-07-17 20:47:02 +00009583 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009584 default: break;
9585 case Instruction::BitCast:
9586 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9587 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009588 // If all indexes are zero, it is just the alignment of the base pointer.
9589 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009590 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009591 if (!isa<Constant>(*i) ||
9592 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009593 AllZeroOperands = false;
9594 break;
9595 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009596
9597 if (AllZeroOperands) {
9598 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009599 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009600 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009601 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009602 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009603 }
9604
9605 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9606 // If there is a large requested alignment and we can, bump up the alignment
9607 // of the global.
9608 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009609 if (GV->getAlignment() >= PrefAlign)
9610 Align = GV->getAlignment();
9611 else {
9612 GV->setAlignment(PrefAlign);
9613 Align = PrefAlign;
9614 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009615 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009616 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9617 // If there is a requested alignment and if this is an alloca, round up.
9618 if (AI->getAlignment() >= PrefAlign)
9619 Align = AI->getAlignment();
9620 else {
9621 AI->setAlignment(PrefAlign);
9622 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009623 }
9624 }
9625
9626 return Align;
9627}
9628
9629/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9630/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9631/// and it is more than the alignment of the ultimate object, see if we can
9632/// increase the alignment of the ultimate object, making this check succeed.
9633unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9634 unsigned PrefAlign) {
9635 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9636 sizeof(PrefAlign) * CHAR_BIT;
9637 APInt Mask = APInt::getAllOnesValue(BitWidth);
9638 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9639 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9640 unsigned TrailZ = KnownZero.countTrailingOnes();
9641 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9642
9643 if (PrefAlign > Align)
9644 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9645
9646 // We don't need to make any adjustment.
9647 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009648}
9649
Chris Lattnerf497b022008-01-13 23:50:23 +00009650Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009651 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009652 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009653 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009654 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009655
9656 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009657 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009658 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009659 return MI;
9660 }
9661
9662 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9663 // load/store.
9664 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9665 if (MemOpLength == 0) return 0;
9666
Chris Lattner37ac6082008-01-14 00:28:35 +00009667 // Source and destination pointer types are always "i8*" for intrinsic. See
9668 // if the size is something we can handle with a single primitive load/store.
9669 // A single load+store correctly handles overlapping memory in the memmove
9670 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009671 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009672 if (Size == 0) return MI; // Delete this mem transfer.
9673
9674 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009675 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009676
Chris Lattner37ac6082008-01-14 00:28:35 +00009677 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009678 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009679 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009680
9681 // Memcpy forces the use of i8* for the source and destination. That means
9682 // that if you're using memcpy to move one double around, you'll get a cast
9683 // from double* to i8*. We'd much rather use a double load+store rather than
9684 // an i64 load+store, here because this improves the odds that the source or
9685 // dest address will be promotable. See if we can find a better type than the
9686 // integer datatype.
9687 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9688 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009689 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009690 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9691 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009692 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009693 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9694 if (STy->getNumElements() == 1)
9695 SrcETy = STy->getElementType(0);
9696 else
9697 break;
9698 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9699 if (ATy->getNumElements() == 1)
9700 SrcETy = ATy->getElementType();
9701 else
9702 break;
9703 } else
9704 break;
9705 }
9706
Dan Gohman8f8e2692008-05-23 01:52:21 +00009707 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009708 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009709 }
9710 }
9711
9712
Chris Lattnerf497b022008-01-13 23:50:23 +00009713 // If the memcpy/memmove provides better alignment info than we can
9714 // infer, use it.
9715 SrcAlign = std::max(SrcAlign, CopyAlign);
9716 DstAlign = std::max(DstAlign, CopyAlign);
9717
Chris Lattner08142f22009-08-30 19:47:22 +00009718 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9719 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009720 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9721 InsertNewInstBefore(L, *MI);
9722 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9723
9724 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009725 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009726 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009727}
Chris Lattner3d69f462004-03-12 05:52:32 +00009728
Chris Lattner69ea9d22008-04-30 06:39:11 +00009729Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9730 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009731 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009732 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009733 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009734 return MI;
9735 }
9736
9737 // Extract the length and alignment and fill if they are constant.
9738 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9739 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009740 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009741 return 0;
9742 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009743 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009744
9745 // If the length is zero, this is a no-op
9746 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9747
9748 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9749 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009750 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009751
9752 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009753 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009754
9755 // Alignment 0 is identity for alignment 1 for memset, but not store.
9756 if (Alignment == 0) Alignment = 1;
9757
9758 // Extract the fill value and store.
9759 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009760 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009761 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009762
9763 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009764 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009765 return MI;
9766 }
9767
9768 return 0;
9769}
9770
9771
Chris Lattner8b0ea312006-01-13 20:11:04 +00009772/// visitCallInst - CallInst simplification. This mostly only handles folding
9773/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9774/// the heavy lifting.
9775///
Chris Lattner9fe38862003-06-19 17:00:31 +00009776Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009777 // If the caller function is nounwind, mark the call as nounwind, even if the
9778 // callee isn't.
9779 if (CI.getParent()->getParent()->doesNotThrow() &&
9780 !CI.doesNotThrow()) {
9781 CI.setDoesNotThrow();
9782 return &CI;
9783 }
9784
Chris Lattner8b0ea312006-01-13 20:11:04 +00009785 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9786 if (!II) return visitCallSite(&CI);
9787
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009788 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9789 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009790 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009791 bool Changed = false;
9792
9793 // memmove/cpy/set of zero bytes is a noop.
9794 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9795 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9796
Chris Lattner35b9e482004-10-12 04:52:52 +00009797 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009798 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009799 // Replace the instruction with just byte operations. We would
9800 // transform other cases to loads/stores, but we don't know if
9801 // alignment is sufficient.
9802 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009803 }
9804
Chris Lattner35b9e482004-10-12 04:52:52 +00009805 // If we have a memmove and the source operation is a constant global,
9806 // then the source and dest pointers can't alias, so we can change this
9807 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009808 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009809 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9810 if (GVSrc->isConstant()) {
9811 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009812 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9813 const Type *Tys[1];
9814 Tys[0] = CI.getOperand(3)->getType();
9815 CI.setOperand(0,
9816 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009817 Changed = true;
9818 }
Chris Lattnera935db82008-05-28 05:30:41 +00009819
9820 // memmove(x,x,size) -> noop.
9821 if (MMI->getSource() == MMI->getDest())
9822 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009823 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009824
Chris Lattner95a959d2006-03-06 20:18:44 +00009825 // If we can determine a pointer alignment that is bigger than currently
9826 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009827 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009828 if (Instruction *I = SimplifyMemTransfer(MI))
9829 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009830 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9831 if (Instruction *I = SimplifyMemSet(MSI))
9832 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009833 }
9834
Chris Lattner8b0ea312006-01-13 20:11:04 +00009835 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009836 }
9837
9838 switch (II->getIntrinsicID()) {
9839 default: break;
9840 case Intrinsic::bswap:
9841 // bswap(bswap(x)) -> x
9842 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9843 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9844 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9845 break;
9846 case Intrinsic::ppc_altivec_lvx:
9847 case Intrinsic::ppc_altivec_lvxl:
9848 case Intrinsic::x86_sse_loadu_ps:
9849 case Intrinsic::x86_sse2_loadu_pd:
9850 case Intrinsic::x86_sse2_loadu_dq:
9851 // Turn PPC lvx -> load if the pointer is known aligned.
9852 // Turn X86 loadups -> load if the pointer is known aligned.
9853 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009854 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9855 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009856 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009857 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009858 break;
9859 case Intrinsic::ppc_altivec_stvx:
9860 case Intrinsic::ppc_altivec_stvxl:
9861 // Turn stvx -> store if the pointer is known aligned.
9862 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9863 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009864 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009865 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009866 return new StoreInst(II->getOperand(1), Ptr);
9867 }
9868 break;
9869 case Intrinsic::x86_sse_storeu_ps:
9870 case Intrinsic::x86_sse2_storeu_pd:
9871 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009872 // Turn X86 storeu -> store if the pointer is known aligned.
9873 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9874 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009875 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009876 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009877 return new StoreInst(II->getOperand(2), Ptr);
9878 }
9879 break;
9880
9881 case Intrinsic::x86_sse_cvttss2si: {
9882 // These intrinsics only demands the 0th element of its input vector. If
9883 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009884 unsigned VWidth =
9885 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9886 APInt DemandedElts(VWidth, 1);
9887 APInt UndefElts(VWidth, 0);
9888 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009889 UndefElts)) {
9890 II->setOperand(1, V);
9891 return II;
9892 }
9893 break;
9894 }
9895
9896 case Intrinsic::ppc_altivec_vperm:
9897 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9898 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9899 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009900
Chris Lattner0521e3c2008-06-18 04:33:20 +00009901 // Check that all of the elements are integer constants or undefs.
9902 bool AllEltsOk = true;
9903 for (unsigned i = 0; i != 16; ++i) {
9904 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9905 !isa<UndefValue>(Mask->getOperand(i))) {
9906 AllEltsOk = false;
9907 break;
9908 }
9909 }
9910
9911 if (AllEltsOk) {
9912 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009913 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9914 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009915 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009916
Chris Lattner0521e3c2008-06-18 04:33:20 +00009917 // Only extract each element once.
9918 Value *ExtractedElts[32];
9919 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9920
Chris Lattnere2ed0572006-04-06 19:19:17 +00009921 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009922 if (isa<UndefValue>(Mask->getOperand(i)))
9923 continue;
9924 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9925 Idx &= 31; // Match the hardware behavior.
9926
9927 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009928 ExtractedElts[Idx] =
9929 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9930 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9931 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009932 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009933
Chris Lattner0521e3c2008-06-18 04:33:20 +00009934 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009935 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9936 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9937 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009938 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009939 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009940 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009941 }
9942 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009943
Chris Lattner0521e3c2008-06-18 04:33:20 +00009944 case Intrinsic::stackrestore: {
9945 // If the save is right next to the restore, remove the restore. This can
9946 // happen when variable allocas are DCE'd.
9947 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9948 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9949 BasicBlock::iterator BI = SS;
9950 if (&*++BI == II)
9951 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009952 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009953 }
9954
9955 // Scan down this block to see if there is another stack restore in the
9956 // same block without an intervening call/alloca.
9957 BasicBlock::iterator BI = II;
9958 TerminatorInst *TI = II->getParent()->getTerminator();
9959 bool CannotRemove = false;
9960 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009961 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009962 CannotRemove = true;
9963 break;
9964 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009965 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9966 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9967 // If there is a stackrestore below this one, remove this one.
9968 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9969 return EraseInstFromFunction(CI);
9970 // Otherwise, ignore the intrinsic.
9971 } else {
9972 // If we found a non-intrinsic call, we can't remove the stack
9973 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009974 CannotRemove = true;
9975 break;
9976 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009977 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009978 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009979
9980 // If the stack restore is in a return/unwind block and if there are no
9981 // allocas or calls between the restore and the return, nuke the restore.
9982 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9983 return EraseInstFromFunction(CI);
9984 break;
9985 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009986 }
9987
Chris Lattner8b0ea312006-01-13 20:11:04 +00009988 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009989}
9990
9991// InvokeInst simplification
9992//
9993Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009994 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009995}
9996
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009997/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9998/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009999static bool isSafeToEliminateVarargsCast(const CallSite CS,
10000 const CastInst * const CI,
10001 const TargetData * const TD,
10002 const int ix) {
10003 if (!CI->isLosslessCast())
10004 return false;
10005
10006 // The size of ByVal arguments is derived from the type, so we
10007 // can't change to a type with a different size. If the size were
10008 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010009 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010010 return true;
10011
10012 const Type* SrcTy =
10013 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10014 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10015 if (!SrcTy->isSized() || !DstTy->isSized())
10016 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010017 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010018 return false;
10019 return true;
10020}
10021
Chris Lattnera44d8a22003-10-07 22:32:43 +000010022// visitCallSite - Improvements for call and invoke instructions.
10023//
10024Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010025 bool Changed = false;
10026
10027 // If the callee is a constexpr cast of a function, attempt to move the cast
10028 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010029 if (transformConstExprCastCall(CS)) return 0;
10030
Chris Lattner6c266db2003-10-07 22:54:13 +000010031 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010032
Chris Lattner08b22ec2005-05-13 07:09:09 +000010033 if (Function *CalleeF = dyn_cast<Function>(Callee))
10034 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10035 Instruction *OldCall = CS.getInstruction();
10036 // If the call and callee calling conventions don't match, this call must
10037 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010038 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010039 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010040 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010041 // If OldCall dues not return void then replaceAllUsesWith undef.
10042 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010043 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010044 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010045 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10046 return EraseInstFromFunction(*OldCall);
10047 return 0;
10048 }
10049
Chris Lattner17be6352004-10-18 02:59:09 +000010050 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10051 // This instruction is not reachable, just remove it. We insert a store to
10052 // undef so that we know that this code is not reachable, despite the fact
10053 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010054 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010055 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010056 CS.getInstruction());
10057
Devang Patel228ebd02009-10-13 22:56:32 +000010058 // If CS dues not return void then replaceAllUsesWith undef.
10059 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010060 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010061 CS.getInstruction()->
10062 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010063
10064 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10065 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010066 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010067 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010068 }
Chris Lattner17be6352004-10-18 02:59:09 +000010069 return EraseInstFromFunction(*CS.getInstruction());
10070 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010071
Duncan Sandscdb6d922007-09-17 10:26:40 +000010072 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10073 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10074 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10075 return transformCallThroughTrampoline(CS);
10076
Chris Lattner6c266db2003-10-07 22:54:13 +000010077 const PointerType *PTy = cast<PointerType>(Callee->getType());
10078 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10079 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010080 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010081 // See if we can optimize any arguments passed through the varargs area of
10082 // the call.
10083 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010084 E = CS.arg_end(); I != E; ++I, ++ix) {
10085 CastInst *CI = dyn_cast<CastInst>(*I);
10086 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10087 *I = CI->getOperand(0);
10088 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010089 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010090 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010091 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010092
Duncan Sandsf0c33542007-12-19 21:13:37 +000010093 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010094 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010095 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010096 Changed = true;
10097 }
10098
Chris Lattner6c266db2003-10-07 22:54:13 +000010099 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010100}
10101
Chris Lattner9fe38862003-06-19 17:00:31 +000010102// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10103// attempt to move the cast to the arguments of the call/invoke.
10104//
10105bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10106 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10107 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010108 if (CE->getOpcode() != Instruction::BitCast ||
10109 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010110 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010111 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010112 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010113 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010114
10115 // Okay, this is a cast from a function to a different type. Unless doing so
10116 // would cause a type conversion of one of our arguments, change this call to
10117 // be a direct call with arguments casted to the appropriate types.
10118 //
10119 const FunctionType *FT = Callee->getFunctionType();
10120 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010121 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010122
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010123 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010124 return false; // TODO: Handle multiple return values.
10125
Chris Lattnerf78616b2004-01-14 06:06:08 +000010126 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010127 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010128 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010129 // Conversion is ok if changing from one pointer type to another or from
10130 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010131 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010132 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010133 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010134 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010135 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010136
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010137 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010138 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010139 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010140 return false; // Cannot transform this return value.
10141
Chris Lattner58d74912008-03-12 17:45:29 +000010142 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010143 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010144 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010145 return false; // Attribute not compatible with transformed value.
10146 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010147
Chris Lattnerf78616b2004-01-14 06:06:08 +000010148 // If the callsite is an invoke instruction, and the return value is used by
10149 // a PHI node in a successor, we cannot change the return type of the call
10150 // because there is no place to put the cast instruction (without breaking
10151 // the critical edge). Bail out in this case.
10152 if (!Caller->use_empty())
10153 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10154 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10155 UI != E; ++UI)
10156 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10157 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010158 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010159 return false;
10160 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010161
10162 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10163 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010164
Chris Lattner9fe38862003-06-19 17:00:31 +000010165 CallSite::arg_iterator AI = CS.arg_begin();
10166 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10167 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010168 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010169
10170 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010171 return false; // Cannot transform this parameter value.
10172
Devang Patel19c87462008-09-26 22:53:05 +000010173 if (CallerPAL.getParamAttributes(i + 1)
10174 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010175 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010176
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010177 // Converting from one pointer type to another or between a pointer and an
10178 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010179 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010180 (TD && ((isa<PointerType>(ParamTy) ||
10181 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10182 (isa<PointerType>(ActTy) ||
10183 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010184 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010185 }
10186
10187 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010188 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010189 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010190
Chris Lattner58d74912008-03-12 17:45:29 +000010191 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10192 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010193 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010194 // won't be dropping them. Check that these extra arguments have attributes
10195 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010196 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10197 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010198 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010199 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010200 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010201 return false;
10202 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010203
Chris Lattner9fe38862003-06-19 17:00:31 +000010204 // Okay, we decided that this is a safe thing to do: go ahead and start
10205 // inserting cast instructions as necessary...
10206 std::vector<Value*> Args;
10207 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010208 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010209 attrVec.reserve(NumCommonArgs);
10210
10211 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010212 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010213
10214 // If the return value is not being used, the type may not be compatible
10215 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010216 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010217
10218 // Add the new return attributes.
10219 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010220 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010221
10222 AI = CS.arg_begin();
10223 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10224 const Type *ParamTy = FT->getParamType(i);
10225 if ((*AI)->getType() == ParamTy) {
10226 Args.push_back(*AI);
10227 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010228 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010229 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010230 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010231 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010232
10233 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010234 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010235 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010236 }
10237
10238 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010239 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010240 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010241 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010242
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010243 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010244 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010245 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010246 errs() << "WARNING: While resolving call to function '"
10247 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010248 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010249 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010250 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10251 const Type *PTy = getPromotedType((*AI)->getType());
10252 if (PTy != (*AI)->getType()) {
10253 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010254 Instruction::CastOps opcode =
10255 CastInst::getCastOpcode(*AI, false, PTy, false);
10256 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010257 } else {
10258 Args.push_back(*AI);
10259 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010260
Duncan Sandse1e520f2008-01-13 08:02:44 +000010261 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010262 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010263 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010264 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010265 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010266 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010267
Devang Patel19c87462008-09-26 22:53:05 +000010268 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10269 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10270
Devang Patel9674d152009-10-14 17:29:00 +000010271 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010272 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010273
Eric Christophera66297a2009-07-25 02:45:27 +000010274 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10275 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010276
Chris Lattner9fe38862003-06-19 17:00:31 +000010277 Instruction *NC;
10278 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010279 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010280 Args.begin(), Args.end(),
10281 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010282 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010283 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010284 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010285 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10286 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010287 CallInst *CI = cast<CallInst>(Caller);
10288 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010289 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010290 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010291 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010292 }
10293
Chris Lattner6934a042007-02-11 01:23:03 +000010294 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010295 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010296 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010297 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010298 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010299 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010300 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010301
10302 // If this is an invoke instruction, we should insert it after the first
10303 // non-phi, instruction in the normal successor block.
10304 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010305 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010306 InsertNewInstBefore(NC, *I);
10307 } else {
10308 // Otherwise, it's a call, just insert cast right after the call instr
10309 InsertNewInstBefore(NC, *Caller);
10310 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010311 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010312 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010313 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010314 }
10315 }
10316
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010317
Chris Lattner931f8f32009-08-31 05:17:58 +000010318 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010319 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010320
10321 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010322 return true;
10323}
10324
Duncan Sandscdb6d922007-09-17 10:26:40 +000010325// transformCallThroughTrampoline - Turn a call to a function created by the
10326// init_trampoline intrinsic into a direct call to the underlying function.
10327//
10328Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10329 Value *Callee = CS.getCalledValue();
10330 const PointerType *PTy = cast<PointerType>(Callee->getType());
10331 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010332 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010333
10334 // If the call already has the 'nest' attribute somewhere then give up -
10335 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010336 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010337 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010338
10339 IntrinsicInst *Tramp =
10340 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10341
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010342 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010343 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10344 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10345
Devang Patel05988662008-09-25 21:00:45 +000010346 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010347 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010348 unsigned NestIdx = 1;
10349 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010350 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010351
10352 // Look for a parameter marked with the 'nest' attribute.
10353 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10354 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010355 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010356 // Record the parameter type and any other attributes.
10357 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010358 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010359 break;
10360 }
10361
10362 if (NestTy) {
10363 Instruction *Caller = CS.getInstruction();
10364 std::vector<Value*> NewArgs;
10365 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10366
Devang Patel05988662008-09-25 21:00:45 +000010367 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010368 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010369
Duncan Sandscdb6d922007-09-17 10:26:40 +000010370 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010371 // mean appending it. Likewise for attributes.
10372
Devang Patel19c87462008-09-26 22:53:05 +000010373 // Add any result attributes.
10374 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010375 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010376
Duncan Sandscdb6d922007-09-17 10:26:40 +000010377 {
10378 unsigned Idx = 1;
10379 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10380 do {
10381 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010382 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010383 Value *NestVal = Tramp->getOperand(3);
10384 if (NestVal->getType() != NestTy)
10385 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10386 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010387 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010388 }
10389
10390 if (I == E)
10391 break;
10392
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010393 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010394 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010395 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010396 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010397 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010398
10399 ++Idx, ++I;
10400 } while (1);
10401 }
10402
Devang Patel19c87462008-09-26 22:53:05 +000010403 // Add any function attributes.
10404 if (Attributes Attr = Attrs.getFnAttributes())
10405 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10406
Duncan Sandscdb6d922007-09-17 10:26:40 +000010407 // The trampoline may have been bitcast to a bogus type (FTy).
10408 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010409 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010410
Duncan Sandscdb6d922007-09-17 10:26:40 +000010411 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010412 NewTypes.reserve(FTy->getNumParams()+1);
10413
Duncan Sandscdb6d922007-09-17 10:26:40 +000010414 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010415 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010416 {
10417 unsigned Idx = 1;
10418 FunctionType::param_iterator I = FTy->param_begin(),
10419 E = FTy->param_end();
10420
10421 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010422 if (Idx == NestIdx)
10423 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010424 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010425
10426 if (I == E)
10427 break;
10428
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010429 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010430 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010431
10432 ++Idx, ++I;
10433 } while (1);
10434 }
10435
10436 // Replace the trampoline call with a direct call. Let the generic
10437 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010438 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010439 FTy->isVarArg());
10440 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010441 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010442 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010443 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010444 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10445 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010446
10447 Instruction *NewCaller;
10448 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010449 NewCaller = InvokeInst::Create(NewCallee,
10450 II->getNormalDest(), II->getUnwindDest(),
10451 NewArgs.begin(), NewArgs.end(),
10452 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010453 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010454 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010455 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010456 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10457 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010458 if (cast<CallInst>(Caller)->isTailCall())
10459 cast<CallInst>(NewCaller)->setTailCall();
10460 cast<CallInst>(NewCaller)->
10461 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010462 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010463 }
Devang Patel9674d152009-10-14 17:29:00 +000010464 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010465 Caller->replaceAllUsesWith(NewCaller);
10466 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010467 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010468 return 0;
10469 }
10470 }
10471
10472 // Replace the trampoline call with a direct call. Since there is no 'nest'
10473 // parameter, there is no need to adjust the argument list. Let the generic
10474 // code sort out any function type mismatches.
10475 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010476 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010477 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010478 CS.setCalledFunction(NewCallee);
10479 return CS.getInstruction();
10480}
10481
Dan Gohman9ad29202009-09-16 16:50:24 +000010482/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10483/// 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 +000010484/// and a single binop.
10485Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10486 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010487 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010488 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010489 Value *LHSVal = FirstInst->getOperand(0);
10490 Value *RHSVal = FirstInst->getOperand(1);
10491
10492 const Type *LHSType = LHSVal->getType();
10493 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010494
Dan Gohman9ad29202009-09-16 16:50:24 +000010495 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010496 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010497 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010498 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010499 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010500 // types or GEP's with different index types.
10501 I->getOperand(0)->getType() != LHSType ||
10502 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010503 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010504
10505 // If they are CmpInst instructions, check their predicates
10506 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10507 if (cast<CmpInst>(I)->getPredicate() !=
10508 cast<CmpInst>(FirstInst)->getPredicate())
10509 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010510
10511 // Keep track of which operand needs a phi node.
10512 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10513 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010514 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010515
10516 // If both LHS and RHS would need a PHI, don't do this transformation,
10517 // because it would increase the number of PHIs entering the block,
10518 // which leads to higher register pressure. This is especially
10519 // bad when the PHIs are in the header of a loop.
10520 if (!LHSVal && !RHSVal)
10521 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010522
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010523 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010524
Chris Lattner7da52b22006-11-01 04:51:18 +000010525 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010526 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010527 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010528 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010529 NewLHS = PHINode::Create(LHSType,
10530 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010531 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10532 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010533 InsertNewInstBefore(NewLHS, PN);
10534 LHSVal = NewLHS;
10535 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010536
10537 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010538 NewRHS = PHINode::Create(RHSType,
10539 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010540 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10541 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010542 InsertNewInstBefore(NewRHS, PN);
10543 RHSVal = NewRHS;
10544 }
10545
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010546 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010547 if (NewLHS || NewRHS) {
10548 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10549 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10550 if (NewLHS) {
10551 Value *NewInLHS = InInst->getOperand(0);
10552 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10553 }
10554 if (NewRHS) {
10555 Value *NewInRHS = InInst->getOperand(1);
10556 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10557 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010558 }
10559 }
10560
Chris Lattner7da52b22006-11-01 04:51:18 +000010561 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010562 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010563 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010564 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010565 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010566}
10567
Chris Lattner05f18922008-12-01 02:34:36 +000010568Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10569 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10570
10571 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10572 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010573 // This is true if all GEP bases are allocas and if all indices into them are
10574 // constants.
10575 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010576
10577 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010578 // more than one phi, which leads to higher register pressure. This is
10579 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010580 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010581
Dan Gohman9ad29202009-09-16 16:50:24 +000010582 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010583 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10584 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10585 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10586 GEP->getNumOperands() != FirstInst->getNumOperands())
10587 return 0;
10588
Chris Lattner36d3e322009-02-21 00:46:50 +000010589 // Keep track of whether or not all GEPs are of alloca pointers.
10590 if (AllBasePointersAreAllocas &&
10591 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10592 !GEP->hasAllConstantIndices()))
10593 AllBasePointersAreAllocas = false;
10594
Chris Lattner05f18922008-12-01 02:34:36 +000010595 // Compare the operand lists.
10596 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10597 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10598 continue;
10599
10600 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10601 // if one of the PHIs has a constant for the index. The index may be
10602 // substantially cheaper to compute for the constants, so making it a
10603 // variable index could pessimize the path. This also handles the case
10604 // for struct indices, which must always be constant.
10605 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10606 isa<ConstantInt>(GEP->getOperand(op)))
10607 return 0;
10608
10609 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10610 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010611
10612 // If we already needed a PHI for an earlier operand, and another operand
10613 // also requires a PHI, we'd be introducing more PHIs than we're
10614 // eliminating, which increases register pressure on entry to the PHI's
10615 // block.
10616 if (NeededPhi)
10617 return 0;
10618
Chris Lattner05f18922008-12-01 02:34:36 +000010619 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010620 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010621 }
10622 }
10623
Chris Lattner36d3e322009-02-21 00:46:50 +000010624 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010625 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010626 // offset calculation, but all the predecessors will have to materialize the
10627 // stack address into a register anyway. We'd actually rather *clone* the
10628 // load up into the predecessors so that we have a load of a gep of an alloca,
10629 // which can usually all be folded into the load.
10630 if (AllBasePointersAreAllocas)
10631 return 0;
10632
Chris Lattner05f18922008-12-01 02:34:36 +000010633 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10634 // that is variable.
10635 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10636
10637 bool HasAnyPHIs = false;
10638 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10639 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10640 Value *FirstOp = FirstInst->getOperand(i);
10641 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10642 FirstOp->getName()+".pn");
10643 InsertNewInstBefore(NewPN, PN);
10644
10645 NewPN->reserveOperandSpace(e);
10646 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10647 OperandPhis[i] = NewPN;
10648 FixedOperands[i] = NewPN;
10649 HasAnyPHIs = true;
10650 }
10651
10652
10653 // Add all operands to the new PHIs.
10654 if (HasAnyPHIs) {
10655 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10656 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10657 BasicBlock *InBB = PN.getIncomingBlock(i);
10658
10659 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10660 if (PHINode *OpPhi = OperandPhis[op])
10661 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10662 }
10663 }
10664
10665 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010666 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10667 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10668 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010669 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10670 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010671}
10672
10673
Chris Lattner21550882009-02-23 05:56:17 +000010674/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10675/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010676/// obvious the value of the load is not changed from the point of the load to
10677/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010678///
10679/// Finally, it is safe, but not profitable, to sink a load targetting a
10680/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10681/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010682static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010683 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10684
10685 for (++BBI; BBI != E; ++BBI)
10686 if (BBI->mayWriteToMemory())
10687 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010688
10689 // Check for non-address taken alloca. If not address-taken already, it isn't
10690 // profitable to do this xform.
10691 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10692 bool isAddressTaken = false;
10693 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10694 UI != E; ++UI) {
10695 if (isa<LoadInst>(UI)) continue;
10696 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10697 // If storing TO the alloca, then the address isn't taken.
10698 if (SI->getOperand(1) == AI) continue;
10699 }
10700 isAddressTaken = true;
10701 break;
10702 }
10703
Chris Lattner36d3e322009-02-21 00:46:50 +000010704 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010705 return false;
10706 }
10707
Chris Lattner36d3e322009-02-21 00:46:50 +000010708 // If this load is a load from a GEP with a constant offset from an alloca,
10709 // then we don't want to sink it. In its present form, it will be
10710 // load [constant stack offset]. Sinking it will cause us to have to
10711 // materialize the stack addresses in each predecessor in a register only to
10712 // do a shared load from register in the successor.
10713 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10714 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10715 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10716 return false;
10717
Chris Lattner76c73142006-11-01 07:13:54 +000010718 return true;
10719}
10720
Chris Lattner9fe38862003-06-19 17:00:31 +000010721
Chris Lattnerbac32862004-11-14 19:13:23 +000010722// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10723// operator and they all are only used by the PHI, PHI together their
10724// inputs, and do the operation once, to the result of the PHI.
10725Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10726 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10727
10728 // Scan the instruction, looking for input operations that can be folded away.
10729 // If all input operands to the phi are the same instruction (e.g. a cast from
10730 // the same type or "+42") we can pull the operation through the PHI, reducing
10731 // code size and simplifying code.
10732 Constant *ConstantOp = 0;
10733 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010734 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010735 if (isa<CastInst>(FirstInst)) {
10736 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010737 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010738 // Can fold binop, compare or shift here if the RHS is a constant,
10739 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010740 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010741 if (ConstantOp == 0)
10742 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010743 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10744 isVolatile = LI->isVolatile();
10745 // We can't sink the load if the loaded value could be modified between the
10746 // load and the PHI.
10747 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010748 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010749 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010750
10751 // If the PHI is of volatile loads and the load block has multiple
10752 // successors, sinking it would remove a load of the volatile value from
10753 // the path through the other successor.
10754 if (isVolatile &&
10755 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10756 return 0;
10757
Chris Lattner9c080502006-11-01 07:43:41 +000010758 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010759 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010760 } else {
10761 return 0; // Cannot fold this operation.
10762 }
10763
10764 // Check to see if all arguments are the same operation.
10765 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10766 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10767 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010768 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010769 return 0;
10770 if (CastSrcTy) {
10771 if (I->getOperand(0)->getType() != CastSrcTy)
10772 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010773 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010774 // We can't sink the load if the loaded value could be modified between
10775 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010776 if (LI->isVolatile() != isVolatile ||
10777 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010778 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010779 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010780
Chris Lattner71042962008-07-08 17:18:32 +000010781 // If the PHI is of volatile loads and the load block has multiple
10782 // successors, sinking it would remove a load of the volatile value from
10783 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010784 if (isVolatile &&
10785 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10786 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010787
Chris Lattnerbac32862004-11-14 19:13:23 +000010788 } else if (I->getOperand(1) != ConstantOp) {
10789 return 0;
10790 }
10791 }
10792
10793 // Okay, they are all the same operation. Create a new PHI node of the
10794 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010795 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10796 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010797 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010798
10799 Value *InVal = FirstInst->getOperand(0);
10800 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010801
10802 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010803 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10804 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10805 if (NewInVal != InVal)
10806 InVal = 0;
10807 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10808 }
10809
10810 Value *PhiVal;
10811 if (InVal) {
10812 // The new PHI unions all of the same values together. This is really
10813 // common, so we handle it intelligently here for compile-time speed.
10814 PhiVal = InVal;
10815 delete NewPN;
10816 } else {
10817 InsertNewInstBefore(NewPN, PN);
10818 PhiVal = NewPN;
10819 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010820
Chris Lattnerbac32862004-11-14 19:13:23 +000010821 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010822 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010823 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010824 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010825 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010826 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010827 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010828 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010829 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10830
10831 // If this was a volatile load that we are merging, make sure to loop through
10832 // and mark all the input loads as non-volatile. If we don't do this, we will
10833 // insert a new volatile load and the old ones will not be deletable.
10834 if (isVolatile)
10835 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10836 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10837
10838 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010839}
Chris Lattnera1be5662002-05-02 17:06:02 +000010840
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010841/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10842/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010843static bool DeadPHICycle(PHINode *PN,
10844 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010845 if (PN->use_empty()) return true;
10846 if (!PN->hasOneUse()) return false;
10847
10848 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010849 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010850 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010851
10852 // Don't scan crazily complex things.
10853 if (PotentiallyDeadPHIs.size() == 16)
10854 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010855
10856 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10857 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010858
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010859 return false;
10860}
10861
Chris Lattnercf5008a2007-11-06 21:52:06 +000010862/// PHIsEqualValue - Return true if this phi node is always equal to
10863/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10864/// z = some value; x = phi (y, z); y = phi (x, z)
10865static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10866 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10867 // See if we already saw this PHI node.
10868 if (!ValueEqualPHIs.insert(PN))
10869 return true;
10870
10871 // Don't scan crazily complex things.
10872 if (ValueEqualPHIs.size() == 16)
10873 return false;
10874
10875 // Scan the operands to see if they are either phi nodes or are equal to
10876 // the value.
10877 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10878 Value *Op = PN->getIncomingValue(i);
10879 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10880 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10881 return false;
10882 } else if (Op != NonPhiInVal)
10883 return false;
10884 }
10885
10886 return true;
10887}
10888
10889
Chris Lattner473945d2002-05-06 18:06:38 +000010890// PHINode simplification
10891//
Chris Lattner7e708292002-06-25 16:13:24 +000010892Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010893 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010894 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010895
Owen Anderson7e057142006-07-10 22:03:18 +000010896 if (Value *V = PN.hasConstantValue())
10897 return ReplaceInstUsesWith(PN, V);
10898
Owen Anderson7e057142006-07-10 22:03:18 +000010899 // If all PHI operands are the same operation, pull them through the PHI,
10900 // reducing code size.
10901 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010902 isa<Instruction>(PN.getIncomingValue(1)) &&
10903 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10904 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10905 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10906 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010907 PN.getIncomingValue(0)->hasOneUse())
10908 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10909 return Result;
10910
10911 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10912 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10913 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010914 if (PN.hasOneUse()) {
10915 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10916 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010917 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010918 PotentiallyDeadPHIs.insert(&PN);
10919 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010920 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010921 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010922
10923 // If this phi has a single use, and if that use just computes a value for
10924 // the next iteration of a loop, delete the phi. This occurs with unused
10925 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10926 // common case here is good because the only other things that catch this
10927 // are induction variable analysis (sometimes) and ADCE, which is only run
10928 // late.
10929 if (PHIUser->hasOneUse() &&
10930 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10931 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010932 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010933 }
10934 }
Owen Anderson7e057142006-07-10 22:03:18 +000010935
Chris Lattnercf5008a2007-11-06 21:52:06 +000010936 // We sometimes end up with phi cycles that non-obviously end up being the
10937 // same value, for example:
10938 // z = some value; x = phi (y, z); y = phi (x, z)
10939 // where the phi nodes don't necessarily need to be in the same block. Do a
10940 // quick check to see if the PHI node only contains a single non-phi value, if
10941 // so, scan to see if the phi cycle is actually equal to that value.
10942 {
10943 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10944 // Scan for the first non-phi operand.
10945 while (InValNo != NumOperandVals &&
10946 isa<PHINode>(PN.getIncomingValue(InValNo)))
10947 ++InValNo;
10948
10949 if (InValNo != NumOperandVals) {
10950 Value *NonPhiInVal = PN.getOperand(InValNo);
10951
10952 // Scan the rest of the operands to see if there are any conflicts, if so
10953 // there is no need to recursively scan other phis.
10954 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10955 Value *OpVal = PN.getIncomingValue(InValNo);
10956 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10957 break;
10958 }
10959
10960 // If we scanned over all operands, then we have one unique value plus
10961 // phi values. Scan PHI nodes to see if they all merge in each other or
10962 // the value.
10963 if (InValNo == NumOperandVals) {
10964 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10965 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10966 return ReplaceInstUsesWith(PN, NonPhiInVal);
10967 }
10968 }
10969 }
Chris Lattner60921c92003-12-19 05:58:40 +000010970 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010971}
10972
Chris Lattner7e708292002-06-25 16:13:24 +000010973Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010974 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000010975 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010976 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010977 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010978
Chris Lattnere87597f2004-10-16 18:11:37 +000010979 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010980 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010981
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010982 bool HasZeroPointerIndex = false;
10983 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10984 HasZeroPointerIndex = C->isNullValue();
10985
10986 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010987 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010988
Chris Lattner28977af2004-04-05 01:30:19 +000010989 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010990 if (TD) {
10991 bool MadeChange = false;
10992 unsigned PtrSize = TD->getPointerSizeInBits();
10993
10994 gep_type_iterator GTI = gep_type_begin(GEP);
10995 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10996 I != E; ++I, ++GTI) {
10997 if (!isa<SequentialType>(*GTI)) continue;
10998
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010999 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011000 // to what we need. If narrower, sign-extend it to what we need. This
11001 // explicit cast can make subsequent optimizations more obvious.
11002 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000011003 if (OpBits == PtrSize)
11004 continue;
11005
Chris Lattner2345d1d2009-08-30 20:01:10 +000011006 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011007 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011008 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011009 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011010 }
Chris Lattner28977af2004-04-05 01:30:19 +000011011
Chris Lattner90ac28c2002-08-02 19:29:35 +000011012 // Combine Indices - If the source pointer to this getelementptr instruction
11013 // is a getelementptr instruction, combine the indices of the two
11014 // getelementptr instructions into a single instruction.
11015 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011016 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011017 // Note that if our source is a gep chain itself that we wait for that
11018 // chain to be resolved before we perform this transformation. This
11019 // avoids us creating a TON of code in some cases.
11020 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011021 if (GetElementPtrInst *SrcGEP =
11022 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11023 if (SrcGEP->getNumOperands() == 2)
11024 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011025
Chris Lattner72588fc2007-02-15 22:48:32 +000011026 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011027
11028 // Find out whether the last index in the source GEP is a sequential idx.
11029 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011030 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11031 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011032 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011033
Chris Lattner90ac28c2002-08-02 19:29:35 +000011034 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011035 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011036 // Replace: gep (gep %P, long B), long A, ...
11037 // With: T = long A+B; gep %P, T, ...
11038 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011039 Value *Sum;
11040 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11041 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011042 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011043 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011044 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011045 Sum = SO1;
11046 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011047 // If they aren't the same type, then the input hasn't been processed
11048 // by the loop above yet (which canonicalizes sequential index types to
11049 // intptr_t). Just avoid transforming this until the input has been
11050 // normalized.
11051 if (SO1->getType() != GO1->getType())
11052 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011053 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000011054 }
Chris Lattner620ce142004-05-07 22:09:22 +000011055
Chris Lattnerab984842009-08-30 05:30:55 +000011056 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011057 if (Src->getNumOperands() == 2) {
11058 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011059 GEP.setOperand(1, Sum);
11060 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011061 }
Chris Lattnerab984842009-08-30 05:30:55 +000011062 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011063 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011064 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011065 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011066 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011067 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011068 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011069 Indices.append(Src->op_begin()+1, Src->op_end());
11070 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011071 }
11072
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011073 if (!Indices.empty())
11074 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11075 Src->isInBounds()) ?
11076 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11077 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011078 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011079 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011080 }
11081
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011082 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11083 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011084 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011085
Chris Lattner2de23192009-08-30 20:38:21 +000011086 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11087 // want to change the gep until the bitcasts are eliminated.
11088 if (getBitCastOperand(X)) {
11089 Worklist.AddValue(PtrOp);
11090 return 0;
11091 }
11092
Chris Lattner963f4ba2009-08-30 20:36:46 +000011093 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11094 // into : GEP [10 x i8]* X, i32 0, ...
11095 //
11096 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11097 // into : GEP i8* X, ...
11098 //
11099 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011100 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011101 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11102 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011103 if (const ArrayType *CATy =
11104 dyn_cast<ArrayType>(CPTy->getElementType())) {
11105 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11106 if (CATy->getElementType() == XTy->getElementType()) {
11107 // -> GEP i8* X, ...
11108 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011109 return cast<GEPOperator>(&GEP)->isInBounds() ?
11110 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11111 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011112 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11113 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011114 }
11115
11116 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011117 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011118 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011119 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011120 // At this point, we know that the cast source type is a pointer
11121 // to an array of the same type as the destination pointer
11122 // array. Because the array type is never stepped over (there
11123 // is a leading zero) we can fold the cast into this GEP.
11124 GEP.setOperand(0, X);
11125 return &GEP;
11126 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011127 }
11128 }
Chris Lattnereed48272005-09-13 00:40:14 +000011129 } else if (GEP.getNumOperands() == 2) {
11130 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011131 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11132 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011133 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11134 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011135 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011136 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11137 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011138 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011139 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011140 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011141 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11142 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011143 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011144 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011145 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011146 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011147
11148 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011149 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011150 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011151 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011152
Owen Anderson1d0be152009-08-13 21:58:54 +000011153 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011154 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011155 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011156
11157 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11158 // allow either a mul, shift, or constant here.
11159 Value *NewIdx = 0;
11160 ConstantInt *Scale = 0;
11161 if (ArrayEltSize == 1) {
11162 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011163 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011164 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011165 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011166 Scale = CI;
11167 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11168 if (Inst->getOpcode() == Instruction::Shl &&
11169 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011170 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11171 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011172 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011173 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011174 NewIdx = Inst->getOperand(0);
11175 } else if (Inst->getOpcode() == Instruction::Mul &&
11176 isa<ConstantInt>(Inst->getOperand(1))) {
11177 Scale = cast<ConstantInt>(Inst->getOperand(1));
11178 NewIdx = Inst->getOperand(0);
11179 }
11180 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011181
Chris Lattner7835cdd2005-09-13 18:36:04 +000011182 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011183 // out, perform the transformation. Note, we don't know whether Scale is
11184 // signed or not. We'll use unsigned version of division/modulo
11185 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011186 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011187 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011188 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011189 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011190 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011191 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11192 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011193 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011194 }
11195
11196 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011197 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011198 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011199 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011200 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11201 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11202 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011203 // The NewGEP must be pointer typed, so must the old one -> BitCast
11204 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011205 }
11206 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011207 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011208 }
Chris Lattner58407792009-01-09 04:53:57 +000011209
Chris Lattner46cd5a12009-01-09 05:44:56 +000011210 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011211 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011212 /// Y = gep X, <...constant indices...>
11213 /// into a gep of the original struct. This is important for SROA and alias
11214 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011215 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011216 if (TD &&
11217 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011218 // Determine how much the GEP moves the pointer. We are guaranteed to get
11219 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011220 ConstantInt *OffsetV =
11221 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011222 int64_t Offset = OffsetV->getSExtValue();
11223
11224 // If this GEP instruction doesn't move the pointer, just replace the GEP
11225 // with a bitcast of the real input to the dest type.
11226 if (Offset == 0) {
11227 // If the bitcast is of an allocation, and the allocation will be
11228 // converted to match the type of the cast, don't touch this.
Victor Hernandez83d63912009-09-18 22:35:49 +000011229 if (isa<AllocationInst>(BCI->getOperand(0)) ||
11230 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011231 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11232 if (Instruction *I = visitBitCast(*BCI)) {
11233 if (I != BCI) {
11234 I->takeName(BCI);
11235 BCI->getParent()->getInstList().insert(BCI, I);
11236 ReplaceInstUsesWith(*BCI, I);
11237 }
11238 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011239 }
Chris Lattner58407792009-01-09 04:53:57 +000011240 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011241 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011242 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011243
11244 // Otherwise, if the offset is non-zero, we need to find out if there is a
11245 // field at Offset in 'A's type. If so, we can pull the cast through the
11246 // GEP.
11247 SmallVector<Value*, 8> NewIndices;
11248 const Type *InTy =
11249 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011250 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011251 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11252 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11253 NewIndices.end()) :
11254 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11255 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011256
11257 if (NGEP->getType() == GEP.getType())
11258 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011259 NGEP->takeName(&GEP);
11260 return new BitCastInst(NGEP, GEP.getType());
11261 }
Chris Lattner58407792009-01-09 04:53:57 +000011262 }
11263 }
11264
Chris Lattner8a2a3112001-12-14 16:52:21 +000011265 return 0;
11266}
11267
Chris Lattner0864acf2002-11-04 16:18:53 +000011268Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11269 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011270 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011271 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11272 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011273 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000011274 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11275 AllocationInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011276 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011277
Chris Lattner0864acf2002-11-04 16:18:53 +000011278 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011279 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011280 //
11281 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011282 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011283
11284 // Now that I is pointing to the first non-allocation-inst in the block,
11285 // insert our getelementptr instruction...
11286 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011287 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011288 Value *Idx[2];
11289 Idx[0] = NullIdx;
11290 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011291 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11292 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011293
11294 // Now make everything use the getelementptr instead of the original
11295 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011296 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011297 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011298 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011299 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011300 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011301
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011302 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011303 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011304 // Note that we only do this for alloca's, because malloc should allocate
11305 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011306 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011307 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011308
11309 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11310 if (AI.getAlignment() == 0)
11311 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11312 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011313
Chris Lattner0864acf2002-11-04 16:18:53 +000011314 return 0;
11315}
11316
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011317Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11318 Value *Op = FI.getOperand(0);
11319
Chris Lattner17be6352004-10-18 02:59:09 +000011320 // free undef -> unreachable.
11321 if (isa<UndefValue>(Op)) {
11322 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011323 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000011324 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011325 return EraseInstFromFunction(FI);
11326 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011327
Chris Lattner6160e852004-02-28 04:57:37 +000011328 // If we have 'free null' delete the instruction. This can happen in stl code
11329 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011330 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011331 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011332
11333 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11334 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11335 FI.setOperand(0, CI->getOperand(0));
11336 return &FI;
11337 }
11338
11339 // Change free (gep X, 0,0,0,0) into free(X)
11340 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11341 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011342 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011343 FI.setOperand(0, GEPI->getOperand(0));
11344 return &FI;
11345 }
11346 }
11347
Victor Hernandez83d63912009-09-18 22:35:49 +000011348 if (isMalloc(Op)) {
11349 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11350 if (Op->hasOneUse() && CI->hasOneUse()) {
11351 EraseInstFromFunction(FI);
11352 EraseInstFromFunction(*CI);
11353 return EraseInstFromFunction(*cast<Instruction>(Op));
11354 }
11355 } else {
11356 // Op is a call to malloc
11357 if (Op->hasOneUse()) {
11358 EraseInstFromFunction(FI);
11359 return EraseInstFromFunction(*cast<Instruction>(Op));
11360 }
11361 }
11362 }
Chris Lattner6160e852004-02-28 04:57:37 +000011363
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011364 return 0;
11365}
11366
11367
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011368/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011369static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011370 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011371 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011372 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011373 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011374
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011375 if (TD) {
11376 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11377 // Instead of loading constant c string, use corresponding integer value
11378 // directly if string length is small enough.
11379 std::string Str;
11380 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11381 unsigned len = Str.length();
11382 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11383 unsigned numBits = Ty->getPrimitiveSizeInBits();
11384 // Replace LI with immediate integer store.
11385 if ((numBits >> 3) == len + 1) {
11386 APInt StrVal(numBits, 0);
11387 APInt SingleChar(numBits, 0);
11388 if (TD->isLittleEndian()) {
11389 for (signed i = len-1; i >= 0; i--) {
11390 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11391 StrVal = (StrVal << 8) | SingleChar;
11392 }
11393 } else {
11394 for (unsigned i = 0; i < len; i++) {
11395 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11396 StrVal = (StrVal << 8) | SingleChar;
11397 }
11398 // Append NULL at the end.
11399 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011400 StrVal = (StrVal << 8) | SingleChar;
11401 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011402 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011403 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011404 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011405 }
11406 }
11407 }
11408
Mon P Wang6753f952009-02-07 22:19:29 +000011409 const PointerType *DestTy = cast<PointerType>(CI->getType());
11410 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011411 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011412
11413 // If the address spaces don't match, don't eliminate the cast.
11414 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11415 return 0;
11416
Chris Lattnerb89e0712004-07-13 01:49:43 +000011417 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011418
Reid Spencer42230162007-01-22 05:51:25 +000011419 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011420 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011421 // If the source is an array, the code below will not succeed. Check to
11422 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11423 // constants.
11424 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11425 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11426 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011427 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011428 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011429 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011430 SrcTy = cast<PointerType>(CastOp->getType());
11431 SrcPTy = SrcTy->getElementType();
11432 }
11433
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011434 if (IC.getTargetData() &&
11435 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011436 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011437 // Do not allow turning this into a load of an integer, which is then
11438 // casted to a pointer, this pessimizes pointer analysis a lot.
11439 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011440 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11441 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011442
Chris Lattnerf9527852005-01-31 04:50:46 +000011443 // Okay, we are casting from one integer or pointer type to another of
11444 // the same size. Instead of casting the pointer before the load, cast
11445 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011446 Value *NewLoad =
11447 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011448 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011449 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011450 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011451 }
11452 }
11453 return 0;
11454}
11455
Chris Lattner833b8a42003-06-26 05:06:25 +000011456Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11457 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011458
Dan Gohman9941f742007-07-20 16:34:21 +000011459 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011460 if (TD) {
11461 unsigned KnownAlign =
11462 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11463 if (KnownAlign >
11464 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11465 LI.getAlignment()))
11466 LI.setAlignment(KnownAlign);
11467 }
Dan Gohman9941f742007-07-20 16:34:21 +000011468
Chris Lattner963f4ba2009-08-30 20:36:46 +000011469 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011470 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011471 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011472 return Res;
11473
11474 // None of the following transforms are legal for volatile loads.
11475 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011476
Dan Gohman2276a7b2008-10-15 23:19:35 +000011477 // Do really simple store-to-load forwarding and load CSE, to catch cases
11478 // where there are several consequtive memory accesses to the same location,
11479 // separated by a few arithmetic operations.
11480 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011481 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11482 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011483
Christopher Lambb15147e2007-12-29 07:56:53 +000011484 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11485 const Value *GEPI0 = GEPI->getOperand(0);
11486 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011487 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011488 // Insert a new store to null instruction before the load to indicate
11489 // that this code is not reachable. We do this instead of inserting
11490 // an unreachable instruction directly because we cannot modify the
11491 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011492 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011493 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011494 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011495 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011496 }
Chris Lattner37366c12005-05-01 04:24:53 +000011497
Chris Lattnere87597f2004-10-16 18:11:37 +000011498 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011499 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011500 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011501 if (isa<UndefValue>(C) ||
11502 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011503 // Insert a new store to null instruction before the load to indicate that
11504 // this code is not reachable. We do this instead of inserting an
11505 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011506 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011507 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011508 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011509 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011510
Chris Lattnere87597f2004-10-16 18:11:37 +000011511 // Instcombine load (constant global) into the value loaded.
11512 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011513 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011514 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011515
Chris Lattnere87597f2004-10-16 18:11:37 +000011516 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011517 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011518 if (CE->getOpcode() == Instruction::GetElementPtr) {
11519 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011520 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011521 if (Constant *V =
Dan Gohmanc6f69e92009-10-05 16:36:26 +000011522 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011523 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011524 if (CE->getOperand(0)->isNullValue()) {
11525 // Insert a new store to null instruction before the load to indicate
11526 // that this code is not reachable. We do this instead of inserting
11527 // an unreachable instruction directly because we cannot modify the
11528 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011529 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011530 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011531 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011532 }
11533
Reid Spencer3da59db2006-11-27 01:05:10 +000011534 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011535 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011536 return Res;
11537 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011538 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011539 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011540
11541 // If this load comes from anywhere in a constant global, and if the global
11542 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011543 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011544 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011545 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011546 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011547 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011548 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011549 }
11550 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011551
Chris Lattner37366c12005-05-01 04:24:53 +000011552 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011553 // Change select and PHI nodes to select values instead of addresses: this
11554 // helps alias analysis out a lot, allows many others simplifications, and
11555 // exposes redundancy in the code.
11556 //
11557 // Note that we cannot do the transformation unless we know that the
11558 // introduced loads cannot trap! Something like this is valid as long as
11559 // the condition is always false: load (select bool %C, int* null, int* %G),
11560 // but it would not be valid if we transformed it to load from null
11561 // unconditionally.
11562 //
11563 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11564 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011565 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11566 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011567 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11568 SI->getOperand(1)->getName()+".val");
11569 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11570 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011571 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011572 }
11573
Chris Lattner684fe212004-09-23 15:46:00 +000011574 // load (select (cond, null, P)) -> load P
11575 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11576 if (C->isNullValue()) {
11577 LI.setOperand(0, SI->getOperand(2));
11578 return &LI;
11579 }
11580
11581 // load (select (cond, P, null)) -> load P
11582 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11583 if (C->isNullValue()) {
11584 LI.setOperand(0, SI->getOperand(1));
11585 return &LI;
11586 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011587 }
11588 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011589 return 0;
11590}
11591
Reid Spencer55af2b52007-01-19 21:20:31 +000011592/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011593/// when possible. This makes it generally easy to do alias analysis and/or
11594/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011595static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11596 User *CI = cast<User>(SI.getOperand(1));
11597 Value *CastOp = CI->getOperand(0);
11598
11599 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011600 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11601 if (SrcTy == 0) return 0;
11602
11603 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011604
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011605 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11606 return 0;
11607
Chris Lattner3914f722009-01-24 01:00:13 +000011608 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11609 /// to its first element. This allows us to handle things like:
11610 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11611 /// on 32-bit hosts.
11612 SmallVector<Value*, 4> NewGEPIndices;
11613
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011614 // If the source is an array, the code below will not succeed. Check to
11615 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11616 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011617 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11618 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011619 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011620 NewGEPIndices.push_back(Zero);
11621
11622 while (1) {
11623 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011624 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011625 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011626 NewGEPIndices.push_back(Zero);
11627 SrcPTy = STy->getElementType(0);
11628 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11629 NewGEPIndices.push_back(Zero);
11630 SrcPTy = ATy->getElementType();
11631 } else {
11632 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011633 }
Chris Lattner3914f722009-01-24 01:00:13 +000011634 }
11635
Owen Andersondebcb012009-07-29 22:17:13 +000011636 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011637 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011638
11639 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11640 return 0;
11641
Chris Lattner71759c42009-01-16 20:12:52 +000011642 // If the pointers point into different address spaces or if they point to
11643 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011644 if (!IC.getTargetData() ||
11645 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011646 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011647 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11648 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011649 return 0;
11650
11651 // Okay, we are casting from one integer or pointer type to another of
11652 // the same size. Instead of casting the pointer before
11653 // the store, cast the value to be stored.
11654 Value *NewCast;
11655 Value *SIOp0 = SI.getOperand(0);
11656 Instruction::CastOps opcode = Instruction::BitCast;
11657 const Type* CastSrcTy = SIOp0->getType();
11658 const Type* CastDstTy = SrcPTy;
11659 if (isa<PointerType>(CastDstTy)) {
11660 if (CastSrcTy->isInteger())
11661 opcode = Instruction::IntToPtr;
11662 } else if (isa<IntegerType>(CastDstTy)) {
11663 if (isa<PointerType>(SIOp0->getType()))
11664 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011665 }
Chris Lattner3914f722009-01-24 01:00:13 +000011666
11667 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11668 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011669 if (!NewGEPIndices.empty())
11670 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11671 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011672
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011673 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11674 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011675 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011676}
11677
Chris Lattner4aebaee2008-11-27 08:56:30 +000011678/// equivalentAddressValues - Test if A and B will obviously have the same
11679/// value. This includes recognizing that %t0 and %t1 will have the same
11680/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011681/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011682/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011683/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011684/// %t2 = load i32* %t1
11685///
11686static bool equivalentAddressValues(Value *A, Value *B) {
11687 // Test if the values are trivially equivalent.
11688 if (A == B) return true;
11689
11690 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011691 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11692 // its only used to compare two uses within the same basic block, which
11693 // means that they'll always either have the same value or one of them
11694 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011695 if (isa<BinaryOperator>(A) ||
11696 isa<CastInst>(A) ||
11697 isa<PHINode>(A) ||
11698 isa<GetElementPtrInst>(A))
11699 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011700 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011701 return true;
11702
11703 // Otherwise they may not be equivalent.
11704 return false;
11705}
11706
Dale Johannesen4945c652009-03-03 21:26:39 +000011707// If this instruction has two uses, one of which is a llvm.dbg.declare,
11708// return the llvm.dbg.declare.
11709DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11710 if (!V->hasNUses(2))
11711 return 0;
11712 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11713 UI != E; ++UI) {
11714 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11715 return DI;
11716 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11717 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11718 return DI;
11719 }
11720 }
11721 return 0;
11722}
11723
Chris Lattner2f503e62005-01-31 05:36:43 +000011724Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11725 Value *Val = SI.getOperand(0);
11726 Value *Ptr = SI.getOperand(1);
11727
11728 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011729 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011730 ++NumCombined;
11731 return 0;
11732 }
Chris Lattner836692d2007-01-15 06:51:56 +000011733
11734 // If the RHS is an alloca with a single use, zapify the store, making the
11735 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011736 // If the RHS is an alloca with a two uses, the other one being a
11737 // llvm.dbg.declare, zapify the store and the declare, making the
11738 // alloca dead. We must do this to prevent declare's from affecting
11739 // codegen.
11740 if (!SI.isVolatile()) {
11741 if (Ptr->hasOneUse()) {
11742 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011743 EraseInstFromFunction(SI);
11744 ++NumCombined;
11745 return 0;
11746 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011747 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11748 if (isa<AllocaInst>(GEP->getOperand(0))) {
11749 if (GEP->getOperand(0)->hasOneUse()) {
11750 EraseInstFromFunction(SI);
11751 ++NumCombined;
11752 return 0;
11753 }
11754 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11755 EraseInstFromFunction(*DI);
11756 EraseInstFromFunction(SI);
11757 ++NumCombined;
11758 return 0;
11759 }
11760 }
11761 }
11762 }
11763 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11764 EraseInstFromFunction(*DI);
11765 EraseInstFromFunction(SI);
11766 ++NumCombined;
11767 return 0;
11768 }
Chris Lattner836692d2007-01-15 06:51:56 +000011769 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011770
Dan Gohman9941f742007-07-20 16:34:21 +000011771 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011772 if (TD) {
11773 unsigned KnownAlign =
11774 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11775 if (KnownAlign >
11776 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11777 SI.getAlignment()))
11778 SI.setAlignment(KnownAlign);
11779 }
Dan Gohman9941f742007-07-20 16:34:21 +000011780
Dale Johannesenacb51a32009-03-03 01:43:03 +000011781 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011782 // stores to the same location, separated by a few arithmetic operations. This
11783 // situation often occurs with bitfield accesses.
11784 BasicBlock::iterator BBI = &SI;
11785 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11786 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011787 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011788 // Don't count debug info directives, lest they affect codegen,
11789 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11790 // It is necessary for correctness to skip those that feed into a
11791 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011792 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011793 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011794 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011795 continue;
11796 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011797
11798 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11799 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011800 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11801 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011802 ++NumDeadStore;
11803 ++BBI;
11804 EraseInstFromFunction(*PrevSI);
11805 continue;
11806 }
11807 break;
11808 }
11809
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011810 // If this is a load, we have to stop. However, if the loaded value is from
11811 // the pointer we're loading and is producing the pointer we're storing,
11812 // then *this* store is dead (X = load P; store X -> P).
11813 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011814 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11815 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011816 EraseInstFromFunction(SI);
11817 ++NumCombined;
11818 return 0;
11819 }
11820 // Otherwise, this is a load from some other location. Stores before it
11821 // may not be dead.
11822 break;
11823 }
11824
Chris Lattner9ca96412006-02-08 03:25:32 +000011825 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011826 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011827 break;
11828 }
11829
11830
11831 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011832
11833 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011834 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011835 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011836 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011837 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011838 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011839 ++NumCombined;
11840 }
11841 return 0; // Do not modify these!
11842 }
11843
11844 // store undef, Ptr -> noop
11845 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011846 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011847 ++NumCombined;
11848 return 0;
11849 }
11850
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011851 // If the pointer destination is a cast, see if we can fold the cast into the
11852 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011853 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011854 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11855 return Res;
11856 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011857 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011858 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11859 return Res;
11860
Chris Lattner408902b2005-09-12 23:23:25 +000011861
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011862 // If this store is the last instruction in the basic block (possibly
11863 // excepting debug info instructions and the pointer bitcasts that feed
11864 // into them), and if the block ends with an unconditional branch, try
11865 // to move it to the successor block.
11866 BBI = &SI;
11867 do {
11868 ++BBI;
11869 } while (isa<DbgInfoIntrinsic>(BBI) ||
11870 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011871 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011872 if (BI->isUnconditional())
11873 if (SimplifyStoreAtEndOfBlock(SI))
11874 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011875
Chris Lattner2f503e62005-01-31 05:36:43 +000011876 return 0;
11877}
11878
Chris Lattner3284d1f2007-04-15 00:07:55 +000011879/// SimplifyStoreAtEndOfBlock - Turn things like:
11880/// if () { *P = v1; } else { *P = v2 }
11881/// into a phi node with a store in the successor.
11882///
Chris Lattner31755a02007-04-15 01:02:18 +000011883/// Simplify things like:
11884/// *P = v1; if () { *P = v2; }
11885/// into a phi node with a store in the successor.
11886///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011887bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11888 BasicBlock *StoreBB = SI.getParent();
11889
11890 // Check to see if the successor block has exactly two incoming edges. If
11891 // so, see if the other predecessor contains a store to the same location.
11892 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011893 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011894
11895 // Determine whether Dest has exactly two predecessors and, if so, compute
11896 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011897 pred_iterator PI = pred_begin(DestBB);
11898 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011899 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011900 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011901 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011902 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011903 return false;
11904
11905 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011906 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011907 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011908 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011909 }
Chris Lattner31755a02007-04-15 01:02:18 +000011910 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011911 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011912
11913 // Bail out if all the relevant blocks aren't distinct (this can happen,
11914 // for example, if SI is in an infinite loop)
11915 if (StoreBB == DestBB || OtherBB == DestBB)
11916 return false;
11917
Chris Lattner31755a02007-04-15 01:02:18 +000011918 // Verify that the other block ends in a branch and is not otherwise empty.
11919 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011920 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011921 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011922 return false;
11923
Chris Lattner31755a02007-04-15 01:02:18 +000011924 // If the other block ends in an unconditional branch, check for the 'if then
11925 // else' case. there is an instruction before the branch.
11926 StoreInst *OtherStore = 0;
11927 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011928 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011929 // Skip over debugging info.
11930 while (isa<DbgInfoIntrinsic>(BBI) ||
11931 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11932 if (BBI==OtherBB->begin())
11933 return false;
11934 --BBI;
11935 }
11936 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011937 OtherStore = dyn_cast<StoreInst>(BBI);
11938 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11939 return false;
11940 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011941 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011942 // destinations is StoreBB, then we have the if/then case.
11943 if (OtherBr->getSuccessor(0) != StoreBB &&
11944 OtherBr->getSuccessor(1) != StoreBB)
11945 return false;
11946
11947 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011948 // if/then triangle. See if there is a store to the same ptr as SI that
11949 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011950 for (;; --BBI) {
11951 // Check to see if we find the matching store.
11952 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11953 if (OtherStore->getOperand(1) != SI.getOperand(1))
11954 return false;
11955 break;
11956 }
Eli Friedman6903a242008-06-13 22:02:12 +000011957 // If we find something that may be using or overwriting the stored
11958 // value, or if we run out of instructions, we can't do the xform.
11959 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011960 BBI == OtherBB->begin())
11961 return false;
11962 }
11963
11964 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011965 // make sure nothing reads or overwrites the stored value in
11966 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011967 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11968 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011969 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011970 return false;
11971 }
11972 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011973
Chris Lattner31755a02007-04-15 01:02:18 +000011974 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011975 Value *MergedVal = OtherStore->getOperand(0);
11976 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011977 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011978 PN->reserveOperandSpace(2);
11979 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011980 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11981 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011982 }
11983
11984 // Advance to a place where it is safe to insert the new store and
11985 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011986 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011987 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11988 OtherStore->isVolatile()), *BBI);
11989
11990 // Nuke the old stores.
11991 EraseInstFromFunction(SI);
11992 EraseInstFromFunction(*OtherStore);
11993 ++NumCombined;
11994 return true;
11995}
11996
Chris Lattner2f503e62005-01-31 05:36:43 +000011997
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011998Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11999 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012000 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012001 BasicBlock *TrueDest;
12002 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012003 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012004 !isa<Constant>(X)) {
12005 // Swap Destinations and condition...
12006 BI.setCondition(X);
12007 BI.setSuccessor(0, FalseDest);
12008 BI.setSuccessor(1, TrueDest);
12009 return &BI;
12010 }
12011
Reid Spencere4d87aa2006-12-23 06:05:41 +000012012 // Cannonicalize fcmp_one -> fcmp_oeq
12013 FCmpInst::Predicate FPred; Value *Y;
12014 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012015 TrueDest, FalseDest)) &&
12016 BI.getCondition()->hasOneUse())
12017 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12018 FPred == FCmpInst::FCMP_OGE) {
12019 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12020 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12021
12022 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012023 BI.setSuccessor(0, FalseDest);
12024 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012025 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012026 return &BI;
12027 }
12028
12029 // Cannonicalize icmp_ne -> icmp_eq
12030 ICmpInst::Predicate IPred;
12031 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012032 TrueDest, FalseDest)) &&
12033 BI.getCondition()->hasOneUse())
12034 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12035 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12036 IPred == ICmpInst::ICMP_SGE) {
12037 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12038 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12039 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012040 BI.setSuccessor(0, FalseDest);
12041 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012042 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012043 return &BI;
12044 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012045
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012046 return 0;
12047}
Chris Lattner0864acf2002-11-04 16:18:53 +000012048
Chris Lattner46238a62004-07-03 00:26:11 +000012049Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12050 Value *Cond = SI.getCondition();
12051 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12052 if (I->getOpcode() == Instruction::Add)
12053 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12054 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12055 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012056 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012057 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012058 AddRHS));
12059 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012060 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012061 return &SI;
12062 }
12063 }
12064 return 0;
12065}
12066
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012067Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012068 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012069
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012070 if (!EV.hasIndices())
12071 return ReplaceInstUsesWith(EV, Agg);
12072
12073 if (Constant *C = dyn_cast<Constant>(Agg)) {
12074 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012075 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012076
12077 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012078 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012079
12080 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12081 // Extract the element indexed by the first index out of the constant
12082 Value *V = C->getOperand(*EV.idx_begin());
12083 if (EV.getNumIndices() > 1)
12084 // Extract the remaining indices out of the constant indexed by the
12085 // first index
12086 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12087 else
12088 return ReplaceInstUsesWith(EV, V);
12089 }
12090 return 0; // Can't handle other constants
12091 }
12092 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12093 // We're extracting from an insertvalue instruction, compare the indices
12094 const unsigned *exti, *exte, *insi, *inse;
12095 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12096 exte = EV.idx_end(), inse = IV->idx_end();
12097 exti != exte && insi != inse;
12098 ++exti, ++insi) {
12099 if (*insi != *exti)
12100 // The insert and extract both reference distinctly different elements.
12101 // This means the extract is not influenced by the insert, and we can
12102 // replace the aggregate operand of the extract with the aggregate
12103 // operand of the insert. i.e., replace
12104 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12105 // %E = extractvalue { i32, { i32 } } %I, 0
12106 // with
12107 // %E = extractvalue { i32, { i32 } } %A, 0
12108 return ExtractValueInst::Create(IV->getAggregateOperand(),
12109 EV.idx_begin(), EV.idx_end());
12110 }
12111 if (exti == exte && insi == inse)
12112 // Both iterators are at the end: Index lists are identical. Replace
12113 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12114 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12115 // with "i32 42"
12116 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12117 if (exti == exte) {
12118 // The extract list is a prefix of the insert list. i.e. replace
12119 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12120 // %E = extractvalue { i32, { i32 } } %I, 1
12121 // with
12122 // %X = extractvalue { i32, { i32 } } %A, 1
12123 // %E = insertvalue { i32 } %X, i32 42, 0
12124 // by switching the order of the insert and extract (though the
12125 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012126 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12127 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012128 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12129 insi, inse);
12130 }
12131 if (insi == inse)
12132 // The insert list is a prefix of the extract list
12133 // We can simply remove the common indices from the extract and make it
12134 // operate on the inserted value instead of the insertvalue result.
12135 // i.e., replace
12136 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12137 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12138 // with
12139 // %E extractvalue { i32 } { i32 42 }, 0
12140 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12141 exti, exte);
12142 }
12143 // Can't simplify extracts from other values. Note that nested extracts are
12144 // already simplified implicitely by the above (extract ( extract (insert) )
12145 // will be translated into extract ( insert ( extract ) ) first and then just
12146 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012147 return 0;
12148}
12149
Chris Lattner220b0cf2006-03-05 00:22:33 +000012150/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12151/// is to leave as a vector operation.
12152static bool CheapToScalarize(Value *V, bool isConstant) {
12153 if (isa<ConstantAggregateZero>(V))
12154 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012155 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012156 if (isConstant) return true;
12157 // If all elts are the same, we can extract.
12158 Constant *Op0 = C->getOperand(0);
12159 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12160 if (C->getOperand(i) != Op0)
12161 return false;
12162 return true;
12163 }
12164 Instruction *I = dyn_cast<Instruction>(V);
12165 if (!I) return false;
12166
12167 // Insert element gets simplified to the inserted element or is deleted if
12168 // this is constant idx extract element and its a constant idx insertelt.
12169 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12170 isa<ConstantInt>(I->getOperand(2)))
12171 return true;
12172 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12173 return true;
12174 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12175 if (BO->hasOneUse() &&
12176 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12177 CheapToScalarize(BO->getOperand(1), isConstant)))
12178 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012179 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12180 if (CI->hasOneUse() &&
12181 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12182 CheapToScalarize(CI->getOperand(1), isConstant)))
12183 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012184
12185 return false;
12186}
12187
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012188/// Read and decode a shufflevector mask.
12189///
12190/// It turns undef elements into values that are larger than the number of
12191/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012192static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12193 unsigned NElts = SVI->getType()->getNumElements();
12194 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12195 return std::vector<unsigned>(NElts, 0);
12196 if (isa<UndefValue>(SVI->getOperand(2)))
12197 return std::vector<unsigned>(NElts, 2*NElts);
12198
12199 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012200 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012201 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12202 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012203 Result.push_back(NElts*2); // undef -> 8
12204 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012205 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012206 return Result;
12207}
12208
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012209/// FindScalarElement - Given a vector and an element number, see if the scalar
12210/// value is already around as a register, for example if it were inserted then
12211/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012212static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012213 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012214 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12215 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012216 unsigned Width = PTy->getNumElements();
12217 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012218 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012219
12220 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012221 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012222 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012223 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012224 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012225 return CP->getOperand(EltNo);
12226 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12227 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012228 if (!isa<ConstantInt>(III->getOperand(2)))
12229 return 0;
12230 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012231
12232 // If this is an insert to the element we are looking for, return the
12233 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012234 if (EltNo == IIElt)
12235 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012236
12237 // Otherwise, the insertelement doesn't modify the value, recurse on its
12238 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012239 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012240 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012241 unsigned LHSWidth =
12242 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012243 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012244 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012245 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012246 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012247 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012248 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012249 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012250 }
12251
12252 // Otherwise, we don't know.
12253 return 0;
12254}
12255
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012256Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012257 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012258 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012259 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012260
Dan Gohman07a96762007-07-16 14:29:03 +000012261 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012262 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012263 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012264
Reid Spencer9d6565a2007-02-15 02:26:10 +000012265 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012266 // If vector val is constant with all elements the same, replace EI with
12267 // that element. When the elements are not identical, we cannot replace yet
12268 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012269 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012270 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012271 if (C->getOperand(i) != op0) {
12272 op0 = 0;
12273 break;
12274 }
12275 if (op0)
12276 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012277 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012278
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012279 // If extracting a specified index from the vector, see if we can recursively
12280 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012281 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012282 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012283 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012284
12285 // If this is extracting an invalid index, turn this into undef, to avoid
12286 // crashing the code below.
12287 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012288 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012289
Chris Lattner867b99f2006-10-05 06:55:50 +000012290 // This instruction only demands the single element from the input vector.
12291 // If the input vector has a single use, simplify it based on this use
12292 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012293 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012294 APInt UndefElts(VectorWidth, 0);
12295 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012296 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012297 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012298 EI.setOperand(0, V);
12299 return &EI;
12300 }
12301 }
12302
Owen Andersond672ecb2009-07-03 00:17:18 +000012303 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012304 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012305
12306 // If the this extractelement is directly using a bitcast from a vector of
12307 // the same number of elements, see if we can find the source element from
12308 // it. In this case, we will end up needing to bitcast the scalars.
12309 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12310 if (const VectorType *VT =
12311 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12312 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012313 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12314 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012315 return new BitCastInst(Elt, EI.getType());
12316 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012317 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012318
Chris Lattner73fa49d2006-05-25 22:53:38 +000012319 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012320 // Push extractelement into predecessor operation if legal and
12321 // profitable to do so
12322 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12323 if (I->hasOneUse() &&
12324 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12325 Value *newEI0 =
12326 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12327 EI.getName()+".lhs");
12328 Value *newEI1 =
12329 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12330 EI.getName()+".rhs");
12331 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012332 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012333 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012334 // Extracting the inserted element?
12335 if (IE->getOperand(2) == EI.getOperand(1))
12336 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12337 // If the inserted and extracted elements are constants, they must not
12338 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012339 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012340 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012341 EI.setOperand(0, IE->getOperand(0));
12342 return &EI;
12343 }
12344 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12345 // If this is extracting an element from a shufflevector, figure out where
12346 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012347 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12348 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012349 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012350 unsigned LHSWidth =
12351 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12352
12353 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012354 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012355 else if (SrcIdx < LHSWidth*2) {
12356 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012357 Src = SVI->getOperand(1);
12358 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012359 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012360 }
Eric Christophera3500da2009-07-25 02:28:41 +000012361 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012362 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12363 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012364 }
12365 }
Eli Friedman2451a642009-07-18 23:06:53 +000012366 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012367 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012368 return 0;
12369}
12370
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012371/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12372/// elements from either LHS or RHS, return the shuffle mask and true.
12373/// Otherwise, return false.
12374static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012375 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012376 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012377 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12378 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012379 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012380
12381 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012382 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012383 return true;
12384 } else if (V == LHS) {
12385 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012386 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012387 return true;
12388 } else if (V == RHS) {
12389 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012390 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012391 return true;
12392 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12393 // If this is an insert of an extract from some other vector, include it.
12394 Value *VecOp = IEI->getOperand(0);
12395 Value *ScalarOp = IEI->getOperand(1);
12396 Value *IdxOp = IEI->getOperand(2);
12397
Chris Lattnerd929f062006-04-27 21:14:21 +000012398 if (!isa<ConstantInt>(IdxOp))
12399 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012400 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012401
12402 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12403 // Okay, we can handle this if the vector we are insertinting into is
12404 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012405 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012406 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012407 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012408 return true;
12409 }
12410 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12411 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012412 EI->getOperand(0)->getType() == V->getType()) {
12413 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012414 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012415
12416 // This must be extracting from either LHS or RHS.
12417 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12418 // Okay, we can handle this if the vector we are insertinting into is
12419 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012420 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012421 // If so, update the mask to reflect the inserted value.
12422 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012423 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012424 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012425 } else {
12426 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012427 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012428 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012429
12430 }
12431 return true;
12432 }
12433 }
12434 }
12435 }
12436 }
12437 // TODO: Handle shufflevector here!
12438
12439 return false;
12440}
12441
12442/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12443/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12444/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012445static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012446 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012447 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012448 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012449 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012450 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012451
12452 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012453 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012454 return V;
12455 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012456 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012457 return V;
12458 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12459 // If this is an insert of an extract from some other vector, include it.
12460 Value *VecOp = IEI->getOperand(0);
12461 Value *ScalarOp = IEI->getOperand(1);
12462 Value *IdxOp = IEI->getOperand(2);
12463
12464 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12465 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12466 EI->getOperand(0)->getType() == V->getType()) {
12467 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012468 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12469 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012470
12471 // Either the extracted from or inserted into vector must be RHSVec,
12472 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012473 if (EI->getOperand(0) == RHS || RHS == 0) {
12474 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012475 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012476 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012477 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012478 return V;
12479 }
12480
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012481 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012482 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12483 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012484 // Everything but the extracted element is replaced with the RHS.
12485 for (unsigned i = 0; i != NumElts; ++i) {
12486 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012487 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012488 }
12489 return V;
12490 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012491
12492 // If this insertelement is a chain that comes from exactly these two
12493 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012494 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12495 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012496 return EI->getOperand(0);
12497
Chris Lattnerefb47352006-04-15 01:39:45 +000012498 }
12499 }
12500 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012501 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012502
12503 // Otherwise, can't do anything fancy. Return an identity vector.
12504 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012505 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012506 return V;
12507}
12508
12509Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12510 Value *VecOp = IE.getOperand(0);
12511 Value *ScalarOp = IE.getOperand(1);
12512 Value *IdxOp = IE.getOperand(2);
12513
Chris Lattner599ded12007-04-09 01:11:16 +000012514 // Inserting an undef or into an undefined place, remove this.
12515 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12516 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012517
Chris Lattnerefb47352006-04-15 01:39:45 +000012518 // If the inserted element was extracted from some other vector, and if the
12519 // indexes are constant, try to turn this into a shufflevector operation.
12520 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12521 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12522 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012523 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012524 unsigned ExtractedIdx =
12525 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012526 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012527
12528 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12529 return ReplaceInstUsesWith(IE, VecOp);
12530
12531 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012532 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012533
12534 // If we are extracting a value from a vector, then inserting it right
12535 // back into the same place, just use the input vector.
12536 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12537 return ReplaceInstUsesWith(IE, VecOp);
12538
Chris Lattnerefb47352006-04-15 01:39:45 +000012539 // If this insertelement isn't used by some other insertelement, turn it
12540 // (and any insertelements it points to), into one big shuffle.
12541 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12542 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012543 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012544 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012545 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012546 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012547 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012548 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012549 }
12550 }
12551 }
12552
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012553 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12554 APInt UndefElts(VWidth, 0);
12555 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12556 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12557 return &IE;
12558
Chris Lattnerefb47352006-04-15 01:39:45 +000012559 return 0;
12560}
12561
12562
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012563Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12564 Value *LHS = SVI.getOperand(0);
12565 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012566 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012567
12568 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012569
Chris Lattner867b99f2006-10-05 06:55:50 +000012570 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012571 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012572 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012573
Dan Gohman488fbfc2008-09-09 18:11:14 +000012574 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012575
12576 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12577 return 0;
12578
Evan Cheng388df622009-02-03 10:05:09 +000012579 APInt UndefElts(VWidth, 0);
12580 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12581 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012582 LHS = SVI.getOperand(0);
12583 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012584 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012585 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012586
Chris Lattner863bcff2006-05-25 23:48:38 +000012587 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12588 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12589 if (LHS == RHS || isa<UndefValue>(LHS)) {
12590 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012591 // shuffle(undef,undef,mask) -> undef.
12592 return ReplaceInstUsesWith(SVI, LHS);
12593 }
12594
Chris Lattner863bcff2006-05-25 23:48:38 +000012595 // Remap any references to RHS to use LHS.
12596 std::vector<Constant*> Elts;
12597 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012598 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012599 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012600 else {
12601 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012602 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012603 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012604 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012605 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012606 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012607 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012608 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012609 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012610 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012611 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012612 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012613 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012614 LHS = SVI.getOperand(0);
12615 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012616 MadeChange = true;
12617 }
12618
Chris Lattner7b2e27922006-05-26 00:29:06 +000012619 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012620 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012621
Chris Lattner863bcff2006-05-25 23:48:38 +000012622 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12623 if (Mask[i] >= e*2) continue; // Ignore undef values.
12624 // Is this an identity shuffle of the LHS value?
12625 isLHSID &= (Mask[i] == i);
12626
12627 // Is this an identity shuffle of the RHS value?
12628 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012629 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012630
Chris Lattner863bcff2006-05-25 23:48:38 +000012631 // Eliminate identity shuffles.
12632 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12633 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012634
Chris Lattner7b2e27922006-05-26 00:29:06 +000012635 // If the LHS is a shufflevector itself, see if we can combine it with this
12636 // one without producing an unusual shuffle. Here we are really conservative:
12637 // we are absolutely afraid of producing a shuffle mask not in the input
12638 // program, because the code gen may not be smart enough to turn a merged
12639 // shuffle into two specific shuffles: it may produce worse code. As such,
12640 // we only merge two shuffles if the result is one of the two input shuffle
12641 // masks. In this case, merging the shuffles just removes one instruction,
12642 // which we know is safe. This is good for things like turning:
12643 // (splat(splat)) -> splat.
12644 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12645 if (isa<UndefValue>(RHS)) {
12646 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12647
12648 std::vector<unsigned> NewMask;
12649 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12650 if (Mask[i] >= 2*e)
12651 NewMask.push_back(2*e);
12652 else
12653 NewMask.push_back(LHSMask[Mask[i]]);
12654
12655 // If the result mask is equal to the src shuffle or this shuffle mask, do
12656 // the replacement.
12657 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012658 unsigned LHSInNElts =
12659 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012660 std::vector<Constant*> Elts;
12661 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012662 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012663 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012664 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012665 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012666 }
12667 }
12668 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12669 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012670 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012671 }
12672 }
12673 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012674
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012675 return MadeChange ? &SVI : 0;
12676}
12677
12678
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012679
Chris Lattnerea1c4542004-12-08 23:43:58 +000012680
12681/// TryToSinkInstruction - Try to move the specified instruction from its
12682/// current block into the beginning of DestBlock, which can only happen if it's
12683/// safe to move the instruction past all of the instructions between it and the
12684/// end of its block.
12685static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12686 assert(I->hasOneUse() && "Invariants didn't hold!");
12687
Chris Lattner108e9022005-10-27 17:13:11 +000012688 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012689 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012690 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012691
Chris Lattnerea1c4542004-12-08 23:43:58 +000012692 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012693 if (isa<AllocaInst>(I) && I->getParent() ==
12694 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012695 return false;
12696
Chris Lattner96a52a62004-12-09 07:14:34 +000012697 // We can only sink load instructions if there is nothing between the load and
12698 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012699 if (I->mayReadFromMemory()) {
12700 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012701 Scan != E; ++Scan)
12702 if (Scan->mayWriteToMemory())
12703 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012704 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012705
Dan Gohman02dea8b2008-05-23 21:05:58 +000012706 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012707
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012708 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012709 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012710 ++NumSunkInst;
12711 return true;
12712}
12713
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012714
12715/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12716/// all reachable code to the worklist.
12717///
12718/// This has a couple of tricks to make the code faster and more powerful. In
12719/// particular, we constant fold and DCE instructions as we go, to avoid adding
12720/// them to the worklist (this significantly speeds up instcombine on code where
12721/// many instructions are dead or constant). Additionally, if we find a branch
12722/// whose condition is a known constant, we only visit the reachable successors.
12723///
Chris Lattner2ee743b2009-10-15 04:59:28 +000012724static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012725 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012726 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012727 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000012728 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000012729 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012730 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000012731
12732 std::vector<Instruction*> InstrsForInstCombineWorklist;
12733 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012734
Chris Lattner2ee743b2009-10-15 04:59:28 +000012735 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12736
Chris Lattner2c7718a2007-03-23 19:17:18 +000012737 while (!Worklist.empty()) {
12738 BB = Worklist.back();
12739 Worklist.pop_back();
12740
12741 // We have now visited this block! If we've already been here, ignore it.
12742 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012743
Chris Lattner2c7718a2007-03-23 19:17:18 +000012744 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12745 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012746
Chris Lattner2c7718a2007-03-23 19:17:18 +000012747 // DCE instruction if trivially dead.
12748 if (isInstructionTriviallyDead(Inst)) {
12749 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012750 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012751 Inst->eraseFromParent();
12752 continue;
12753 }
12754
12755 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012756 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
12757 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12758 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12759 << *Inst << '\n');
12760 Inst->replaceAllUsesWith(C);
12761 ++NumConstProp;
12762 Inst->eraseFromParent();
12763 continue;
12764 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000012765
12766
12767
12768 if (TD) {
12769 // See if we can constant fold its operands.
12770 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12771 i != e; ++i) {
12772 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12773 if (CE == 0) continue;
12774
12775 // If we already folded this constant, don't try again.
12776 if (!FoldedConstants.insert(CE))
12777 continue;
12778
12779 Constant *NewC =
12780 ConstantFoldConstantExpression(CE, BB->getContext(), TD);
12781 if (NewC && NewC != CE) {
12782 *i = NewC;
12783 MadeIRChange = true;
12784 }
12785 }
12786 }
12787
Devang Patel7fe1dec2008-11-19 18:56:50 +000012788
Chris Lattner67f7d542009-10-12 03:58:40 +000012789 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012790 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012791
12792 // Recursively visit successors. If this is a branch or switch on a
12793 // constant, only visit the reachable successor.
12794 TerminatorInst *TI = BB->getTerminator();
12795 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12796 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12797 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012798 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012799 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012800 continue;
12801 }
12802 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12803 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12804 // See if this is an explicit destination.
12805 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12806 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012807 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012808 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012809 continue;
12810 }
12811
12812 // Otherwise it is the default destination.
12813 Worklist.push_back(SI->getSuccessor(0));
12814 continue;
12815 }
12816 }
12817
12818 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12819 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012820 }
Chris Lattner67f7d542009-10-12 03:58:40 +000012821
12822 // Once we've found all of the instructions to add to instcombine's worklist,
12823 // add them in reverse order. This way instcombine will visit from the top
12824 // of the function down. This jives well with the way that it adds all uses
12825 // of instructions to the worklist after doing a transformation, thus avoiding
12826 // some N^2 behavior in pathological cases.
12827 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12828 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000012829
12830 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012831}
12832
Chris Lattnerec9c3582007-03-03 02:04:50 +000012833bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012834 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012835
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012836 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12837 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012838
Chris Lattnerb3d59702005-07-07 20:40:38 +000012839 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012840 // Do a depth-first traversal of the function, populate the worklist with
12841 // the reachable instructions. Ignore blocks that are not reachable. Keep
12842 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012843 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000012844 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012845
Chris Lattnerb3d59702005-07-07 20:40:38 +000012846 // Do a quick scan over the function. If we find any blocks that are
12847 // unreachable, remove any instructions inside of them. This prevents
12848 // the instcombine code from having to deal with some bad special cases.
12849 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12850 if (!Visited.count(BB)) {
12851 Instruction *Term = BB->getTerminator();
12852 while (Term != BB->begin()) { // Remove instrs bottom-up
12853 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012854
Chris Lattnerbdff5482009-08-23 04:37:46 +000012855 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012856 // A debug intrinsic shouldn't force another iteration if we weren't
12857 // going to do one without it.
12858 if (!isa<DbgInfoIntrinsic>(I)) {
12859 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012860 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000012861 }
Devang Patel228ebd02009-10-13 22:56:32 +000012862
Devang Patel228ebd02009-10-13 22:56:32 +000012863 // If I is not void type then replaceAllUsesWith undef.
12864 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000012865 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000012866 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012867 I->eraseFromParent();
12868 }
12869 }
12870 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012871
Chris Lattner873ff012009-08-30 05:55:36 +000012872 while (!Worklist.isEmpty()) {
12873 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012874 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012875
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012876 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012877 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012878 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012879 EraseInstFromFunction(*I);
12880 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012881 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012882 continue;
12883 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012884
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012885 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012886 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
12887 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12888 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012889
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012890 // Add operands to the worklist.
12891 ReplaceInstUsesWith(*I, C);
12892 ++NumConstProp;
12893 EraseInstFromFunction(*I);
12894 MadeIRChange = true;
12895 continue;
12896 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012897
Chris Lattnerea1c4542004-12-08 23:43:58 +000012898 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012899 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012900 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000012901 Instruction *UserInst = cast<Instruction>(I->use_back());
12902 BasicBlock *UserParent;
12903
12904 // Get the block the use occurs in.
12905 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12906 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12907 else
12908 UserParent = UserInst->getParent();
12909
Chris Lattnerea1c4542004-12-08 23:43:58 +000012910 if (UserParent != BB) {
12911 bool UserIsSuccessor = false;
12912 // See if the user is one of our successors.
12913 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12914 if (*SI == UserParent) {
12915 UserIsSuccessor = true;
12916 break;
12917 }
12918
12919 // If the user is one of our immediate successors, and if that successor
12920 // only has us as a predecessors (we'd have to split the critical edge
12921 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000012922 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012923 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012924 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012925 }
12926 }
12927
Chris Lattner74381062009-08-30 07:44:24 +000012928 // Now that we have an instruction, try combining it to simplify it.
12929 Builder->SetInsertPoint(I->getParent(), I);
12930
Reid Spencera9b81012007-03-26 17:44:01 +000012931#ifndef NDEBUG
12932 std::string OrigI;
12933#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012934 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000012935 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12936
Chris Lattner90ac28c2002-08-02 19:29:35 +000012937 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012938 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012939 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012940 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012941 DEBUG(errs() << "IC: Old = " << *I << '\n'
12942 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012943
Chris Lattnerf523d062004-06-09 05:08:07 +000012944 // Everything uses the new instruction now.
12945 I->replaceAllUsesWith(Result);
12946
12947 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012948 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012949 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012950
Chris Lattner6934a042007-02-11 01:23:03 +000012951 // Move the name to the new instruction first.
12952 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012953
12954 // Insert the new instruction into the basic block...
12955 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012956 BasicBlock::iterator InsertPos = I;
12957
12958 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12959 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12960 ++InsertPos;
12961
12962 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012963
Chris Lattner7a1e9242009-08-30 06:13:40 +000012964 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012965 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012966#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012967 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12968 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012969#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012970
Chris Lattner90ac28c2002-08-02 19:29:35 +000012971 // If the instruction was modified, it's possible that it is now dead.
12972 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012973 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012974 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012975 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012976 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012977 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012978 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012979 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012980 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012981 }
12982 }
12983
Chris Lattner873ff012009-08-30 05:55:36 +000012984 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012985 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012986}
12987
Chris Lattnerec9c3582007-03-03 02:04:50 +000012988
12989bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012990 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012991 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012992 TD = getAnalysisIfAvailable<TargetData>();
12993
Chris Lattner74381062009-08-30 07:44:24 +000012994
12995 /// Builder - This is an IRBuilder that automatically inserts new
12996 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012997 IRBuilder<true, TargetFolder, InstCombineIRInserter>
12998 TheBuilder(F.getContext(), TargetFolder(TD, F.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +000012999 InstCombineIRInserter(Worklist));
13000 Builder = &TheBuilder;
13001
Chris Lattnerec9c3582007-03-03 02:04:50 +000013002 bool EverMadeChange = false;
13003
13004 // Iterate while there is work to do.
13005 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013006 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013007 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000013008
13009 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013010 return EverMadeChange;
13011}
13012
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013013FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013014 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013015}