blob: ba899bf15bbac73e0866d1f72370a12ccdc010b0 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000045#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner173234a2008-06-02 01:18:21 +000046#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000047#include "llvm/Target/TargetData.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000051#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000052#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000053#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000054#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000055#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000056#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000057#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000058#include "llvm/Support/PatternMatch.h"
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000059#include "llvm/Support/TargetFolder.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000060#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000061#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000062#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000063#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000064#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000065#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000066#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000067#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000068using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000069using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000070
Chris Lattner0e5f4992006-12-19 21:40:18 +000071STATISTIC(NumCombined , "Number of insts combined");
72STATISTIC(NumConstProp, "Number of constant folds");
73STATISTIC(NumDeadInst , "Number of dead inst eliminated");
74STATISTIC(NumDeadStore, "Number of dead stores eliminated");
75STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000076
Chris Lattner0e5f4992006-12-19 21:40:18 +000077namespace {
Chris Lattner873ff012009-08-30 05:55:36 +000078 /// InstCombineWorklist - This is the worklist management logic for
79 /// InstCombine.
80 class InstCombineWorklist {
81 SmallVector<Instruction*, 256> Worklist;
82 DenseMap<Instruction*, unsigned> WorklistMap;
83
84 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
85 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
86 public:
87 InstCombineWorklist() {}
88
89 bool isEmpty() const { return Worklist.empty(); }
90
91 /// Add - Add the specified instruction to the worklist if it isn't already
92 /// in it.
93 void Add(Instruction *I) {
Jeffrey Yasskin43069632009-10-08 00:12:24 +000094 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
95 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner873ff012009-08-30 05:55:36 +000096 Worklist.push_back(I);
Jeffrey Yasskin43069632009-10-08 00:12:24 +000097 }
Chris Lattner873ff012009-08-30 05:55:36 +000098 }
99
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000100 void AddValue(Value *V) {
101 if (Instruction *I = dyn_cast<Instruction>(V))
102 Add(I);
103 }
104
Chris Lattner67f7d542009-10-12 03:58:40 +0000105 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
106 /// which should only be done when the worklist is empty and when the group
107 /// has no duplicates.
108 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
109 assert(Worklist.empty() && "Worklist must be empty to add initial group");
110 Worklist.reserve(NumEntries+16);
111 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
112 for (; NumEntries; --NumEntries) {
113 Instruction *I = List[NumEntries-1];
114 WorklistMap.insert(std::make_pair(I, Worklist.size()));
115 Worklist.push_back(I);
116 }
117 }
118
Chris Lattner7a1e9242009-08-30 06:13:40 +0000119 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000120 void Remove(Instruction *I) {
121 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
122 if (It == WorklistMap.end()) return; // Not in worklist.
123
124 // Don't bother moving everything down, just null out the slot.
125 Worklist[It->second] = 0;
126
127 WorklistMap.erase(It);
128 }
129
130 Instruction *RemoveOne() {
131 Instruction *I = Worklist.back();
132 Worklist.pop_back();
133 WorklistMap.erase(I);
134 return I;
135 }
136
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000137 /// AddUsersToWorkList - When an instruction is simplified, add all users of
138 /// the instruction to the work lists because they might get more simplified
139 /// now.
140 ///
141 void AddUsersToWorkList(Instruction &I) {
142 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
143 UI != UE; ++UI)
144 Add(cast<Instruction>(*UI));
145 }
146
Chris Lattner873ff012009-08-30 05:55:36 +0000147
148 /// Zap - check that the worklist is empty and nuke the backing store for
149 /// the map if it is large.
150 void Zap() {
151 assert(WorklistMap.empty() && "Worklist empty, but map not?");
152
153 // Do an explicit clear, this shrinks the map if needed.
154 WorklistMap.clear();
155 }
156 };
157} // end anonymous namespace.
158
159
160namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000161 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
162 /// just like the normal insertion helper, but also adds any new instructions
163 /// to the instcombine worklist.
164 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
165 InstCombineWorklist &Worklist;
166 public:
167 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
168
169 void InsertHelper(Instruction *I, const Twine &Name,
170 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
171 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
172 Worklist.Add(I);
173 }
174 };
175} // end anonymous namespace
176
177
178namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000179 class InstCombiner : public FunctionPass,
180 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000181 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000182 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000183 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000184 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000185 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000186 InstCombineWorklist Worklist;
187
Chris Lattner74381062009-08-30 07:44:24 +0000188 /// Builder - This is an IRBuilder that automatically inserts new
189 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +0000190 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000191 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000192
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000193 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000194 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000195
Owen Andersone922c022009-07-22 00:24:57 +0000196 LLVMContext *Context;
197 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000198
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000199 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000200 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000201
202 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000203
Chris Lattner97e52e42002-04-28 21:27:06 +0000204 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000205 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000206 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000207 }
208
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000209 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000210
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000211 // Visitation implementation - Implement instruction combining for different
212 // instruction types. The semantics are as follows:
213 // Return Value:
214 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000215 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000216 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000217 //
Chris Lattner7e708292002-06-25 16:13:24 +0000218 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000219 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000220 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000221 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000222 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000223 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000224 Instruction *visitURem(BinaryOperator &I);
225 Instruction *visitSRem(BinaryOperator &I);
226 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000227 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000228 Instruction *commonRemTransforms(BinaryOperator &I);
229 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000230 Instruction *commonDivTransforms(BinaryOperator &I);
231 Instruction *commonIDivTransforms(BinaryOperator &I);
232 Instruction *visitUDiv(BinaryOperator &I);
233 Instruction *visitSDiv(BinaryOperator &I);
234 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000235 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000236 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000237 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000238 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000239 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000240 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000241 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000242 Instruction *visitOr (BinaryOperator &I);
243 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000244 Instruction *visitShl(BinaryOperator &I);
245 Instruction *visitAShr(BinaryOperator &I);
246 Instruction *visitLShr(BinaryOperator &I);
247 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000248 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
249 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000250 Instruction *visitFCmpInst(FCmpInst &I);
251 Instruction *visitICmpInst(ICmpInst &I);
252 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000253 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
254 Instruction *LHS,
255 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000256 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
257 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000258
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000259 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000260 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000261 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000262 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000263 Instruction *commonCastTransforms(CastInst &CI);
264 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000265 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000266 Instruction *visitTrunc(TruncInst &CI);
267 Instruction *visitZExt(ZExtInst &CI);
268 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000269 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000270 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000271 Instruction *visitFPToUI(FPToUIInst &FI);
272 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000273 Instruction *visitUIToFP(CastInst &CI);
274 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000275 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000276 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000277 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000278 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
279 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000280 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000281 Instruction *visitSelectInst(SelectInst &SI);
282 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000283 Instruction *visitCallInst(CallInst &CI);
284 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000285 Instruction *visitPHINode(PHINode &PN);
286 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000287 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000288 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000289 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000290 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000291 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000292 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000293 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000294 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000295 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000296 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000297
298 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000299 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000300
Chris Lattner9fe38862003-06-19 17:00:31 +0000301 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000302 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000303 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000304 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000305 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
306 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000307 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000308 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
309
Chris Lattner9fe38862003-06-19 17:00:31 +0000310
Chris Lattner28977af2004-04-05 01:30:19 +0000311 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000312 // InsertNewInstBefore - insert an instruction New before instruction Old
313 // in the program. Add the new instruction to the worklist.
314 //
Chris Lattner955f3312004-09-28 21:48:02 +0000315 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000316 assert(New && New->getParent() == 0 &&
317 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000318 BasicBlock *BB = Old.getParent();
319 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000320 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000321 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000322 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000323
Chris Lattner8b170942002-08-09 23:47:40 +0000324 // ReplaceInstUsesWith - This method is to be used when an instruction is
325 // found to be dead, replacable with another preexisting expression. Here
326 // we add all uses of I to the worklist, replace all uses of I with the new
327 // value, then return I, so that the inst combiner will know that I was
328 // modified.
329 //
330 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000331 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000332
333 // If we are replacing the instruction with itself, this must be in a
334 // segment of unreachable code, so just clobber the instruction.
335 if (&I == V)
336 V = UndefValue::get(I.getType());
337
338 I.replaceAllUsesWith(V);
339 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000340 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000341
342 // EraseInstFromFunction - When dealing with an instruction that has side
343 // effects or produces a void value, we can't rely on DCE to delete the
344 // instruction. Instead, visit methods should return the value returned by
345 // this function.
346 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000347 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000348
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000349 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000350 // Make sure that we reprocess all operands now that we reduced their
351 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000352 if (I.getNumOperands() < 8) {
353 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
354 if (Instruction *Op = dyn_cast<Instruction>(*i))
355 Worklist.Add(Op);
356 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000357 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000358 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000359 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000360 return 0; // Don't do anything with FI
361 }
Chris Lattner173234a2008-06-02 01:18:21 +0000362
363 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
364 APInt &KnownOne, unsigned Depth = 0) const {
365 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
366 }
367
368 bool MaskedValueIsZero(Value *V, const APInt &Mask,
369 unsigned Depth = 0) const {
370 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
371 }
372 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
373 return llvm::ComputeNumSignBits(Op, TD, Depth);
374 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000375
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000376 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000377
Reid Spencere4d87aa2006-12-23 06:05:41 +0000378 /// SimplifyCommutative - This performs a few simplifications for
379 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000380 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000381
Reid Spencere4d87aa2006-12-23 06:05:41 +0000382 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
383 /// most-complex to least-complex order.
384 bool SimplifyCompare(CmpInst &I);
385
Chris Lattner886ab6c2009-01-31 08:15:18 +0000386 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
387 /// based on the demanded bits.
388 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
389 APInt& KnownZero, APInt& KnownOne,
390 unsigned Depth);
391 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000392 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000393 unsigned Depth=0);
394
395 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
396 /// SimplifyDemandedBits knows about. See if the instruction has any
397 /// properties that allow us to simplify its operands.
398 bool SimplifyDemandedInstructionBits(Instruction &Inst);
399
Evan Cheng388df622009-02-03 10:05:09 +0000400 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
401 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000402
Chris Lattner5d1704d2009-09-27 19:57:57 +0000403 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
404 // which has a PHI node as operand #0, see if we can fold the instruction
405 // into the PHI (which is only possible if all operands to the PHI are
406 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000407 //
408 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
409 // that would normally be unprofitable because they strongly encourage jump
410 // threading.
411 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000412
Chris Lattnerbac32862004-11-14 19:13:23 +0000413 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
414 // operator and they all are only used by the PHI, PHI together their
415 // inputs, and do the operation once, to the result of the PHI.
416 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000417 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000418 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner751a3622009-11-01 20:04:24 +0000419 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000420
Chris Lattner7da52b22006-11-01 04:51:18 +0000421
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000422 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
423 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000424
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000425 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000426 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000427 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000428 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000429 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000430 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000431 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000432 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000433 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000434
Chris Lattnerafe91a52006-06-15 19:07:26 +0000435
Reid Spencerc55b2432006-12-13 18:21:21 +0000436 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000437
Dan Gohman6de29f82009-06-15 22:12:54 +0000438 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000439 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000440 unsigned GetOrEnforceKnownAlignment(Value *V,
441 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000442
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000443 };
Chris Lattner873ff012009-08-30 05:55:36 +0000444} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000445
Dan Gohman844731a2008-05-13 00:00:25 +0000446char InstCombiner::ID = 0;
447static RegisterPass<InstCombiner>
448X("instcombine", "Combine redundant instructions");
449
Chris Lattner4f98c562003-03-10 21:43:22 +0000450// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000451// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000452static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000453 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000454 if (BinaryOperator::isNeg(V) ||
455 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000456 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000457 return 3;
458 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000459 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000460 if (isa<Argument>(V)) return 3;
461 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000462}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000463
Chris Lattnerc8802d22003-03-11 00:12:48 +0000464// isOnlyUse - Return true if this instruction will be deleted if we stop using
465// it.
466static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000467 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000468}
469
Chris Lattner4cb170c2004-02-23 06:38:22 +0000470// getPromotedType - Return the specified type promoted as it would be to pass
471// though a va_arg area...
472static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000473 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
474 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000475 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000476 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000477 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000478}
479
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000480/// getBitCastOperand - If the specified operand is a CastInst, a constant
481/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
482/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000483static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000484 if (Operator *O = dyn_cast<Operator>(V)) {
485 if (O->getOpcode() == Instruction::BitCast)
486 return O->getOperand(0);
487 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
488 if (GEP->hasAllZeroIndices())
489 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000490 }
Chris Lattnereed48272005-09-13 00:40:14 +0000491 return 0;
492}
493
Reid Spencer3da59db2006-11-27 01:05:10 +0000494/// This function is a wrapper around CastInst::isEliminableCastPair. It
495/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000496static Instruction::CastOps
497isEliminableCastPair(
498 const CastInst *CI, ///< The first cast instruction
499 unsigned opcode, ///< The opcode of the second cast instruction
500 const Type *DstTy, ///< The target type for the second cast instruction
501 TargetData *TD ///< The target data for pointer size
502) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000503
Reid Spencer3da59db2006-11-27 01:05:10 +0000504 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
505 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000506
Reid Spencer3da59db2006-11-27 01:05:10 +0000507 // Get the opcodes of the two Cast instructions
508 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
509 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000510
Chris Lattnera0e69692009-03-24 18:35:40 +0000511 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000512 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000513 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000514
515 // We don't want to form an inttoptr or ptrtoint that converts to an integer
516 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000517 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000518 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000519 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000520 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000521 Res = 0;
522
523 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000524}
525
526/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
527/// in any code being generated. It does not require codegen if V is simple
528/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000529static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
530 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000531 if (V->getType() == Ty || isa<Constant>(V)) return false;
532
Chris Lattner01575b72006-05-25 23:24:33 +0000533 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000534 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000535 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000536 return false;
537 return true;
538}
539
Chris Lattner4f98c562003-03-10 21:43:22 +0000540// SimplifyCommutative - This performs a few simplifications for commutative
541// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000542//
Chris Lattner4f98c562003-03-10 21:43:22 +0000543// 1. Order operands such that they are listed from right (least complex) to
544// left (most complex). This puts constants before unary operators before
545// binary operators.
546//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000547// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
548// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000549//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000550bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000551 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000552 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000553 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000554
Chris Lattner4f98c562003-03-10 21:43:22 +0000555 if (!I.isAssociative()) return Changed;
556 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000557 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
558 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
559 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000560 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000561 cast<Constant>(I.getOperand(1)),
562 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000563 I.setOperand(0, Op->getOperand(0));
564 I.setOperand(1, Folded);
565 return true;
566 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
567 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
568 isOnlyUse(Op) && isOnlyUse(Op1)) {
569 Constant *C1 = cast<Constant>(Op->getOperand(1));
570 Constant *C2 = cast<Constant>(Op1->getOperand(1));
571
572 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000573 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000574 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000575 Op1->getOperand(0),
576 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000577 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000578 I.setOperand(0, New);
579 I.setOperand(1, Folded);
580 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000581 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000582 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000583 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000584}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000585
Reid Spencere4d87aa2006-12-23 06:05:41 +0000586/// SimplifyCompare - For a CmpInst this function just orders the operands
587/// so that theyare listed from right (least complex) to left (most complex).
588/// This puts constants before unary operators before binary operators.
589bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000590 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000591 return false;
592 I.swapOperands();
593 // Compare instructions are not associative so there's nothing else we can do.
594 return true;
595}
596
Chris Lattner8d969642003-03-10 23:06:50 +0000597// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
598// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000599//
Dan Gohman186a6362009-08-12 16:04:34 +0000600static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000601 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000602 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000603
Chris Lattner0ce85802004-12-14 20:08:06 +0000604 // Constants can be considered to be negated values if they can be folded.
605 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000606 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000607
608 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
609 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000610 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000611
Chris Lattner8d969642003-03-10 23:06:50 +0000612 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000613}
614
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000615// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
616// instruction if the LHS is a constant negative zero (which is the 'negate'
617// form).
618//
Dan Gohman186a6362009-08-12 16:04:34 +0000619static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000620 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000621 return BinaryOperator::getFNegArgument(V);
622
623 // Constants can be considered to be negated values if they can be folded.
624 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000625 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000626
627 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
628 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000629 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000630
631 return 0;
632}
633
Chris Lattner48b59ec2009-10-26 15:40:07 +0000634/// isFreeToInvert - Return true if the specified value is free to invert (apply
635/// ~ to). This happens in cases where the ~ can be eliminated.
636static inline bool isFreeToInvert(Value *V) {
637 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000638 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000639 return true;
640
641 // Constants can be considered to be not'ed values.
642 if (isa<ConstantInt>(V))
643 return true;
644
645 // Compares can be inverted if they have a single use.
646 if (CmpInst *CI = dyn_cast<CmpInst>(V))
647 return CI->hasOneUse();
648
649 return false;
650}
651
652static inline Value *dyn_castNotVal(Value *V) {
653 // If this is not(not(x)) don't return that this is a not: we want the two
654 // not's to be folded first.
655 if (BinaryOperator::isNot(V)) {
656 Value *Operand = BinaryOperator::getNotArgument(V);
657 if (!isFreeToInvert(Operand))
658 return Operand;
659 }
Chris Lattner8d969642003-03-10 23:06:50 +0000660
661 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000662 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000663 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000664 return 0;
665}
666
Chris Lattner48b59ec2009-10-26 15:40:07 +0000667
668
Chris Lattnerc8802d22003-03-11 00:12:48 +0000669// dyn_castFoldableMul - If this value is a multiply that can be folded into
670// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000671// non-constant operand of the multiply, and set CST to point to the multiplier.
672// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000673//
Dan Gohman186a6362009-08-12 16:04:34 +0000674static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000675 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000676 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000677 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000678 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000679 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000680 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000681 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000682 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000683 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000684 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000685 CST = ConstantInt::get(V->getType()->getContext(),
686 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000687 return I->getOperand(0);
688 }
689 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000690 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000691}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000692
Reid Spencer7177c3a2007-03-25 05:33:51 +0000693/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000694static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000695 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000696 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000697}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000698/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000699static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000700 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000701 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000702}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000703/// MultiplyOverflows - True if the multiply can not be expressed in an int
704/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000705static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000706 uint32_t W = C1->getBitWidth();
707 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
708 if (sign) {
709 LHSExt.sext(W * 2);
710 RHSExt.sext(W * 2);
711 } else {
712 LHSExt.zext(W * 2);
713 RHSExt.zext(W * 2);
714 }
715
716 APInt MulExt = LHSExt * RHSExt;
717
718 if (sign) {
719 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
720 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
721 return MulExt.slt(Min) || MulExt.sgt(Max);
722 } else
723 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
724}
Chris Lattner955f3312004-09-28 21:48:02 +0000725
Reid Spencere7816b52007-03-08 01:52:58 +0000726
Chris Lattner255d8912006-02-11 09:31:47 +0000727/// ShrinkDemandedConstant - Check to see if the specified operand of the
728/// specified instruction is a constant integer. If so, check to see if there
729/// are any bits set in the constant that are not demanded. If so, shrink the
730/// constant and return true.
731static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000732 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000733 assert(I && "No instruction?");
734 assert(OpNo < I->getNumOperands() && "Operand index too large");
735
736 // If the operand is not a constant integer, nothing to do.
737 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
738 if (!OpC) return false;
739
740 // If there are no bits set that aren't demanded, nothing to do.
741 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
742 if ((~Demanded & OpC->getValue()) == 0)
743 return false;
744
745 // This instruction is producing bits that are not demanded. Shrink the RHS.
746 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000747 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000748 return true;
749}
750
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000751// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
752// set of known zero and one bits, compute the maximum and minimum values that
753// could have the specified known zero and known one bits, returning them in
754// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000755static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000756 const APInt& KnownOne,
757 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000758 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
759 KnownZero.getBitWidth() == Min.getBitWidth() &&
760 KnownZero.getBitWidth() == Max.getBitWidth() &&
761 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000762 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000763
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000764 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
765 // bit if it is unknown.
766 Min = KnownOne;
767 Max = KnownOne|UnknownBits;
768
Dan Gohman1c8491e2009-04-25 17:12:48 +0000769 if (UnknownBits.isNegative()) { // Sign bit is unknown
770 Min.set(Min.getBitWidth()-1);
771 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000772 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000773}
774
775// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
776// a set of known zero and one bits, compute the maximum and minimum values that
777// could have the specified known zero and known one bits, returning them in
778// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000779static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000780 const APInt &KnownOne,
781 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000782 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
783 KnownZero.getBitWidth() == Min.getBitWidth() &&
784 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000785 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000786 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000787
788 // The minimum value is when the unknown bits are all zeros.
789 Min = KnownOne;
790 // The maximum value is when the unknown bits are all ones.
791 Max = KnownOne|UnknownBits;
792}
Chris Lattner255d8912006-02-11 09:31:47 +0000793
Chris Lattner886ab6c2009-01-31 08:15:18 +0000794/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
795/// SimplifyDemandedBits knows about. See if the instruction has any
796/// properties that allow us to simplify its operands.
797bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000798 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000799 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
800 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
801
802 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
803 KnownZero, KnownOne, 0);
804 if (V == 0) return false;
805 if (V == &Inst) return true;
806 ReplaceInstUsesWith(Inst, V);
807 return true;
808}
809
810/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
811/// specified instruction operand if possible, updating it in place. It returns
812/// true if it made any change and false otherwise.
813bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
814 APInt &KnownZero, APInt &KnownOne,
815 unsigned Depth) {
816 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
817 KnownZero, KnownOne, Depth);
818 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000819 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000820 return true;
821}
822
823
824/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
825/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000826/// that only the bits set in DemandedMask of the result of V are ever used
827/// downstream. Consequently, depending on the mask and V, it may be possible
828/// to replace V with a constant or one of its operands. In such cases, this
829/// function does the replacement and returns true. In all other cases, it
830/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000831/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000832/// to be zero in the expression. These are provided to potentially allow the
833/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
834/// the expression. KnownOne and KnownZero always follow the invariant that
835/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
836/// the bits in KnownOne and KnownZero may only be accurate for those bits set
837/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
838/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000839///
840/// This returns null if it did not change anything and it permits no
841/// simplification. This returns V itself if it did some simplification of V's
842/// operands based on the information about what bits are demanded. This returns
843/// some other non-null value if it found out that V is equal to another value
844/// in the context where the specified bits are demanded, but not for all users.
845Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
846 APInt &KnownZero, APInt &KnownOne,
847 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000848 assert(V != 0 && "Null pointer of Value???");
849 assert(Depth <= 6 && "Limit Search Depth");
850 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000851 const Type *VTy = V->getType();
852 assert((TD || !isa<PointerType>(VTy)) &&
853 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000854 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
855 (!VTy->isIntOrIntVector() ||
856 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000857 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000858 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000859 "Value *V, DemandedMask, KnownZero and KnownOne "
860 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000861 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
862 // We know all of the bits for a constant!
863 KnownOne = CI->getValue() & DemandedMask;
864 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000865 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000866 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000867 if (isa<ConstantPointerNull>(V)) {
868 // We know all of the bits for a constant!
869 KnownOne.clear();
870 KnownZero = DemandedMask;
871 return 0;
872 }
873
Chris Lattner08d2cc72009-01-31 07:26:06 +0000874 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000875 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000876 if (DemandedMask == 0) { // Not demanding any bits from V.
877 if (isa<UndefValue>(V))
878 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000879 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000880 }
881
Chris Lattner4598c942009-01-31 08:24:16 +0000882 if (Depth == 6) // Limit search depth.
883 return 0;
884
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000885 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
886 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
887
Dan Gohman1c8491e2009-04-25 17:12:48 +0000888 Instruction *I = dyn_cast<Instruction>(V);
889 if (!I) {
890 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
891 return 0; // Only analyze instructions.
892 }
893
Chris Lattner4598c942009-01-31 08:24:16 +0000894 // If there are multiple uses of this value and we aren't at the root, then
895 // we can't do any simplifications of the operands, because DemandedMask
896 // only reflects the bits demanded by *one* of the users.
897 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000898 // Despite the fact that we can't simplify this instruction in all User's
899 // context, we can at least compute the knownzero/knownone bits, and we can
900 // do simplifications that apply to *just* the one user if we know that
901 // this instruction has a simpler value in that context.
902 if (I->getOpcode() == Instruction::And) {
903 // If either the LHS or the RHS are Zero, the result is zero.
904 ComputeMaskedBits(I->getOperand(1), DemandedMask,
905 RHSKnownZero, RHSKnownOne, Depth+1);
906 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
907 LHSKnownZero, LHSKnownOne, Depth+1);
908
909 // If all of the demanded bits are known 1 on one side, return the other.
910 // These bits cannot contribute to the result of the 'and' in this
911 // context.
912 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
913 (DemandedMask & ~LHSKnownZero))
914 return I->getOperand(0);
915 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
916 (DemandedMask & ~RHSKnownZero))
917 return I->getOperand(1);
918
919 // If all of the demanded bits in the inputs are known zeros, return zero.
920 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000921 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000922
923 } else if (I->getOpcode() == Instruction::Or) {
924 // We can simplify (X|Y) -> X or Y in the user's context if we know that
925 // only bits from X or Y are demanded.
926
927 // If either the LHS or the RHS are One, the result is One.
928 ComputeMaskedBits(I->getOperand(1), DemandedMask,
929 RHSKnownZero, RHSKnownOne, Depth+1);
930 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
931 LHSKnownZero, LHSKnownOne, Depth+1);
932
933 // If all of the demanded bits are known zero on one side, return the
934 // other. These bits cannot contribute to the result of the 'or' in this
935 // context.
936 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
937 (DemandedMask & ~LHSKnownOne))
938 return I->getOperand(0);
939 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
940 (DemandedMask & ~RHSKnownOne))
941 return I->getOperand(1);
942
943 // If all of the potentially set bits on one side are known to be set on
944 // the other side, just use the 'other' side.
945 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
946 (DemandedMask & (~RHSKnownZero)))
947 return I->getOperand(0);
948 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
949 (DemandedMask & (~LHSKnownZero)))
950 return I->getOperand(1);
951 }
952
Chris Lattner4598c942009-01-31 08:24:16 +0000953 // Compute the KnownZero/KnownOne bits to simplify things downstream.
954 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
955 return 0;
956 }
957
958 // If this is the root being simplified, allow it to have multiple uses,
959 // just set the DemandedMask to all bits so that we can try to simplify the
960 // operands. This allows visitTruncInst (for example) to simplify the
961 // operand of a trunc without duplicating all the logic below.
962 if (Depth == 0 && !V->hasOneUse())
963 DemandedMask = APInt::getAllOnesValue(BitWidth);
964
Reid Spencer8cb68342007-03-12 17:25:59 +0000965 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000966 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000967 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000968 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000969 case Instruction::And:
970 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000971 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
972 RHSKnownZero, RHSKnownOne, Depth+1) ||
973 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000974 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000975 return I;
976 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
977 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000978
979 // If all of the demanded bits are known 1 on one side, return the other.
980 // These bits cannot contribute to the result of the 'and'.
981 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
982 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000983 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000984 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
985 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000986 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000987
988 // If all of the demanded bits in the inputs are known zeros, return zero.
989 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000990 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000991
992 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000993 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000994 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000995
996 // Output known-1 bits are only known if set in both the LHS & RHS.
997 RHSKnownOne &= LHSKnownOne;
998 // Output known-0 are known to be clear if zero in either the LHS | RHS.
999 RHSKnownZero |= LHSKnownZero;
1000 break;
1001 case Instruction::Or:
1002 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001003 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1004 RHSKnownZero, RHSKnownOne, Depth+1) ||
1005 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +00001006 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001007 return I;
1008 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1009 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001010
1011 // If all of the demanded bits are known zero on one side, return the other.
1012 // These bits cannot contribute to the result of the 'or'.
1013 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1014 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001015 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001016 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1017 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001018 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001019
1020 // If all of the potentially set bits on one side are known to be set on
1021 // the other side, just use the 'other' side.
1022 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1023 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001024 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001025 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1026 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001027 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001028
1029 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001030 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001031 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001032
1033 // Output known-0 bits are only known if clear in both the LHS & RHS.
1034 RHSKnownZero &= LHSKnownZero;
1035 // Output known-1 are known to be set if set in either the LHS | RHS.
1036 RHSKnownOne |= LHSKnownOne;
1037 break;
1038 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001039 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1040 RHSKnownZero, RHSKnownOne, Depth+1) ||
1041 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001042 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001043 return I;
1044 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1045 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001046
1047 // If all of the demanded bits are known zero on one side, return the other.
1048 // These bits cannot contribute to the result of the 'xor'.
1049 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001050 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001051 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001052 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001053
1054 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1055 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1056 (RHSKnownOne & LHSKnownOne);
1057 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1058 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1059 (RHSKnownOne & LHSKnownZero);
1060
1061 // If all of the demanded bits are known to be zero on one side or the
1062 // other, turn this into an *inclusive* or.
1063 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001064 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1065 Instruction *Or =
1066 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1067 I->getName());
1068 return InsertNewInstBefore(Or, *I);
1069 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001070
1071 // If all of the demanded bits on one side are known, and all of the set
1072 // bits on that side are also known to be set on the other side, turn this
1073 // into an AND, as we know the bits will be cleared.
1074 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1075 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1076 // all known
1077 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001078 Constant *AndC = Constant::getIntegerValue(VTy,
1079 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001080 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001081 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001082 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001083 }
1084 }
1085
1086 // If the RHS is a constant, see if we can simplify it.
1087 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001088 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001089 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001090
Chris Lattnerd0883142009-10-11 22:22:13 +00001091 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1092 // are flipping are known to be set, then the xor is just resetting those
1093 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1094 // simplifying both of them.
1095 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1096 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1097 isa<ConstantInt>(I->getOperand(1)) &&
1098 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1099 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1100 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1101 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1102 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1103
1104 Constant *AndC =
1105 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1106 Instruction *NewAnd =
1107 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1108 InsertNewInstBefore(NewAnd, *I);
1109
1110 Constant *XorC =
1111 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1112 Instruction *NewXor =
1113 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1114 return InsertNewInstBefore(NewXor, *I);
1115 }
1116
1117
Reid Spencer8cb68342007-03-12 17:25:59 +00001118 RHSKnownZero = KnownZeroOut;
1119 RHSKnownOne = KnownOneOut;
1120 break;
1121 }
1122 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001123 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1124 RHSKnownZero, RHSKnownOne, Depth+1) ||
1125 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001126 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001127 return I;
1128 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1129 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001130
1131 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001132 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1133 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001134 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001135
1136 // Only known if known in both the LHS and RHS.
1137 RHSKnownOne &= LHSKnownOne;
1138 RHSKnownZero &= LHSKnownZero;
1139 break;
1140 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001141 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001142 DemandedMask.zext(truncBf);
1143 RHSKnownZero.zext(truncBf);
1144 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001145 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001146 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001147 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001148 DemandedMask.trunc(BitWidth);
1149 RHSKnownZero.trunc(BitWidth);
1150 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001151 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001152 break;
1153 }
1154 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001155 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001156 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001157
1158 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1159 if (const VectorType *SrcVTy =
1160 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1161 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1162 // Don't touch a bitcast between vectors of different element counts.
1163 return false;
1164 } else
1165 // Don't touch a scalar-to-vector bitcast.
1166 return false;
1167 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1168 // Don't touch a vector-to-scalar bitcast.
1169 return false;
1170
Chris Lattner886ab6c2009-01-31 08:15:18 +00001171 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001172 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001173 return I;
1174 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001175 break;
1176 case Instruction::ZExt: {
1177 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001178 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001179
Zhou Shengd48653a2007-03-29 04:45:55 +00001180 DemandedMask.trunc(SrcBitWidth);
1181 RHSKnownZero.trunc(SrcBitWidth);
1182 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001183 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001184 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001185 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001186 DemandedMask.zext(BitWidth);
1187 RHSKnownZero.zext(BitWidth);
1188 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001189 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001190 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001191 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001192 break;
1193 }
1194 case Instruction::SExt: {
1195 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001196 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001197
Reid Spencer8cb68342007-03-12 17:25:59 +00001198 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001199 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001200
Zhou Sheng01542f32007-03-29 02:26:30 +00001201 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001202 // If any of the sign extended bits are demanded, we know that the sign
1203 // bit is demanded.
1204 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001205 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001206
Zhou Shengd48653a2007-03-29 04:45:55 +00001207 InputDemandedBits.trunc(SrcBitWidth);
1208 RHSKnownZero.trunc(SrcBitWidth);
1209 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001210 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001211 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001212 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001213 InputDemandedBits.zext(BitWidth);
1214 RHSKnownZero.zext(BitWidth);
1215 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001216 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001217
1218 // If the sign bit of the input is known set or clear, then we know the
1219 // top bits of the result.
1220
1221 // If the input sign bit is known zero, or if the NewBits are not demanded
1222 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001223 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001224 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001225 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1226 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001227 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001228 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001229 }
1230 break;
1231 }
1232 case Instruction::Add: {
1233 // Figure out what the input bits are. If the top bits of the and result
1234 // are not demanded, then the add doesn't demand them from its input
1235 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001236 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001237
1238 // If there is a constant on the RHS, there are a variety of xformations
1239 // we can do.
1240 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1241 // If null, this should be simplified elsewhere. Some of the xforms here
1242 // won't work if the RHS is zero.
1243 if (RHS->isZero())
1244 break;
1245
1246 // If the top bit of the output is demanded, demand everything from the
1247 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001248 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001249
1250 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001251 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001252 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001253 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001254
1255 // If the RHS of the add has bits set that can't affect the input, reduce
1256 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001257 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001258 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001259
1260 // Avoid excess work.
1261 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1262 break;
1263
1264 // Turn it into OR if input bits are zero.
1265 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1266 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001267 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001268 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001269 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 }
1271
1272 // We can say something about the output known-zero and known-one bits,
1273 // depending on potential carries from the input constant and the
1274 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1275 // bits set and the RHS constant is 0x01001, then we know we have a known
1276 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1277
1278 // To compute this, we first compute the potential carry bits. These are
1279 // the bits which may be modified. I'm not aware of a better way to do
1280 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001281 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001282 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001283
1284 // Now that we know which bits have carries, compute the known-1/0 sets.
1285
1286 // Bits are known one if they are known zero in one operand and one in the
1287 // other, and there is no input carry.
1288 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1289 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1290
1291 // Bits are known zero if they are known zero in both operands and there
1292 // is no input carry.
1293 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1294 } else {
1295 // If the high-bits of this ADD are not demanded, then it does not demand
1296 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001297 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 // Right fill the mask of bits for this ADD to demand the most
1299 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001300 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001301 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1302 LHSKnownZero, LHSKnownOne, Depth+1) ||
1303 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001304 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001305 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001306 }
1307 }
1308 break;
1309 }
1310 case Instruction::Sub:
1311 // If the high-bits of this SUB are not demanded, then it does not demand
1312 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001313 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001314 // Right fill the mask of bits for this SUB to demand the most
1315 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001316 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001317 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001318 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1319 LHSKnownZero, LHSKnownOne, Depth+1) ||
1320 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001321 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001322 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001323 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001324 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1325 // the known zeros and ones.
1326 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001327 break;
1328 case Instruction::Shl:
1329 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001330 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001331 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001332 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001333 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001334 return I;
1335 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001336 RHSKnownZero <<= ShiftAmt;
1337 RHSKnownOne <<= ShiftAmt;
1338 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001339 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001340 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001341 }
1342 break;
1343 case Instruction::LShr:
1344 // For a logical shift right
1345 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001346 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001347
Reid Spencer8cb68342007-03-12 17:25:59 +00001348 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001349 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001350 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001351 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001352 return I;
1353 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001354 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1355 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001356 if (ShiftAmt) {
1357 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001358 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001359 RHSKnownZero |= HighBits; // high bits known zero.
1360 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001361 }
1362 break;
1363 case Instruction::AShr:
1364 // If this is an arithmetic shift right and only the low-bit is set, we can
1365 // always convert this into a logical shr, even if the shift amount is
1366 // variable. The low bit of the shift cannot be an input sign bit unless
1367 // the shift amount is >= the size of the datatype, which is undefined.
1368 if (DemandedMask == 1) {
1369 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001370 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001371 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001372 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001373 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001374
1375 // If the sign bit is the only bit demanded by this ashr, then there is no
1376 // need to do it, the shift doesn't change the high bit.
1377 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001378 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001379
1380 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001381 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001382
Reid Spencer8cb68342007-03-12 17:25:59 +00001383 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001384 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001385 // If any of the "high bits" are demanded, we should set the sign bit as
1386 // demanded.
1387 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1388 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001389 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001390 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001391 return I;
1392 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001393 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001394 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001395 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1396 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1397
1398 // Handle the sign bits.
1399 APInt SignBit(APInt::getSignBit(BitWidth));
1400 // Adjust to where it is now in the mask.
1401 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1402
1403 // If the input sign bit is known to be zero, or if none of the top bits
1404 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001405 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001406 (HighBits & ~DemandedMask) == HighBits) {
1407 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001408 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001409 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001410 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001411 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1412 RHSKnownOne |= HighBits;
1413 }
1414 }
1415 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001416 case Instruction::SRem:
1417 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001418 APInt RA = Rem->getValue().abs();
1419 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001420 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001421 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001422
Nick Lewycky8e394322008-11-02 02:41:50 +00001423 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001424 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001425 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001426 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001427 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001428
1429 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1430 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001431
1432 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001433
Chris Lattner886ab6c2009-01-31 08:15:18 +00001434 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001435 }
1436 }
1437 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001438 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001439 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1440 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001441 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1442 KnownZero2, KnownOne2, Depth+1) ||
1443 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001444 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001445 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001446
Chris Lattner455e9ab2009-01-21 18:09:24 +00001447 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001448 Leaders = std::max(Leaders,
1449 KnownZero2.countLeadingOnes());
1450 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001451 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001452 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001453 case Instruction::Call:
1454 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1455 switch (II->getIntrinsicID()) {
1456 default: break;
1457 case Intrinsic::bswap: {
1458 // If the only bits demanded come from one byte of the bswap result,
1459 // just shift the input byte into position to eliminate the bswap.
1460 unsigned NLZ = DemandedMask.countLeadingZeros();
1461 unsigned NTZ = DemandedMask.countTrailingZeros();
1462
1463 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1464 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1465 // have 14 leading zeros, round to 8.
1466 NLZ &= ~7;
1467 NTZ &= ~7;
1468 // If we need exactly one byte, we can do this transformation.
1469 if (BitWidth-NLZ-NTZ == 8) {
1470 unsigned ResultBit = NTZ;
1471 unsigned InputBit = BitWidth-NTZ-8;
1472
1473 // Replace this with either a left or right shift to get the byte into
1474 // the right place.
1475 Instruction *NewVal;
1476 if (InputBit > ResultBit)
1477 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001478 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001479 else
1480 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001481 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001482 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001483 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001484 }
1485
1486 // TODO: Could compute known zero/one bits based on the input.
1487 break;
1488 }
1489 }
1490 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001491 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001492 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001493 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001494
1495 // If the client is only demanding bits that we know, return the known
1496 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001497 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1498 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001499 return false;
1500}
1501
Chris Lattner867b99f2006-10-05 06:55:50 +00001502
Mon P Wangaeb06d22008-11-10 04:46:22 +00001503/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001504/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001505/// actually used by the caller. This method analyzes which elements of the
1506/// operand are undef and returns that information in UndefElts.
1507///
1508/// If the information about demanded elements can be used to simplify the
1509/// operation, the operation is simplified, then the resultant value is
1510/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001511Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1512 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001513 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001514 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001515 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001516 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001517
1518 if (isa<UndefValue>(V)) {
1519 // If the entire vector is undefined, just return this info.
1520 UndefElts = EltMask;
1521 return 0;
1522 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1523 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001524 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001525 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001526
Chris Lattner867b99f2006-10-05 06:55:50 +00001527 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001528 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1529 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001530 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001531
1532 std::vector<Constant*> Elts;
1533 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001534 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001535 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001536 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001537 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1538 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001539 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001540 } else { // Otherwise, defined.
1541 Elts.push_back(CP->getOperand(i));
1542 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001543
Chris Lattner867b99f2006-10-05 06:55:50 +00001544 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001545 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001546 return NewCP != CP ? NewCP : 0;
1547 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001548 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001549 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001550
1551 // Check if this is identity. If so, return 0 since we are not simplifying
1552 // anything.
1553 if (DemandedElts == ((1ULL << VWidth) -1))
1554 return 0;
1555
Reid Spencer9d6565a2007-02-15 02:26:10 +00001556 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001557 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001558 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001559 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001560 for (unsigned i = 0; i != VWidth; ++i) {
1561 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1562 Elts.push_back(Elt);
1563 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001564 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001565 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001566 }
1567
Dan Gohman488fbfc2008-09-09 18:11:14 +00001568 // Limit search depth.
1569 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001570 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571
1572 // If multiple users are using the root value, procede with
1573 // simplification conservatively assuming that all elements
1574 // are needed.
1575 if (!V->hasOneUse()) {
1576 // Quit if we find multiple users of a non-root value though.
1577 // They'll be handled when it's their turn to be visited by
1578 // the main instcombine process.
1579 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001580 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001581 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001582
1583 // Conservatively assume that all elements are needed.
1584 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001585 }
1586
1587 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001588 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001589
1590 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001591 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001592 Value *TmpV;
1593 switch (I->getOpcode()) {
1594 default: break;
1595
1596 case Instruction::InsertElement: {
1597 // If this is a variable index, we don't know which element it overwrites.
1598 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001599 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001600 if (Idx == 0) {
1601 // Note that we can't propagate undef elt info, because we don't know
1602 // which elt is getting updated.
1603 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1604 UndefElts2, Depth+1);
1605 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1606 break;
1607 }
1608
1609 // If this is inserting an element that isn't demanded, remove this
1610 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001611 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001612 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1613 Worklist.Add(I);
1614 return I->getOperand(0);
1615 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001616
1617 // Otherwise, the element inserted overwrites whatever was there, so the
1618 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001619 APInt DemandedElts2 = DemandedElts;
1620 DemandedElts2.clear(IdxNo);
1621 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001622 UndefElts, Depth+1);
1623 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1624
1625 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001626 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001627 break;
1628 }
1629 case Instruction::ShuffleVector: {
1630 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001631 uint64_t LHSVWidth =
1632 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001633 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001634 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001635 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001636 unsigned MaskVal = Shuffle->getMaskValue(i);
1637 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001638 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001639 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001640 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001641 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001642 else
Evan Cheng388df622009-02-03 10:05:09 +00001643 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001644 }
1645 }
1646 }
1647
Nate Begeman7b254672009-02-11 22:36:25 +00001648 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001649 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001650 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001651 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1652
Nate Begeman7b254672009-02-11 22:36:25 +00001653 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001654 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1655 UndefElts3, Depth+1);
1656 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1657
1658 bool NewUndefElts = false;
1659 for (unsigned i = 0; i < VWidth; i++) {
1660 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001661 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001662 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001663 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001664 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001665 NewUndefElts = true;
1666 UndefElts.set(i);
1667 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001668 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001669 if (UndefElts3[MaskVal - LHSVWidth]) {
1670 NewUndefElts = true;
1671 UndefElts.set(i);
1672 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001673 }
1674 }
1675
1676 if (NewUndefElts) {
1677 // Add additional discovered undefs.
1678 std::vector<Constant*> Elts;
1679 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001680 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001681 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001682 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001683 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001684 Shuffle->getMaskValue(i)));
1685 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001686 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001687 MadeChange = true;
1688 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001689 break;
1690 }
Chris Lattner69878332007-04-14 22:29:23 +00001691 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001692 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001693 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1694 if (!VTy) break;
1695 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001696 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001697 unsigned Ratio;
1698
1699 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001700 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001701 // elements as are demanded of us.
1702 Ratio = 1;
1703 InputDemandedElts = DemandedElts;
1704 } else if (VWidth > InVWidth) {
1705 // Untested so far.
1706 break;
1707
1708 // If there are more elements in the result than there are in the source,
1709 // then an input element is live if any of the corresponding output
1710 // elements are live.
1711 Ratio = VWidth/InVWidth;
1712 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001713 if (DemandedElts[OutIdx])
1714 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001715 }
1716 } else {
1717 // Untested so far.
1718 break;
1719
1720 // If there are more elements in the source than there are in the result,
1721 // then an input element is live if the corresponding output element is
1722 // live.
1723 Ratio = InVWidth/VWidth;
1724 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001725 if (DemandedElts[InIdx/Ratio])
1726 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001727 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001728
Chris Lattner69878332007-04-14 22:29:23 +00001729 // div/rem demand all inputs, because they don't want divide by zero.
1730 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1731 UndefElts2, Depth+1);
1732 if (TmpV) {
1733 I->setOperand(0, TmpV);
1734 MadeChange = true;
1735 }
1736
1737 UndefElts = UndefElts2;
1738 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001739 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001740 // If there are more elements in the result than there are in the source,
1741 // then an output element is undef if the corresponding input element is
1742 // undef.
1743 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001744 if (UndefElts2[OutIdx/Ratio])
1745 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001746 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001747 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001748 // If there are more elements in the source than there are in the result,
1749 // then a result element is undef if all of the corresponding input
1750 // elements are undef.
1751 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1752 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001753 if (!UndefElts2[InIdx]) // Not undef?
1754 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001755 }
1756 break;
1757 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001758 case Instruction::And:
1759 case Instruction::Or:
1760 case Instruction::Xor:
1761 case Instruction::Add:
1762 case Instruction::Sub:
1763 case Instruction::Mul:
1764 // div/rem demand all inputs, because they don't want divide by zero.
1765 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1766 UndefElts, Depth+1);
1767 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1768 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1769 UndefElts2, Depth+1);
1770 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1771
1772 // Output elements are undefined if both are undefined. Consider things
1773 // like undef&0. The result is known zero, not undef.
1774 UndefElts &= UndefElts2;
1775 break;
1776
1777 case Instruction::Call: {
1778 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1779 if (!II) break;
1780 switch (II->getIntrinsicID()) {
1781 default: break;
1782
1783 // Binary vector operations that work column-wise. A dest element is a
1784 // function of the corresponding input elements from the two inputs.
1785 case Intrinsic::x86_sse_sub_ss:
1786 case Intrinsic::x86_sse_mul_ss:
1787 case Intrinsic::x86_sse_min_ss:
1788 case Intrinsic::x86_sse_max_ss:
1789 case Intrinsic::x86_sse2_sub_sd:
1790 case Intrinsic::x86_sse2_mul_sd:
1791 case Intrinsic::x86_sse2_min_sd:
1792 case Intrinsic::x86_sse2_max_sd:
1793 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1794 UndefElts, Depth+1);
1795 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1796 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1797 UndefElts2, Depth+1);
1798 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1799
1800 // If only the low elt is demanded and this is a scalarizable intrinsic,
1801 // scalarize it now.
1802 if (DemandedElts == 1) {
1803 switch (II->getIntrinsicID()) {
1804 default: break;
1805 case Intrinsic::x86_sse_sub_ss:
1806 case Intrinsic::x86_sse_mul_ss:
1807 case Intrinsic::x86_sse2_sub_sd:
1808 case Intrinsic::x86_sse2_mul_sd:
1809 // TODO: Lower MIN/MAX/ABS/etc
1810 Value *LHS = II->getOperand(1);
1811 Value *RHS = II->getOperand(2);
1812 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001813 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001814 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001815 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001816 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001817
1818 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001819 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001820 case Intrinsic::x86_sse_sub_ss:
1821 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001822 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001823 II->getName()), *II);
1824 break;
1825 case Intrinsic::x86_sse_mul_ss:
1826 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001827 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001828 II->getName()), *II);
1829 break;
1830 }
1831
1832 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001833 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001834 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001835 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001836 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001837 return New;
1838 }
1839 }
1840
1841 // Output elements are undefined if both are undefined. Consider things
1842 // like undef&0. The result is known zero, not undef.
1843 UndefElts &= UndefElts2;
1844 break;
1845 }
1846 break;
1847 }
1848 }
1849 return MadeChange ? I : 0;
1850}
1851
Dan Gohman45b4e482008-05-19 22:14:15 +00001852
Chris Lattner564a7272003-08-13 19:01:45 +00001853/// AssociativeOpt - Perform an optimization on an associative operator. This
1854/// function is designed to check a chain of associative operators for a
1855/// potential to apply a certain optimization. Since the optimization may be
1856/// applicable if the expression was reassociated, this checks the chain, then
1857/// reassociates the expression as necessary to expose the optimization
1858/// opportunity. This makes use of a special Functor, which must define
1859/// 'shouldApply' and 'apply' methods.
1860///
1861template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001862static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001863 unsigned Opcode = Root.getOpcode();
1864 Value *LHS = Root.getOperand(0);
1865
1866 // Quick check, see if the immediate LHS matches...
1867 if (F.shouldApply(LHS))
1868 return F.apply(Root);
1869
1870 // Otherwise, if the LHS is not of the same opcode as the root, return.
1871 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001872 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001873 // Should we apply this transform to the RHS?
1874 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1875
1876 // If not to the RHS, check to see if we should apply to the LHS...
1877 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1878 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1879 ShouldApply = true;
1880 }
1881
1882 // If the functor wants to apply the optimization to the RHS of LHSI,
1883 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1884 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001885 // Now all of the instructions are in the current basic block, go ahead
1886 // and perform the reassociation.
1887 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1888
1889 // First move the selected RHS to the LHS of the root...
1890 Root.setOperand(0, LHSI->getOperand(1));
1891
1892 // Make what used to be the LHS of the root be the user of the root...
1893 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001894 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001895 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001896 return 0;
1897 }
Chris Lattner65725312004-04-16 18:08:07 +00001898 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001899 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001900 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001901 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001902 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001903
1904 // Now propagate the ExtraOperand down the chain of instructions until we
1905 // get to LHSI.
1906 while (TmpLHSI != LHSI) {
1907 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001908 // Move the instruction to immediately before the chain we are
1909 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001910 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001911 ARI = NextLHSI;
1912
Chris Lattner564a7272003-08-13 19:01:45 +00001913 Value *NextOp = NextLHSI->getOperand(1);
1914 NextLHSI->setOperand(1, ExtraOperand);
1915 TmpLHSI = NextLHSI;
1916 ExtraOperand = NextOp;
1917 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001918
Chris Lattner564a7272003-08-13 19:01:45 +00001919 // Now that the instructions are reassociated, have the functor perform
1920 // the transformation...
1921 return F.apply(Root);
1922 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001923
Chris Lattner564a7272003-08-13 19:01:45 +00001924 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1925 }
1926 return 0;
1927}
1928
Dan Gohman844731a2008-05-13 00:00:25 +00001929namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001930
Nick Lewycky02d639f2008-05-23 04:34:58 +00001931// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001932struct AddRHS {
1933 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001934 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001935 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1936 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001937 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001938 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001939 }
1940};
1941
1942// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1943// iff C1&C2 == 0
1944struct AddMaskingAnd {
1945 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001946 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001947 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001948 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001949 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001950 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001951 }
1952 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001953 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001954 }
1955};
1956
Dan Gohman844731a2008-05-13 00:00:25 +00001957}
1958
Chris Lattner6e7ba452005-01-01 16:22:27 +00001959static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001960 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001961 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001962 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001963
Chris Lattner2eefe512004-04-09 19:05:30 +00001964 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001965 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1966 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001967
Chris Lattner2eefe512004-04-09 19:05:30 +00001968 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1969 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001970 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1971 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001972 }
1973
1974 Value *Op0 = SO, *Op1 = ConstOperand;
1975 if (!ConstIsRHS)
1976 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001977
Chris Lattner6e7ba452005-01-01 16:22:27 +00001978 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001979 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1980 SO->getName()+".op");
1981 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1982 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1983 SO->getName()+".cmp");
1984 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1985 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1986 SO->getName()+".cmp");
1987 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001988}
1989
1990// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1991// constant as the other operand, try to fold the binary operator into the
1992// select arguments. This also works for Cast instructions, which obviously do
1993// not have a second operand.
1994static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1995 InstCombiner *IC) {
1996 // Don't modify shared select instructions
1997 if (!SI->hasOneUse()) return 0;
1998 Value *TV = SI->getOperand(1);
1999 Value *FV = SI->getOperand(2);
2000
2001 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002002 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00002003 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002004
Chris Lattner6e7ba452005-01-01 16:22:27 +00002005 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2006 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2007
Gabor Greif051a9502008-04-06 20:25:17 +00002008 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2009 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002010 }
2011 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002012}
2013
Chris Lattner4e998b22004-09-29 05:07:12 +00002014
Chris Lattner5d1704d2009-09-27 19:57:57 +00002015/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2016/// has a PHI node as operand #0, see if we can fold the instruction into the
2017/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002018///
2019/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2020/// that would normally be unprofitable because they strongly encourage jump
2021/// threading.
2022Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2023 bool AllowAggressive) {
2024 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002025 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002026 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002027 if (NumPHIValues == 0 ||
2028 // We normally only transform phis with a single use, unless we're trying
2029 // hard to make jump threading happen.
2030 (!PN->hasOneUse() && !AllowAggressive))
2031 return 0;
2032
2033
Chris Lattner5d1704d2009-09-27 19:57:57 +00002034 // Check to see if all of the operands of the PHI are simple constants
2035 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002036 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2037 // bail out. We don't do arbitrary constant expressions here because moving
2038 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002039 BasicBlock *NonConstBB = 0;
2040 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002041 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2042 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002043 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002044 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002045 NonConstBB = PN->getIncomingBlock(i);
2046
2047 // If the incoming non-constant value is in I's block, we have an infinite
2048 // loop.
2049 if (NonConstBB == I.getParent())
2050 return 0;
2051 }
2052
2053 // If there is exactly one non-constant value, we can insert a copy of the
2054 // operation in that block. However, if this is a critical edge, we would be
2055 // inserting the computation one some other paths (e.g. inside a loop). Only
2056 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002057 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002058 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2059 if (!BI || !BI->isUnconditional()) return 0;
2060 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002061
2062 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002063 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002064 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002065 InsertNewInstBefore(NewPN, *PN);
2066 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002067
2068 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002069 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2070 // We only currently try to fold the condition of a select when it is a phi,
2071 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002072 Value *TrueV = SI->getTrueValue();
2073 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002074 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002075 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002076 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002077 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2078 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002079 Value *InV = 0;
2080 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002081 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002082 } else {
2083 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002084 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2085 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002086 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002087 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002088 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002089 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002090 }
2091 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002092 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002093 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002094 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002095 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002096 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002097 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002098 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002099 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002100 } else {
2101 assert(PN->getIncomingBlock(i) == NonConstBB);
2102 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002103 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002104 PN->getIncomingValue(i), C, "phitmp",
2105 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002106 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002107 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002108 CI->getPredicate(),
2109 PN->getIncomingValue(i), C, "phitmp",
2110 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002111 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002112 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002113
2114 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002115 }
2116 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002117 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002118 } else {
2119 CastInst *CI = cast<CastInst>(&I);
2120 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002121 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002122 Value *InV;
2123 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002124 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002125 } else {
2126 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002127 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002128 I.getType(), "phitmp",
2129 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002130 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002131 }
2132 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002133 }
2134 }
2135 return ReplaceInstUsesWith(I, NewPN);
2136}
2137
Chris Lattner2454a2e2008-01-29 06:52:45 +00002138
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002139/// WillNotOverflowSignedAdd - Return true if we can prove that:
2140/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2141/// This basically requires proving that the add in the original type would not
2142/// overflow to change the sign bit or have a carry out.
2143bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2144 // There are different heuristics we can use for this. Here are some simple
2145 // ones.
2146
2147 // Add has the property that adding any two 2's complement numbers can only
2148 // have one carry bit which can change a sign. As such, if LHS and RHS each
2149 // have at least two sign bits, we know that the addition of the two values will
2150 // sign extend fine.
2151 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2152 return true;
2153
2154
2155 // If one of the operands only has one non-zero bit, and if the other operand
2156 // has a known-zero bit in a more significant place than it (not including the
2157 // sign bit) the ripple may go up to and fill the zero, but won't change the
2158 // sign. For example, (X & ~4) + 1.
2159
2160 // TODO: Implement.
2161
2162 return false;
2163}
2164
Chris Lattner2454a2e2008-01-29 06:52:45 +00002165
Chris Lattner7e708292002-06-25 16:13:24 +00002166Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002167 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002168 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002169
Chris Lattner66331a42004-04-10 22:01:55 +00002170 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002171 // X + undef -> undef
2172 if (isa<UndefValue>(RHS))
2173 return ReplaceInstUsesWith(I, RHS);
2174
Chris Lattner66331a42004-04-10 22:01:55 +00002175 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002176 if (RHSC->isNullValue())
2177 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002178
Chris Lattner66331a42004-04-10 22:01:55 +00002179 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002180 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002181 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002182 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002183 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002184 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002185
2186 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2187 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002188 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002189 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002190
Eli Friedman709b33d2009-07-13 22:27:52 +00002191 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002192 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002193 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002194 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002195 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002196
2197 if (isa<PHINode>(LHS))
2198 if (Instruction *NV = FoldOpIntoPhi(I))
2199 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002200
Chris Lattner4f637d42006-01-06 17:59:59 +00002201 ConstantInt *XorRHS = 0;
2202 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002203 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002204 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002205 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002206 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002207
Zhou Sheng4351c642007-04-02 08:20:41 +00002208 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002209 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2210 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002211 do {
2212 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002213 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2214 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002215 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2216 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002217 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002218 if (!MaskedValueIsZero(XorLHS,
2219 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002220 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002221 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002222 }
2223 }
2224 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002225 C0080Val = APIntOps::lshr(C0080Val, Size);
2226 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2227 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002228
Reid Spencer35c38852007-03-28 01:36:16 +00002229 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002230 // with funny bit widths then this switch statement should be removed. It
2231 // is just here to get the size of the "middle" type back up to something
2232 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002233 const Type *MiddleType = 0;
2234 switch (Size) {
2235 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002236 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2237 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2238 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002239 }
2240 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002241 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002242 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002243 }
2244 }
Chris Lattner66331a42004-04-10 22:01:55 +00002245 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002246
Owen Anderson1d0be152009-08-13 21:58:54 +00002247 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002248 return BinaryOperator::CreateXor(LHS, RHS);
2249
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002250 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002251 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002252 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002253 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002254
2255 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2256 if (RHSI->getOpcode() == Instruction::Sub)
2257 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2258 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2259 }
2260 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2261 if (LHSI->getOpcode() == Instruction::Sub)
2262 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2263 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2264 }
Robert Bocchino71698282004-07-27 21:02:21 +00002265 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002266
Chris Lattner5c4afb92002-05-08 22:46:53 +00002267 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002268 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002269 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002270 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002271 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002272 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002273 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002274 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002275 }
2276
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002277 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002278 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002279
2280 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002281 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002282 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002283 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002284
Misha Brukmanfd939082005-04-21 23:48:37 +00002285
Chris Lattner50af16a2004-11-13 19:50:12 +00002286 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002287 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002288 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002289 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002290
2291 // X*C1 + X*C2 --> X * (C1+C2)
2292 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002293 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002294 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002295 }
2296
2297 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002298 if (dyn_castFoldableMul(RHS, C2) == LHS)
2299 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002300
Chris Lattnere617c9e2007-01-05 02:17:46 +00002301 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002302 if (dyn_castNotVal(LHS) == RHS ||
2303 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002304 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002305
Chris Lattnerad3448c2003-02-18 19:57:07 +00002306
Chris Lattner564a7272003-08-13 19:01:45 +00002307 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002308 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2309 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002310 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002311
2312 // A+B --> A|B iff A and B have no bits set in common.
2313 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2314 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2315 APInt LHSKnownOne(IT->getBitWidth(), 0);
2316 APInt LHSKnownZero(IT->getBitWidth(), 0);
2317 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2318 if (LHSKnownZero != 0) {
2319 APInt RHSKnownOne(IT->getBitWidth(), 0);
2320 APInt RHSKnownZero(IT->getBitWidth(), 0);
2321 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2322
2323 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002324 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002325 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002326 }
2327 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002328
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002329 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002330 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002331 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002332 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2333 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002334 if (W != Y) {
2335 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002336 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002337 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002338 std::swap(W, X);
2339 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002340 std::swap(Y, Z);
2341 std::swap(W, X);
2342 }
2343 }
2344
2345 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002346 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002347 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002348 }
2349 }
2350 }
2351
Chris Lattner6b032052003-10-02 15:11:26 +00002352 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002353 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002354 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002355 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002356
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002357 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002358 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002359 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002360 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002361 if (Anded == CRHS) {
2362 // See if all bits from the first bit set in the Add RHS up are included
2363 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002364 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002365
2366 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002367 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002368
2369 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002370 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002371
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002372 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2373 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002374 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002375 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002376 }
2377 }
2378 }
2379
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002380 // Try to fold constant add into select arguments.
2381 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002382 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002383 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002384 }
2385
Chris Lattner42790482007-12-20 01:56:58 +00002386 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002387 {
2388 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002389 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002390 if (!SI) {
2391 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002392 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002393 }
Chris Lattner42790482007-12-20 01:56:58 +00002394 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002395 Value *TV = SI->getTrueValue();
2396 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002397 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002398
2399 // Can we fold the add into the argument of the select?
2400 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002401 if (match(FV, m_Zero()) &&
2402 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002403 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002404 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002405 if (match(TV, m_Zero()) &&
2406 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002407 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002408 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002409 }
2410 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002411
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002412 // Check for (add (sext x), y), see if we can merge this into an
2413 // integer add followed by a sext.
2414 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2415 // (add (sext x), cst) --> (sext (add x, cst'))
2416 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2417 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002418 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002419 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002420 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002421 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2422 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002423 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2424 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002425 return new SExtInst(NewAdd, I.getType());
2426 }
2427 }
2428
2429 // (add (sext x), (sext y)) --> (sext (add int x, y))
2430 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2431 // Only do this if x/y have the same type, if at last one of them has a
2432 // single use (so we don't increase the number of sexts), and if the
2433 // integer add will not overflow.
2434 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2435 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2436 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2437 RHSConv->getOperand(0))) {
2438 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002439 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2440 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002441 return new SExtInst(NewAdd, I.getType());
2442 }
2443 }
2444 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002445
2446 return Changed ? &I : 0;
2447}
2448
2449Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2450 bool Changed = SimplifyCommutative(I);
2451 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2452
2453 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2454 // X + 0 --> X
2455 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002456 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002457 (I.getType())->getValueAPF()))
2458 return ReplaceInstUsesWith(I, LHS);
2459 }
2460
2461 if (isa<PHINode>(LHS))
2462 if (Instruction *NV = FoldOpIntoPhi(I))
2463 return NV;
2464 }
2465
2466 // -A + B --> B - A
2467 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002468 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002469 return BinaryOperator::CreateFSub(RHS, LHSV);
2470
2471 // A + -B --> A - B
2472 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002473 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002474 return BinaryOperator::CreateFSub(LHS, V);
2475
2476 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2477 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2478 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2479 return ReplaceInstUsesWith(I, LHS);
2480
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002481 // Check for (add double (sitofp x), y), see if we can merge this into an
2482 // integer add followed by a promotion.
2483 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2484 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2485 // ... if the constant fits in the integer value. This is useful for things
2486 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2487 // requires a constant pool load, and generally allows the add to be better
2488 // instcombined.
2489 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2490 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002491 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002492 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002493 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002494 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2495 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002496 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2497 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002498 return new SIToFPInst(NewAdd, I.getType());
2499 }
2500 }
2501
2502 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2503 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2504 // Only do this if x/y have the same type, if at last one of them has a
2505 // single use (so we don't increase the number of int->fp conversions),
2506 // and if the integer add will not overflow.
2507 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2508 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2509 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2510 RHSConv->getOperand(0))) {
2511 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002512 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2513 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002514 return new SIToFPInst(NewAdd, I.getType());
2515 }
2516 }
2517 }
2518
Chris Lattner7e708292002-06-25 16:13:24 +00002519 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002520}
2521
Chris Lattner7e708292002-06-25 16:13:24 +00002522Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002523 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002524
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002525 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002526 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002527
Chris Lattner233f7dc2002-08-12 21:17:25 +00002528 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002529 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002530 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002531
Chris Lattnere87597f2004-10-16 18:11:37 +00002532 if (isa<UndefValue>(Op0))
2533 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2534 if (isa<UndefValue>(Op1))
2535 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2536
Chris Lattnerd65460f2003-11-05 01:06:05 +00002537 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2538 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002539 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002540 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002541
Chris Lattnerd65460f2003-11-05 01:06:05 +00002542 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002543 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002544 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002545 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002546
Chris Lattner76b7a062007-01-15 07:02:54 +00002547 // -(X >>u 31) -> (X >>s 31)
2548 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002549 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002550 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002551 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002552 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002553 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002554 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002555 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002556 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002557 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002558 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002559 }
2560 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002561 }
2562 else if (SI->getOpcode() == Instruction::AShr) {
2563 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2564 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002565 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002566 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002567 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002568 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002569 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002570 }
2571 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002572 }
2573 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002574 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002575
2576 // Try to fold constant sub into select arguments.
2577 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002578 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002579 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002580
2581 // C - zext(bool) -> bool ? C - 1 : C
2582 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002583 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002584 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002585 }
2586
Owen Anderson1d0be152009-08-13 21:58:54 +00002587 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002588 return BinaryOperator::CreateXor(Op0, Op1);
2589
Chris Lattner43d84d62005-04-07 16:15:25 +00002590 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002591 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002592 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002593 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002594 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002595 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002596 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002597 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002598 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2599 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2600 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002601 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002602 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002603 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002604 }
2605
Chris Lattnerfd059242003-10-15 16:48:29 +00002606 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002607 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2608 // is not used by anyone else...
2609 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002610 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002611 // Swap the two operands of the subexpr...
2612 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2613 Op1I->setOperand(0, IIOp1);
2614 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002615
Chris Lattnera2881962003-02-18 19:28:33 +00002616 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002617 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002618 }
2619
2620 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2621 //
2622 if (Op1I->getOpcode() == Instruction::And &&
2623 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2624 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2625
Chris Lattner74381062009-08-30 07:44:24 +00002626 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002627 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002628 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002629
Reid Spencerac5209e2006-10-16 23:08:08 +00002630 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002631 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002632 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002633 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002634 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002635 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002636 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002637
Chris Lattnerad3448c2003-02-18 19:57:07 +00002638 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002639 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002640 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002641 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002642 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002643 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002644 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002645 }
Chris Lattner40371712002-05-09 01:29:19 +00002646 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002647 }
Chris Lattnera2881962003-02-18 19:28:33 +00002648
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002649 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2650 if (Op0I->getOpcode() == Instruction::Add) {
2651 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2652 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2653 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2654 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2655 } else if (Op0I->getOpcode() == Instruction::Sub) {
2656 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002657 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002658 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002659 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002660 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002661
Chris Lattner50af16a2004-11-13 19:50:12 +00002662 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002663 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002664 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002665 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002666
Chris Lattner50af16a2004-11-13 19:50:12 +00002667 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002668 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002669 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002670 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002671 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002672}
2673
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002674Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2675 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2676
2677 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002678 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002679 return BinaryOperator::CreateFAdd(Op0, V);
2680
2681 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2682 if (Op1I->getOpcode() == Instruction::FAdd) {
2683 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002684 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002685 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002686 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002687 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002688 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002689 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002690 }
2691
2692 return 0;
2693}
2694
Chris Lattnera0141b92007-07-15 20:42:37 +00002695/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2696/// comparison only checks the sign bit. If it only checks the sign bit, set
2697/// TrueIfSigned if the result of the comparison is true when the input value is
2698/// signed.
2699static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2700 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002701 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002702 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2703 TrueIfSigned = true;
2704 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002705 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2706 TrueIfSigned = true;
2707 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002708 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2709 TrueIfSigned = false;
2710 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002711 case ICmpInst::ICMP_UGT:
2712 // True if LHS u> RHS and RHS == high-bit-mask - 1
2713 TrueIfSigned = true;
2714 return RHS->getValue() ==
2715 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2716 case ICmpInst::ICMP_UGE:
2717 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2718 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002719 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002720 default:
2721 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002722 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002723}
2724
Chris Lattner7e708292002-06-25 16:13:24 +00002725Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002726 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002727 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002728
Chris Lattnera2498472009-10-11 21:36:10 +00002729 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002730 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002731
Chris Lattner8af304a2009-10-11 07:53:15 +00002732 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002733 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2734 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002735
2736 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002737 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002738 if (SI->getOpcode() == Instruction::Shl)
2739 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002740 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002741 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002742
Zhou Sheng843f07672007-04-19 05:39:12 +00002743 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002744 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002745 if (CI->equalsInt(1)) // X * 1 == X
2746 return ReplaceInstUsesWith(I, Op0);
2747 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002748 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002749
Zhou Sheng97b52c22007-03-29 01:57:21 +00002750 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002751 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002752 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002753 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002754 }
Chris Lattnera2498472009-10-11 21:36:10 +00002755 } else if (isa<VectorType>(Op1C->getType())) {
2756 if (Op1C->isNullValue())
2757 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002758
Chris Lattnera2498472009-10-11 21:36:10 +00002759 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002760 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002761 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002762
2763 // As above, vector X*splat(1.0) -> X in all defined cases.
2764 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002765 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2766 if (CI->equalsInt(1))
2767 return ReplaceInstUsesWith(I, Op0);
2768 }
2769 }
Chris Lattnera2881962003-02-18 19:28:33 +00002770 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002771
2772 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2773 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002774 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002775 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00002776 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2777 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002778 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002779
2780 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002781
2782 // Try to fold constant mul into select arguments.
2783 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002784 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002785 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002786
2787 if (isa<PHINode>(Op0))
2788 if (Instruction *NV = FoldOpIntoPhi(I))
2789 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002790 }
2791
Dan Gohman186a6362009-08-12 16:04:34 +00002792 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002793 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002794 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002795
Nick Lewycky0c730792008-11-21 07:33:58 +00002796 // (X / Y) * Y = X - (X % Y)
2797 // (X / Y) * -Y = (X % Y) - X
2798 {
Chris Lattnera2498472009-10-11 21:36:10 +00002799 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00002800 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2801 if (!BO ||
2802 (BO->getOpcode() != Instruction::UDiv &&
2803 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00002804 Op1C = Op0;
2805 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002806 }
Chris Lattnera2498472009-10-11 21:36:10 +00002807 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00002808 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002809 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00002810 (BO->getOpcode() == Instruction::UDiv ||
2811 BO->getOpcode() == Instruction::SDiv)) {
2812 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2813
Dan Gohmanfa94b942009-08-12 16:33:09 +00002814 // If the division is exact, X % Y is zero.
2815 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2816 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00002817 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00002818 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00002819 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00002820 }
2821
Chris Lattner74381062009-08-30 07:44:24 +00002822 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002823 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002824 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002825 else
Chris Lattner74381062009-08-30 07:44:24 +00002826 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002827 Rem->takeName(BO);
2828
Chris Lattnera2498472009-10-11 21:36:10 +00002829 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00002830 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002831 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002832 }
2833 }
2834
Chris Lattner8af304a2009-10-11 07:53:15 +00002835 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00002836 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00002837 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002838
Chris Lattner8af304a2009-10-11 07:53:15 +00002839 // X*(1 << Y) --> X << Y
2840 // (1 << Y)*X --> X << Y
2841 {
2842 Value *Y;
2843 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00002844 return BinaryOperator::CreateShl(Op1, Y);
2845 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00002846 return BinaryOperator::CreateShl(Op0, Y);
2847 }
2848
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002849 // If one of the operands of the multiply is a cast from a boolean value, then
2850 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00002851 // X * Y (where Y is 0 or 1) -> X & (0-Y)
2852 if (!isa<VectorType>(I.getType())) {
2853 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00002854 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00002855
Chris Lattnerd2c58362009-10-11 21:29:45 +00002856 Value *BoolCast = 0, *OtherOp = 0;
2857 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00002858 BoolCast = Op0, OtherOp = Op1;
2859 else if (MaskedValueIsZero(Op1, Negative2))
2860 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00002861
Chris Lattner0036e3a2009-10-11 21:22:21 +00002862 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00002863 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2864 BoolCast, "tmp");
2865 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002866 }
2867 }
2868
Chris Lattner7e708292002-06-25 16:13:24 +00002869 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002870}
2871
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002872Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2873 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002874 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002875
2876 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00002877 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2878 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002879 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2880 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2881 if (Op1F->isExactlyValue(1.0))
2882 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00002883 } else if (isa<VectorType>(Op1C->getType())) {
2884 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002885 // As above, vector X*splat(1.0) -> X in all defined cases.
2886 if (Constant *Splat = Op1V->getSplatValue()) {
2887 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2888 if (F->isExactlyValue(1.0))
2889 return ReplaceInstUsesWith(I, Op0);
2890 }
2891 }
2892 }
2893
2894 // Try to fold constant mul into select arguments.
2895 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2896 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2897 return R;
2898
2899 if (isa<PHINode>(Op0))
2900 if (Instruction *NV = FoldOpIntoPhi(I))
2901 return NV;
2902 }
2903
Dan Gohman186a6362009-08-12 16:04:34 +00002904 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002905 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002906 return BinaryOperator::CreateFMul(Op0v, Op1v);
2907
2908 return Changed ? &I : 0;
2909}
2910
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002911/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2912/// instruction.
2913bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2914 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2915
2916 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2917 int NonNullOperand = -1;
2918 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2919 if (ST->isNullValue())
2920 NonNullOperand = 2;
2921 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2922 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2923 if (ST->isNullValue())
2924 NonNullOperand = 1;
2925
2926 if (NonNullOperand == -1)
2927 return false;
2928
2929 Value *SelectCond = SI->getOperand(0);
2930
2931 // Change the div/rem to use 'Y' instead of the select.
2932 I.setOperand(1, SI->getOperand(NonNullOperand));
2933
2934 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2935 // problem. However, the select, or the condition of the select may have
2936 // multiple uses. Based on our knowledge that the operand must be non-zero,
2937 // propagate the known value for the select into other uses of it, and
2938 // propagate a known value of the condition into its other users.
2939
2940 // If the select and condition only have a single use, don't bother with this,
2941 // early exit.
2942 if (SI->use_empty() && SelectCond->hasOneUse())
2943 return true;
2944
2945 // Scan the current block backward, looking for other uses of SI.
2946 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2947
2948 while (BBI != BBFront) {
2949 --BBI;
2950 // If we found a call to a function, we can't assume it will return, so
2951 // information from below it cannot be propagated above it.
2952 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2953 break;
2954
2955 // Replace uses of the select or its condition with the known values.
2956 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2957 I != E; ++I) {
2958 if (*I == SI) {
2959 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002960 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002961 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002962 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2963 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002964 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002965 }
2966 }
2967
2968 // If we past the instruction, quit looking for it.
2969 if (&*BBI == SI)
2970 SI = 0;
2971 if (&*BBI == SelectCond)
2972 SelectCond = 0;
2973
2974 // If we ran out of things to eliminate, break out of the loop.
2975 if (SelectCond == 0 && SI == 0)
2976 break;
2977
2978 }
2979 return true;
2980}
2981
2982
Reid Spencer1628cec2006-10-26 06:15:43 +00002983/// This function implements the transforms on div instructions that work
2984/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2985/// used by the visitors to those instructions.
2986/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002987Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002988 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002989
Chris Lattner50b2ca42008-02-19 06:12:18 +00002990 // undef / X -> 0 for integer.
2991 // undef / X -> undef for FP (the undef could be a snan).
2992 if (isa<UndefValue>(Op0)) {
2993 if (Op0->getType()->isFPOrFPVector())
2994 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002995 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002996 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002997
2998 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002999 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003000 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003001
Reid Spencer1628cec2006-10-26 06:15:43 +00003002 return 0;
3003}
Misha Brukmanfd939082005-04-21 23:48:37 +00003004
Reid Spencer1628cec2006-10-26 06:15:43 +00003005/// This function implements the transforms common to both integer division
3006/// instructions (udiv and sdiv). It is called by the visitors to those integer
3007/// division instructions.
3008/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003009Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003010 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3011
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003012 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003013 if (Op0 == Op1) {
3014 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003015 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003016 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003017 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003018 }
3019
Owen Andersoneed707b2009-07-24 23:12:02 +00003020 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003021 return ReplaceInstUsesWith(I, CI);
3022 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003023
Reid Spencer1628cec2006-10-26 06:15:43 +00003024 if (Instruction *Common = commonDivTransforms(I))
3025 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003026
3027 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3028 // This does not apply for fdiv.
3029 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3030 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003031
3032 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3033 // div X, 1 == X
3034 if (RHS->equalsInt(1))
3035 return ReplaceInstUsesWith(I, Op0);
3036
3037 // (X / C1) / C2 -> X / (C1*C2)
3038 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3039 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3040 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003041 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003042 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003043 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003044 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003045 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003046 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003047 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003048
Reid Spencerbca0e382007-03-23 20:05:17 +00003049 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003050 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3051 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3052 return R;
3053 if (isa<PHINode>(Op0))
3054 if (Instruction *NV = FoldOpIntoPhi(I))
3055 return NV;
3056 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003057 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003058
Chris Lattnera2881962003-02-18 19:28:33 +00003059 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003060 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003061 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003062 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003063
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003064 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003065 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003066 return ReplaceInstUsesWith(I, Op0);
3067
Nick Lewycky895f0852008-11-27 20:21:08 +00003068 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3069 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3070 // div X, 1 == X
3071 if (X->isOne())
3072 return ReplaceInstUsesWith(I, Op0);
3073 }
3074
Reid Spencer1628cec2006-10-26 06:15:43 +00003075 return 0;
3076}
3077
3078Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3079 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3080
3081 // Handle the integer div common cases
3082 if (Instruction *Common = commonIDivTransforms(I))
3083 return Common;
3084
Reid Spencer1628cec2006-10-26 06:15:43 +00003085 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003086 // X udiv C^2 -> X >> C
3087 // Check to see if this is an unsigned division with an exact power of 2,
3088 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003089 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003090 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003091 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003092
3093 // X udiv C, where C >= signbit
3094 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003095 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003096 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003097 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003098 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003099 }
3100
3101 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003102 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003103 if (RHSI->getOpcode() == Instruction::Shl &&
3104 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003105 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003106 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003107 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003108 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003109 if (uint32_t C2 = C1.logBase2())
3110 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003111 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003112 }
3113 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003114 }
3115
Reid Spencer1628cec2006-10-26 06:15:43 +00003116 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3117 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003118 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003119 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003120 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003121 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003122 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003123 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003124 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003125 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003126 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003127 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003128
3129 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003130 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003131 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003132
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003133 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003134 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003135 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003136 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003137 return 0;
3138}
3139
Reid Spencer1628cec2006-10-26 06:15:43 +00003140Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3141 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3142
3143 // Handle the integer div common cases
3144 if (Instruction *Common = commonIDivTransforms(I))
3145 return Common;
3146
3147 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3148 // sdiv X, -1 == -X
3149 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003150 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003151
Dan Gohmanfa94b942009-08-12 16:33:09 +00003152 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003153 if (cast<SDivOperator>(&I)->isExact() &&
3154 RHS->getValue().isNonNegative() &&
3155 RHS->getValue().isPowerOf2()) {
3156 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3157 RHS->getValue().exactLogBase2());
3158 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3159 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003160
3161 // -X/C --> X/-C provided the negation doesn't overflow.
3162 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3163 if (isa<Constant>(Sub->getOperand(0)) &&
3164 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003165 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003166 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3167 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003168 }
3169
3170 // If the sign bits of both operands are zero (i.e. we can prove they are
3171 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003172 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003173 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003174 if (MaskedValueIsZero(Op0, Mask)) {
3175 if (MaskedValueIsZero(Op1, Mask)) {
3176 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3177 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3178 }
3179 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003180 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003181 ShiftedInt->getValue().isPowerOf2()) {
3182 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3183 // Safe because the only negative value (1 << Y) can take on is
3184 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3185 // the sign bit set.
3186 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3187 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003188 }
Eli Friedman8be17392009-07-18 09:53:21 +00003189 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003190
3191 return 0;
3192}
3193
3194Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3195 return commonDivTransforms(I);
3196}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003197
Reid Spencer0a783f72006-11-02 01:53:59 +00003198/// This function implements the transforms on rem instructions that work
3199/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3200/// is used by the visitors to those instructions.
3201/// @brief Transforms common to all three rem instructions
3202Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003203 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003204
Chris Lattner50b2ca42008-02-19 06:12:18 +00003205 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3206 if (I.getType()->isFPOrFPVector())
3207 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003208 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003209 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003210 if (isa<UndefValue>(Op1))
3211 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003212
3213 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003214 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3215 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003216
Reid Spencer0a783f72006-11-02 01:53:59 +00003217 return 0;
3218}
3219
3220/// This function implements the transforms common to both integer remainder
3221/// instructions (urem and srem). It is called by the visitors to those integer
3222/// remainder instructions.
3223/// @brief Common integer remainder transforms
3224Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3225 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3226
3227 if (Instruction *common = commonRemTransforms(I))
3228 return common;
3229
Dale Johannesened6af242009-01-21 00:35:19 +00003230 // 0 % X == 0 for integer, we don't need to preserve faults!
3231 if (Constant *LHS = dyn_cast<Constant>(Op0))
3232 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003233 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003234
Chris Lattner857e8cd2004-12-12 21:48:58 +00003235 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003236 // X % 0 == undef, we don't need to preserve faults!
3237 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003238 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003239
Chris Lattnera2881962003-02-18 19:28:33 +00003240 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003241 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003242
Chris Lattner97943922006-02-28 05:49:21 +00003243 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3244 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3245 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3246 return R;
3247 } else if (isa<PHINode>(Op0I)) {
3248 if (Instruction *NV = FoldOpIntoPhi(I))
3249 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003250 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003251
3252 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003253 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003254 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003255 }
Chris Lattnera2881962003-02-18 19:28:33 +00003256 }
3257
Reid Spencer0a783f72006-11-02 01:53:59 +00003258 return 0;
3259}
3260
3261Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3262 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3263
3264 if (Instruction *common = commonIRemTransforms(I))
3265 return common;
3266
3267 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3268 // X urem C^2 -> X and C
3269 // Check to see if this is an unsigned remainder with an exact power of 2,
3270 // if so, convert to a bitwise and.
3271 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003272 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003273 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003274 }
3275
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003276 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003277 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3278 if (RHSI->getOpcode() == Instruction::Shl &&
3279 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003280 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003281 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003282 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003283 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003284 }
3285 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003286 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003287
Reid Spencer0a783f72006-11-02 01:53:59 +00003288 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3289 // where C1&C2 are powers of two.
3290 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3291 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3292 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3293 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003294 if ((STO->getValue().isPowerOf2()) &&
3295 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003296 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3297 SI->getName()+".t");
3298 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3299 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003300 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003301 }
3302 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003303 }
3304
Chris Lattner3f5b8772002-05-06 16:14:14 +00003305 return 0;
3306}
3307
Reid Spencer0a783f72006-11-02 01:53:59 +00003308Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3309 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3310
Dan Gohmancff55092007-11-05 23:16:33 +00003311 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003312 if (Instruction *Common = commonIRemTransforms(I))
3313 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003314
Dan Gohman186a6362009-08-12 16:04:34 +00003315 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003316 if (!isa<Constant>(RHSNeg) ||
3317 (isa<ConstantInt>(RHSNeg) &&
3318 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003319 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003320 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003321 I.setOperand(1, RHSNeg);
3322 return &I;
3323 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003324
Dan Gohmancff55092007-11-05 23:16:33 +00003325 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003326 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003327 if (I.getType()->isInteger()) {
3328 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3329 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3330 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003331 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003332 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003333 }
3334
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003335 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003336 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3337 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003338
Nick Lewycky9dce8732008-12-20 16:48:00 +00003339 bool hasNegative = false;
3340 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3341 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3342 if (RHS->getValue().isNegative())
3343 hasNegative = true;
3344
3345 if (hasNegative) {
3346 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003347 for (unsigned i = 0; i != VWidth; ++i) {
3348 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3349 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003350 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003351 else
3352 Elts[i] = RHS;
3353 }
3354 }
3355
Owen Andersonaf7ec972009-07-28 21:19:26 +00003356 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003357 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003358 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003359 I.setOperand(1, NewRHSV);
3360 return &I;
3361 }
3362 }
3363 }
3364
Reid Spencer0a783f72006-11-02 01:53:59 +00003365 return 0;
3366}
3367
3368Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003369 return commonRemTransforms(I);
3370}
3371
Chris Lattner457dd822004-06-09 07:59:58 +00003372// isOneBitSet - Return true if there is exactly one bit set in the specified
3373// constant.
3374static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003375 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003376}
3377
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003378// isHighOnes - Return true if the constant is of the form 1+0+.
3379// This is the same as lowones(~X).
3380static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003381 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003382}
3383
Reid Spencere4d87aa2006-12-23 06:05:41 +00003384/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003385/// are carefully arranged to allow folding of expressions such as:
3386///
3387/// (A < B) | (A > B) --> (A != B)
3388///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003389/// Note that this is only valid if the first and second predicates have the
3390/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003391///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003392/// Three bits are used to represent the condition, as follows:
3393/// 0 A > B
3394/// 1 A == B
3395/// 2 A < B
3396///
3397/// <=> Value Definition
3398/// 000 0 Always false
3399/// 001 1 A > B
3400/// 010 2 A == B
3401/// 011 3 A >= B
3402/// 100 4 A < B
3403/// 101 5 A != B
3404/// 110 6 A <= B
3405/// 111 7 Always true
3406///
3407static unsigned getICmpCode(const ICmpInst *ICI) {
3408 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003409 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003410 case ICmpInst::ICMP_UGT: return 1; // 001
3411 case ICmpInst::ICMP_SGT: return 1; // 001
3412 case ICmpInst::ICMP_EQ: return 2; // 010
3413 case ICmpInst::ICMP_UGE: return 3; // 011
3414 case ICmpInst::ICMP_SGE: return 3; // 011
3415 case ICmpInst::ICMP_ULT: return 4; // 100
3416 case ICmpInst::ICMP_SLT: return 4; // 100
3417 case ICmpInst::ICMP_NE: return 5; // 101
3418 case ICmpInst::ICMP_ULE: return 6; // 110
3419 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003420 // True -> 7
3421 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003422 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003423 return 0;
3424 }
3425}
3426
Evan Cheng8db90722008-10-14 17:15:11 +00003427/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3428/// predicate into a three bit mask. It also returns whether it is an ordered
3429/// predicate by reference.
3430static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3431 isOrdered = false;
3432 switch (CC) {
3433 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3434 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003435 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3436 case FCmpInst::FCMP_UGT: return 1; // 001
3437 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3438 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003439 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3440 case FCmpInst::FCMP_UGE: return 3; // 011
3441 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3442 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003443 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3444 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003445 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3446 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003447 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003448 default:
3449 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003450 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003451 return 0;
3452 }
3453}
3454
Reid Spencere4d87aa2006-12-23 06:05:41 +00003455/// getICmpValue - This is the complement of getICmpCode, which turns an
3456/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003457/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003458/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003459static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003460 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003461 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003462 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003463 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003464 case 1:
3465 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003466 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003467 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003468 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3469 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003470 case 3:
3471 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003472 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003473 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003474 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003475 case 4:
3476 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003477 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003478 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003479 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3480 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003481 case 6:
3482 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003483 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003484 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003485 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003486 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003487 }
3488}
3489
Evan Cheng8db90722008-10-14 17:15:11 +00003490/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3491/// opcode and two operands into either a FCmp instruction. isordered is passed
3492/// in to determine which kind of predicate to use in the new fcmp instruction.
3493static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003494 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003495 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003496 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003497 case 0:
3498 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003499 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003500 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003501 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003502 case 1:
3503 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003504 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003505 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003506 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003507 case 2:
3508 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003509 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003510 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003511 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003512 case 3:
3513 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003514 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003515 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003516 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003517 case 4:
3518 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003519 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003520 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003521 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003522 case 5:
3523 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003524 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003525 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003526 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003527 case 6:
3528 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003529 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003530 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003531 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003532 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003533 }
3534}
3535
Chris Lattnerb9553d62008-11-16 04:55:20 +00003536/// PredicatesFoldable - Return true if both predicates match sign or if at
3537/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003538static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003539 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3540 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3541 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003542}
3543
3544namespace {
3545// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3546struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003547 InstCombiner &IC;
3548 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003549 ICmpInst::Predicate pred;
3550 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3551 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3552 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003553 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003554 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3555 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003556 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3557 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003558 return false;
3559 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003560 Instruction *apply(Instruction &Log) const {
3561 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3562 if (ICI->getOperand(0) != LHS) {
3563 assert(ICI->getOperand(1) == LHS);
3564 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003565 }
3566
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003567 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003568 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003569 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003570 unsigned Code;
3571 switch (Log.getOpcode()) {
3572 case Instruction::And: Code = LHSCode & RHSCode; break;
3573 case Instruction::Or: Code = LHSCode | RHSCode; break;
3574 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003575 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003576 }
3577
Nick Lewycky4a134af2009-10-25 05:20:17 +00003578 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003579 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003580 if (Instruction *I = dyn_cast<Instruction>(RV))
3581 return I;
3582 // Otherwise, it's a constant boolean value...
3583 return IC.ReplaceInstUsesWith(Log, RV);
3584 }
3585};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003586} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003587
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003588// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3589// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003590// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003591Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003592 ConstantInt *OpRHS,
3593 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003594 BinaryOperator &TheAnd) {
3595 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003596 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003597 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003598 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003599
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003600 switch (Op->getOpcode()) {
3601 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003602 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003603 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003604 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003605 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003606 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003607 }
3608 break;
3609 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003610 if (Together == AndRHS) // (X | C) & C --> C
3611 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003612
Chris Lattner6e7ba452005-01-01 16:22:27 +00003613 if (Op->hasOneUse() && Together != OpRHS) {
3614 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003615 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003616 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003617 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003618 }
3619 break;
3620 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003621 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003622 // Adding a one to a single bit bit-field should be turned into an XOR
3623 // of the bit. First thing to check is to see if this AND is with a
3624 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003625 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003626
3627 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003628 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003629 // Ok, at this point, we know that we are masking the result of the
3630 // ADD down to exactly one bit. If the constant we are adding has
3631 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003632 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003633
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003634 // Check to see if any bits below the one bit set in AndRHSV are set.
3635 if ((AddRHS & (AndRHSV-1)) == 0) {
3636 // If not, the only thing that can effect the output of the AND is
3637 // the bit specified by AndRHSV. If that bit is set, the effect of
3638 // the XOR is to toggle the bit. If it is clear, then the ADD has
3639 // no effect.
3640 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3641 TheAnd.setOperand(0, X);
3642 return &TheAnd;
3643 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003644 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003645 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003646 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003647 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003648 }
3649 }
3650 }
3651 }
3652 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003653
3654 case Instruction::Shl: {
3655 // We know that the AND will not produce any of the bits shifted in, so if
3656 // the anded constant includes them, clear them now!
3657 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003658 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003659 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003660 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003661 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003662
Zhou Sheng290bec52007-03-29 08:15:12 +00003663 if (CI->getValue() == ShlMask) {
3664 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003665 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3666 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003667 TheAnd.setOperand(1, CI);
3668 return &TheAnd;
3669 }
3670 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003671 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003672 case Instruction::LShr:
3673 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003674 // We know that the AND will not produce any of the bits shifted in, so if
3675 // the anded constant includes them, clear them now! This only applies to
3676 // unsigned shifts, because a signed shr may bring in set bits!
3677 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003678 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003679 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003680 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003681 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003682
Zhou Sheng290bec52007-03-29 08:15:12 +00003683 if (CI->getValue() == ShrMask) {
3684 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003685 return ReplaceInstUsesWith(TheAnd, Op);
3686 } else if (CI != AndRHS) {
3687 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3688 return &TheAnd;
3689 }
3690 break;
3691 }
3692 case Instruction::AShr:
3693 // Signed shr.
3694 // See if this is shifting in some sign extension, then masking it out
3695 // with an and.
3696 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003697 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003698 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003699 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003700 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003701 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003702 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003703 // Make the argument unsigned.
3704 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003705 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003706 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003707 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003708 }
3709 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003710 }
3711 return 0;
3712}
3713
Chris Lattner8b170942002-08-09 23:47:40 +00003714
Chris Lattnera96879a2004-09-29 17:40:11 +00003715/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3716/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003717/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3718/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003719/// insert new instructions.
3720Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003721 bool isSigned, bool Inside,
3722 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003723 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003724 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003725 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003726
Chris Lattnera96879a2004-09-29 17:40:11 +00003727 if (Inside) {
3728 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003729 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003730
Reid Spencere4d87aa2006-12-23 06:05:41 +00003731 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003732 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003733 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003734 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003735 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003736 }
3737
3738 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003739 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003740 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003741 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003742 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003743 }
3744
3745 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003746 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003747
Reid Spencere4e40032007-03-21 23:19:50 +00003748 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003749 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003750 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003751 ICmpInst::Predicate pred = (isSigned ?
3752 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003753 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003754 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003755
Reid Spencere4e40032007-03-21 23:19:50 +00003756 // Emit V-Lo >u Hi-1-Lo
3757 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003758 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003759 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003760 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003761 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003762}
3763
Chris Lattner7203e152005-09-18 07:22:02 +00003764// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3765// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3766// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3767// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003768static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003769 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003770 uint32_t BitWidth = Val->getType()->getBitWidth();
3771 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003772
3773 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003774 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003775 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003776 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003777 return true;
3778}
3779
Chris Lattner7203e152005-09-18 07:22:02 +00003780/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3781/// where isSub determines whether the operator is a sub. If we can fold one of
3782/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003783///
3784/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3785/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3786/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3787///
3788/// return (A +/- B).
3789///
3790Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003791 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003792 Instruction &I) {
3793 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3794 if (!LHSI || LHSI->getNumOperands() != 2 ||
3795 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3796
3797 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3798
3799 switch (LHSI->getOpcode()) {
3800 default: return 0;
3801 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003802 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003803 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003804 if ((Mask->getValue().countLeadingZeros() +
3805 Mask->getValue().countPopulation()) ==
3806 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003807 break;
3808
3809 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3810 // part, we don't need any explicit masks to take them out of A. If that
3811 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003812 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003813 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003814 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003815 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003816 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003817 break;
3818 }
3819 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003820 return 0;
3821 case Instruction::Or:
3822 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003823 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003824 if ((Mask->getValue().countLeadingZeros() +
3825 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003826 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003827 break;
3828 return 0;
3829 }
3830
Chris Lattnerc8e77562005-09-18 04:24:45 +00003831 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003832 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3833 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003834}
3835
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003836/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3837Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3838 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003839 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003840 ConstantInt *LHSCst, *RHSCst;
3841 ICmpInst::Predicate LHSCC, RHSCC;
3842
Chris Lattnerea065fb2008-11-16 05:10:52 +00003843 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003844 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003845 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003846 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003847 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003848 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003849
3850 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3851 // where C is a power of 2
3852 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3853 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003854 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003855 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003856 }
3857
3858 // From here on, we only handle:
3859 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3860 if (Val != Val2) return 0;
3861
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003862 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3863 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3864 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3865 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3866 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3867 return 0;
3868
3869 // We can't fold (ugt x, C) & (sgt x, C2).
3870 if (!PredicatesFoldable(LHSCC, RHSCC))
3871 return 0;
3872
3873 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003874 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00003875 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003876 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00003877 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003878 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003879 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003880 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3881
3882 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003883 std::swap(LHS, RHS);
3884 std::swap(LHSCst, RHSCst);
3885 std::swap(LHSCC, RHSCC);
3886 }
3887
3888 // At this point, we know we have have two icmp instructions
3889 // comparing a value against two constants and and'ing the result
3890 // together. Because of the above check, we know that we only have
3891 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3892 // (from the FoldICmpLogical check above), that the two constants
3893 // are not equal and that the larger constant is on the RHS
3894 assert(LHSCst != RHSCst && "Compares not folded above?");
3895
3896 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003897 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003898 case ICmpInst::ICMP_EQ:
3899 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003900 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003901 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3902 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3903 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003904 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003905 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3906 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3907 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3908 return ReplaceInstUsesWith(I, LHS);
3909 }
3910 case ICmpInst::ICMP_NE:
3911 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003912 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003913 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003914 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003915 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003916 break; // (X != 13 & X u< 15) -> no change
3917 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003918 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003919 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003920 break; // (X != 13 & X s< 15) -> no change
3921 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3922 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3923 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3924 return ReplaceInstUsesWith(I, RHS);
3925 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003926 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003927 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003928 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003929 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003930 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003931 }
3932 break; // (X != 13 & X != 15) -> no change
3933 }
3934 break;
3935 case ICmpInst::ICMP_ULT:
3936 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003937 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003938 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3939 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003940 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003941 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3942 break;
3943 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3944 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3945 return ReplaceInstUsesWith(I, LHS);
3946 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3947 break;
3948 }
3949 break;
3950 case ICmpInst::ICMP_SLT:
3951 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003952 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003953 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3954 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003955 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003956 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3957 break;
3958 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3959 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3960 return ReplaceInstUsesWith(I, LHS);
3961 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3962 break;
3963 }
3964 break;
3965 case ICmpInst::ICMP_UGT:
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) -> X == 15
3969 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3970 return ReplaceInstUsesWith(I, RHS);
3971 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3972 break;
3973 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003974 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003975 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003976 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003977 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003978 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003979 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003980 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3981 break;
3982 }
3983 break;
3984 case ICmpInst::ICMP_SGT:
3985 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003986 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003987 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3988 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3989 return ReplaceInstUsesWith(I, RHS);
3990 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3991 break;
3992 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003993 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003994 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003995 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003996 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003997 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003998 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003999 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4000 break;
4001 }
4002 break;
4003 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004004
4005 return 0;
4006}
4007
Chris Lattner42d1be02009-07-23 05:14:02 +00004008Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4009 FCmpInst *RHS) {
4010
4011 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4012 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4013 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4014 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4015 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4016 // If either of the constants are nans, then the whole thing returns
4017 // false.
4018 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004019 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004020 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004021 LHS->getOperand(0), RHS->getOperand(0));
4022 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004023
4024 // Handle vector zeros. This occurs because the canonical form of
4025 // "fcmp ord x,x" is "fcmp ord x, 0".
4026 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4027 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004028 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004029 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004030 return 0;
4031 }
4032
4033 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4034 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4035 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4036
4037
4038 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4039 // Swap RHS operands to match LHS.
4040 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4041 std::swap(Op1LHS, Op1RHS);
4042 }
4043
4044 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4045 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4046 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004047 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004048
4049 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004050 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004051 if (Op0CC == FCmpInst::FCMP_TRUE)
4052 return ReplaceInstUsesWith(I, RHS);
4053 if (Op1CC == FCmpInst::FCMP_TRUE)
4054 return ReplaceInstUsesWith(I, LHS);
4055
4056 bool Op0Ordered;
4057 bool Op1Ordered;
4058 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4059 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4060 if (Op1Pred == 0) {
4061 std::swap(LHS, RHS);
4062 std::swap(Op0Pred, Op1Pred);
4063 std::swap(Op0Ordered, Op1Ordered);
4064 }
4065 if (Op0Pred == 0) {
4066 // uno && ueq -> uno && (uno || eq) -> ueq
4067 // ord && olt -> ord && (ord && lt) -> olt
4068 if (Op0Ordered == Op1Ordered)
4069 return ReplaceInstUsesWith(I, RHS);
4070
4071 // uno && oeq -> uno && (ord && eq) -> false
4072 // uno && ord -> false
4073 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004074 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004075 // ord && ueq -> ord && (uno || eq) -> oeq
4076 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4077 Op0LHS, Op0RHS, Context));
4078 }
4079 }
4080
4081 return 0;
4082}
4083
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004084
Chris Lattner7e708292002-06-25 16:13:24 +00004085Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004086 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004087 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004088
Chris Lattnere87597f2004-10-16 18:11:37 +00004089 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004090 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004091
Chris Lattner6e7ba452005-01-01 16:22:27 +00004092 // and X, X = X
4093 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004094 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004095
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004096 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004097 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004098 if (SimplifyDemandedInstructionBits(I))
4099 return &I;
4100 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004101 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004102 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004103 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004104 } else if (isa<ConstantAggregateZero>(Op1)) {
4105 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004106 }
4107 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004108
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004109 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004110 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004111 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004112
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004113 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004114 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004115 Value *Op0LHS = Op0I->getOperand(0);
4116 Value *Op0RHS = Op0I->getOperand(1);
4117 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004118 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004119 case Instruction::Xor:
4120 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004121 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004122 if (!Op0I->hasOneUse()) break;
4123
4124 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4125 // Not masking anything out for the LHS, move to RHS.
4126 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4127 Op0RHS->getName()+".masked");
4128 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4129 }
4130 if (!isa<Constant>(Op0RHS) &&
4131 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4132 // Not masking anything out for the RHS, move to LHS.
4133 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4134 Op0LHS->getName()+".masked");
4135 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004136 }
4137
Chris Lattner6e7ba452005-01-01 16:22:27 +00004138 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004139 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004140 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4141 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4142 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4143 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004144 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004145 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004146 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004147 break;
4148
4149 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004150 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4151 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4152 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4153 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004154 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004155
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004156 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4157 // has 1's for all bits that the subtraction with A might affect.
4158 if (Op0I->hasOneUse()) {
4159 uint32_t BitWidth = AndRHSMask.getBitWidth();
4160 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4161 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4162
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004163 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004164 if (!(A && A->isZero()) && // avoid infinite recursion.
4165 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004166 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004167 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4168 }
4169 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004170 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004171
4172 case Instruction::Shl:
4173 case Instruction::LShr:
4174 // (1 << x) & 1 --> zext(x == 0)
4175 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004176 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004177 Value *NewICmp =
4178 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004179 return new ZExtInst(NewICmp, I.getType());
4180 }
4181 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004182 }
4183
Chris Lattner58403262003-07-23 19:25:52 +00004184 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004185 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004186 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004187 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004188 // If this is an integer truncation or change from signed-to-unsigned, and
4189 // if the source is an and/or with immediate, transform it. This
4190 // frequently occurs for bitfield accesses.
4191 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004192 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004193 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004194 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004195 if (CastOp->getOpcode() == Instruction::And) {
4196 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004197 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4198 // This will fold the two constants together, which may allow
4199 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004200 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004201 CastOp->getOperand(0), I.getType(),
4202 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004203 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004204 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004205 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004206 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004207 } else if (CastOp->getOpcode() == Instruction::Or) {
4208 // Change: and (cast (or X, C1) to T), C2
4209 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004210 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004211 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004212 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004213 return ReplaceInstUsesWith(I, AndRHS);
4214 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004215 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004216 }
Chris Lattner06782f82003-07-23 19:36:21 +00004217 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004218
4219 // Try to fold constant and into select arguments.
4220 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004221 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004222 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004223 if (isa<PHINode>(Op0))
4224 if (Instruction *NV = FoldOpIntoPhi(I))
4225 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004226 }
4227
Dan Gohman186a6362009-08-12 16:04:34 +00004228 Value *Op0NotVal = dyn_castNotVal(Op0);
4229 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004230
Chris Lattner5b62aa72004-06-18 06:07:51 +00004231 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004232 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004233
Misha Brukmancb6267b2004-07-30 12:50:08 +00004234 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004235 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004236 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4237 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004238 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004239 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004240
4241 {
Chris Lattner003b6202007-06-15 05:58:24 +00004242 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004243 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004244 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4245 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004246
4247 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004248 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004249 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004250 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004251 }
4252 }
4253
Dan Gohman4ae51262009-08-12 16:23:25 +00004254 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004255 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4256 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004257
4258 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004259 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004260 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004261 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004262 }
4263 }
Chris Lattner64daab52006-04-01 08:03:55 +00004264
4265 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004266 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004267 if (A == Op1) { // (A^B)&A -> A&(A^B)
4268 I.swapOperands(); // Simplify below
4269 std::swap(Op0, Op1);
4270 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4271 cast<BinaryOperator>(Op0)->swapOperands();
4272 I.swapOperands(); // Simplify below
4273 std::swap(Op0, Op1);
4274 }
4275 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004276
Chris Lattner64daab52006-04-01 08:03:55 +00004277 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004278 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004279 if (B == Op0) { // B&(A^B) -> B&(B^A)
4280 cast<BinaryOperator>(Op1)->swapOperands();
4281 std::swap(A, B);
4282 }
Chris Lattner74381062009-08-30 07:44:24 +00004283 if (A == Op0) // A&(A^B) -> A & ~B
4284 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004285 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004286
4287 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004288 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4289 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004290 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004291 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4292 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004293 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004294 }
4295
Reid Spencere4d87aa2006-12-23 06:05:41 +00004296 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4297 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004298 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004299 return R;
4300
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004301 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4302 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4303 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004304 }
4305
Chris Lattner6fc205f2006-05-05 06:39:07 +00004306 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004307 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4308 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4309 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4310 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004311 if (SrcTy == Op1C->getOperand(0)->getType() &&
4312 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004313 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004314 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4315 I.getType(), TD) &&
4316 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4317 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004318 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4319 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004320 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004321 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004322 }
Chris Lattnere511b742006-11-14 07:46:50 +00004323
4324 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004325 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4326 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4327 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004328 SI0->getOperand(1) == SI1->getOperand(1) &&
4329 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004330 Value *NewOp =
4331 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4332 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004333 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004334 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004335 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004336 }
4337
Evan Cheng8db90722008-10-14 17:15:11 +00004338 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004339 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004340 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4341 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4342 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004343 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004344
Chris Lattner7e708292002-06-25 16:13:24 +00004345 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004346}
4347
Chris Lattner8c34cd22008-10-05 02:13:19 +00004348/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4349/// capable of providing pieces of a bswap. The subexpression provides pieces
4350/// of a bswap if it is proven that each of the non-zero bytes in the output of
4351/// the expression came from the corresponding "byte swapped" byte in some other
4352/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4353/// we know that the expression deposits the low byte of %X into the high byte
4354/// of the bswap result and that all other bytes are zero. This expression is
4355/// accepted, the high byte of ByteValues is set to X to indicate a correct
4356/// match.
4357///
4358/// This function returns true if the match was unsuccessful and false if so.
4359/// On entry to the function the "OverallLeftShift" is a signed integer value
4360/// indicating the number of bytes that the subexpression is later shifted. For
4361/// example, if the expression is later right shifted by 16 bits, the
4362/// OverallLeftShift value would be -2 on entry. This is used to specify which
4363/// byte of ByteValues is actually being set.
4364///
4365/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4366/// byte is masked to zero by a user. For example, in (X & 255), X will be
4367/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4368/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4369/// always in the local (OverallLeftShift) coordinate space.
4370///
4371static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4372 SmallVector<Value*, 8> &ByteValues) {
4373 if (Instruction *I = dyn_cast<Instruction>(V)) {
4374 // If this is an or instruction, it may be an inner node of the bswap.
4375 if (I->getOpcode() == Instruction::Or) {
4376 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4377 ByteValues) ||
4378 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4379 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004380 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004381
4382 // If this is a logical shift by a constant multiple of 8, recurse with
4383 // OverallLeftShift and ByteMask adjusted.
4384 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4385 unsigned ShAmt =
4386 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4387 // Ensure the shift amount is defined and of a byte value.
4388 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4389 return true;
4390
4391 unsigned ByteShift = ShAmt >> 3;
4392 if (I->getOpcode() == Instruction::Shl) {
4393 // X << 2 -> collect(X, +2)
4394 OverallLeftShift += ByteShift;
4395 ByteMask >>= ByteShift;
4396 } else {
4397 // X >>u 2 -> collect(X, -2)
4398 OverallLeftShift -= ByteShift;
4399 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004400 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004401 }
4402
4403 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4404 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4405
4406 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4407 ByteValues);
4408 }
4409
4410 // If this is a logical 'and' with a mask that clears bytes, clear the
4411 // corresponding bytes in ByteMask.
4412 if (I->getOpcode() == Instruction::And &&
4413 isa<ConstantInt>(I->getOperand(1))) {
4414 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4415 unsigned NumBytes = ByteValues.size();
4416 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4417 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4418
4419 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4420 // If this byte is masked out by a later operation, we don't care what
4421 // the and mask is.
4422 if ((ByteMask & (1 << i)) == 0)
4423 continue;
4424
4425 // If the AndMask is all zeros for this byte, clear the bit.
4426 APInt MaskB = AndMask & Byte;
4427 if (MaskB == 0) {
4428 ByteMask &= ~(1U << i);
4429 continue;
4430 }
4431
4432 // If the AndMask is not all ones for this byte, it's not a bytezap.
4433 if (MaskB != Byte)
4434 return true;
4435
4436 // Otherwise, this byte is kept.
4437 }
4438
4439 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4440 ByteValues);
4441 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004442 }
4443
Chris Lattner8c34cd22008-10-05 02:13:19 +00004444 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4445 // the input value to the bswap. Some observations: 1) if more than one byte
4446 // is demanded from this input, then it could not be successfully assembled
4447 // into a byteswap. At least one of the two bytes would not be aligned with
4448 // their ultimate destination.
4449 if (!isPowerOf2_32(ByteMask)) return true;
4450 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004451
Chris Lattner8c34cd22008-10-05 02:13:19 +00004452 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4453 // is demanded, it needs to go into byte 0 of the result. This means that the
4454 // byte needs to be shifted until it lands in the right byte bucket. The
4455 // shift amount depends on the position: if the byte is coming from the high
4456 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4457 // low part, it must be shifted left.
4458 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4459 if (InputByteNo < ByteValues.size()/2) {
4460 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4461 return true;
4462 } else {
4463 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4464 return true;
4465 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004466
4467 // If the destination byte value is already defined, the values are or'd
4468 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004469 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004470 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004471 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004472 return false;
4473}
4474
4475/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4476/// If so, insert the new bswap intrinsic and return it.
4477Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004478 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004479 if (!ITy || ITy->getBitWidth() % 16 ||
4480 // ByteMask only allows up to 32-byte values.
4481 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004482 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004483
4484 /// ByteValues - For each byte of the result, we keep track of which value
4485 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004486 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004487 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004488
4489 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004490 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4491 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004492 return 0;
4493
4494 // Check to see if all of the bytes come from the same value.
4495 Value *V = ByteValues[0];
4496 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4497
4498 // Check to make sure that all of the bytes come from the same value.
4499 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4500 if (ByteValues[i] != V)
4501 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004502 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004503 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004504 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004505 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004506}
4507
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004508/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4509/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4510/// we can simplify this expression to "cond ? C : D or B".
4511static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004512 Value *C, Value *D,
4513 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004514 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004515 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004516 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004517 return 0;
4518
Chris Lattnera6a474d2008-11-16 04:26:55 +00004519 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004520 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004521 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004522 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004523 return SelectInst::Create(Cond, C, B);
4524 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004525 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004526 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004527 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004528 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004529 return 0;
4530}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004531
Chris Lattner69d4ced2008-11-16 05:20:07 +00004532/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4533Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4534 ICmpInst *LHS, ICmpInst *RHS) {
4535 Value *Val, *Val2;
4536 ConstantInt *LHSCst, *RHSCst;
4537 ICmpInst::Predicate LHSCC, RHSCC;
4538
4539 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004540 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004541 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004542 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004543 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004544 return 0;
4545
4546 // From here on, we only handle:
4547 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4548 if (Val != Val2) return 0;
4549
4550 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4551 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4552 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4553 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4554 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4555 return 0;
4556
4557 // We can't fold (ugt x, C) | (sgt x, C2).
4558 if (!PredicatesFoldable(LHSCC, RHSCC))
4559 return 0;
4560
4561 // Ensure that the larger constant is on the RHS.
4562 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004563 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004564 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004565 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004566 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4567 else
4568 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4569
4570 if (ShouldSwap) {
4571 std::swap(LHS, RHS);
4572 std::swap(LHSCst, RHSCst);
4573 std::swap(LHSCC, RHSCC);
4574 }
4575
4576 // At this point, we know we have have two icmp instructions
4577 // comparing a value against two constants and or'ing the result
4578 // together. Because of the above check, we know that we only have
4579 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4580 // FoldICmpLogical check above), that the two constants are not
4581 // equal.
4582 assert(LHSCst != RHSCst && "Compares not folded above?");
4583
4584 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004585 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004586 case ICmpInst::ICMP_EQ:
4587 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004588 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004589 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004590 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004591 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004592 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004593 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004594 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004595 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004596 }
4597 break; // (X == 13 | X == 15) -> no change
4598 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4599 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4600 break;
4601 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4602 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4603 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4604 return ReplaceInstUsesWith(I, RHS);
4605 }
4606 break;
4607 case ICmpInst::ICMP_NE:
4608 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004609 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004610 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4611 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4612 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4613 return ReplaceInstUsesWith(I, LHS);
4614 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4615 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4616 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004617 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004618 }
4619 break;
4620 case ICmpInst::ICMP_ULT:
4621 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004622 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004623 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4624 break;
4625 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4626 // If RHSCst is [us]MAXINT, it is always false. Not handling
4627 // this can cause overflow.
4628 if (RHSCst->isMaxValue(false))
4629 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004630 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004631 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004632 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4633 break;
4634 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4635 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4636 return ReplaceInstUsesWith(I, RHS);
4637 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4638 break;
4639 }
4640 break;
4641 case ICmpInst::ICMP_SLT:
4642 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004643 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004644 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4645 break;
4646 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4647 // If RHSCst is [us]MAXINT, it is always false. Not handling
4648 // this can cause overflow.
4649 if (RHSCst->isMaxValue(true))
4650 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004651 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004652 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004653 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4654 break;
4655 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4656 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4657 return ReplaceInstUsesWith(I, RHS);
4658 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4659 break;
4660 }
4661 break;
4662 case ICmpInst::ICMP_UGT:
4663 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004664 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004665 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4666 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4667 return ReplaceInstUsesWith(I, LHS);
4668 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4669 break;
4670 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4671 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004672 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004673 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4674 break;
4675 }
4676 break;
4677 case ICmpInst::ICMP_SGT:
4678 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004679 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004680 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4681 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4682 return ReplaceInstUsesWith(I, LHS);
4683 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4684 break;
4685 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4686 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004687 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004688 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4689 break;
4690 }
4691 break;
4692 }
4693 return 0;
4694}
4695
Chris Lattner5414cc52009-07-23 05:46:22 +00004696Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4697 FCmpInst *RHS) {
4698 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4699 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4700 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4701 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4702 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4703 // If either of the constants are nans, then the whole thing returns
4704 // true.
4705 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004706 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004707
4708 // Otherwise, no need to compare the two constants, compare the
4709 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004710 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004711 LHS->getOperand(0), RHS->getOperand(0));
4712 }
4713
4714 // Handle vector zeros. This occurs because the canonical form of
4715 // "fcmp uno x,x" is "fcmp uno x, 0".
4716 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4717 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004718 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004719 LHS->getOperand(0), RHS->getOperand(0));
4720
4721 return 0;
4722 }
4723
4724 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4725 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4726 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4727
4728 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4729 // Swap RHS operands to match LHS.
4730 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4731 std::swap(Op1LHS, Op1RHS);
4732 }
4733 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4734 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4735 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004736 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004737 Op0LHS, Op0RHS);
4738 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004739 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004740 if (Op0CC == FCmpInst::FCMP_FALSE)
4741 return ReplaceInstUsesWith(I, RHS);
4742 if (Op1CC == FCmpInst::FCMP_FALSE)
4743 return ReplaceInstUsesWith(I, LHS);
4744 bool Op0Ordered;
4745 bool Op1Ordered;
4746 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4747 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4748 if (Op0Ordered == Op1Ordered) {
4749 // If both are ordered or unordered, return a new fcmp with
4750 // or'ed predicates.
4751 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4752 Op0LHS, Op0RHS, Context);
4753 if (Instruction *I = dyn_cast<Instruction>(RV))
4754 return I;
4755 // Otherwise, it's a constant boolean value...
4756 return ReplaceInstUsesWith(I, RV);
4757 }
4758 }
4759 return 0;
4760}
4761
Bill Wendlinga698a472008-12-01 08:23:25 +00004762/// FoldOrWithConstants - This helper function folds:
4763///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004764/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004765///
4766/// into:
4767///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004768/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004769///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004770/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004771Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004772 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004773 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4774 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004775
Bill Wendling286a0542008-12-02 06:24:20 +00004776 Value *V1 = 0;
4777 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004778 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004779
Bill Wendling29976b92008-12-02 06:18:11 +00004780 APInt Xor = CI1->getValue() ^ CI2->getValue();
4781 if (!Xor.isAllOnesValue()) return 0;
4782
Bill Wendling286a0542008-12-02 06:24:20 +00004783 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004784 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004785 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004786 }
4787
4788 return 0;
4789}
4790
Chris Lattner7e708292002-06-25 16:13:24 +00004791Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004792 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004793 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004794
Chris Lattner42593e62007-03-24 23:56:43 +00004795 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004796 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004797
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004798 // or X, X = X
4799 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004800 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004801
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004802 // See if we can simplify any instructions used by the instruction whose sole
4803 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004804 if (SimplifyDemandedInstructionBits(I))
4805 return &I;
4806 if (isa<VectorType>(I.getType())) {
4807 if (isa<ConstantAggregateZero>(Op1)) {
4808 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4809 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4810 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4811 return ReplaceInstUsesWith(I, I.getOperand(1));
4812 }
Chris Lattner42593e62007-03-24 23:56:43 +00004813 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004814
Chris Lattner3f5b8772002-05-06 16:14:14 +00004815 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004816 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004817 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004818 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004819 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004820 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004821 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004822 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004823 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004824 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004825 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004826
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004827 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004828 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004829 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004830 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004831 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004832 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004833 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004834 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004835
4836 // Try to fold constant and into select arguments.
4837 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004838 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004839 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004840 if (isa<PHINode>(Op0))
4841 if (Instruction *NV = FoldOpIntoPhi(I))
4842 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004843 }
4844
Chris Lattner4f637d42006-01-06 17:59:59 +00004845 Value *A = 0, *B = 0;
4846 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004847
Dan Gohman4ae51262009-08-12 16:23:25 +00004848 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004849 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4850 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004851 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004852 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4853 return ReplaceInstUsesWith(I, Op0);
4854
Chris Lattner6423d4c2006-07-10 20:25:24 +00004855 // (A | B) | C and A | (B | C) -> bswap if possible.
4856 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004857 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4858 match(Op1, m_Or(m_Value(), m_Value())) ||
4859 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4860 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004861 if (Instruction *BSwap = MatchBSwap(I))
4862 return BSwap;
4863 }
4864
Chris Lattner6e4c6492005-05-09 04:58:36 +00004865 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004866 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004867 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004868 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004869 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004870 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004871 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004872 }
4873
4874 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004875 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004876 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004877 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004878 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004879 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004880 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004881 }
4882
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004883 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004884 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004885 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4886 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004887 Value *V1 = 0, *V2 = 0, *V3 = 0;
4888 C1 = dyn_cast<ConstantInt>(C);
4889 C2 = dyn_cast<ConstantInt>(D);
4890 if (C1 && C2) { // (A & C1)|(B & C2)
4891 // If we have: ((V + N) & C1) | (V & C2)
4892 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4893 // replace with V+N.
4894 if (C1->getValue() == ~C2->getValue()) {
4895 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004896 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004897 // Add commutes, try both ways.
4898 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4899 return ReplaceInstUsesWith(I, A);
4900 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4901 return ReplaceInstUsesWith(I, A);
4902 }
4903 // Or commutes, try both ways.
4904 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004905 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004906 // Add commutes, try both ways.
4907 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4908 return ReplaceInstUsesWith(I, B);
4909 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4910 return ReplaceInstUsesWith(I, B);
4911 }
4912 }
Chris Lattner044e5332007-04-08 08:01:49 +00004913 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004914 }
4915
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004916 // Check to see if we have any common things being and'ed. If so, find the
4917 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004918 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4919 if (A == B) // (A & C)|(A & D) == A & (C|D)
4920 V1 = A, V2 = C, V3 = D;
4921 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4922 V1 = A, V2 = B, V3 = C;
4923 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4924 V1 = C, V2 = A, V3 = D;
4925 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4926 V1 = C, V2 = A, V3 = B;
4927
4928 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004929 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004930 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004931 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004932 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004933
Dan Gohman1975d032008-10-30 20:40:10 +00004934 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004935 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004936 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004937 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004938 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004939 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004940 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004941 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004942 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004943
Bill Wendlingb01865c2008-11-30 13:52:49 +00004944 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004945 if ((match(C, m_Not(m_Specific(D))) &&
4946 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004947 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004948 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004949 if ((match(A, m_Not(m_Specific(D))) &&
4950 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004951 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004952 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004953 if ((match(C, m_Not(m_Specific(B))) &&
4954 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004955 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004956 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004957 if ((match(A, m_Not(m_Specific(B))) &&
4958 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004959 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004960 }
Chris Lattnere511b742006-11-14 07:46:50 +00004961
4962 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004963 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4964 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4965 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004966 SI0->getOperand(1) == SI1->getOperand(1) &&
4967 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004968 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4969 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004970 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004971 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004972 }
4973 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004974
Bill Wendlingb3833d12008-12-01 01:07:11 +00004975 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004976 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4977 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004978 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004979 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004980 }
4981 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004982 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4983 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004984 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004985 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004986 }
4987
Chris Lattner48b59ec2009-10-26 15:40:07 +00004988 if ((A = dyn_castNotVal(Op0))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004989 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004990 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004991 } else {
4992 A = 0;
4993 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004994 // Note, A is still live here!
Chris Lattner48b59ec2009-10-26 15:40:07 +00004995 if ((B = dyn_castNotVal(Op1))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004996 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004997 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004998
Misha Brukmancb6267b2004-07-30 12:50:08 +00004999 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005000 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00005001 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00005002 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005003 }
Chris Lattnera27231a2003-03-10 23:13:59 +00005004 }
Chris Lattnera2881962003-02-18 19:28:33 +00005005
Reid Spencere4d87aa2006-12-23 06:05:41 +00005006 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5007 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005008 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005009 return R;
5010
Chris Lattner69d4ced2008-11-16 05:20:07 +00005011 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5012 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5013 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005014 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005015
5016 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005017 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005018 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005019 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005020 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5021 !isa<ICmpInst>(Op1C->getOperand(0))) {
5022 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005023 if (SrcTy == Op1C->getOperand(0)->getType() &&
5024 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005025 // Only do this if the casts both really cause code to be
5026 // generated.
5027 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5028 I.getType(), TD) &&
5029 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5030 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005031 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5032 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005033 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005034 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005035 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005036 }
Chris Lattner99c65742007-10-24 05:38:08 +00005037 }
5038
5039
5040 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5041 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005042 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5043 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5044 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005045 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005046
Chris Lattner7e708292002-06-25 16:13:24 +00005047 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005048}
5049
Dan Gohman844731a2008-05-13 00:00:25 +00005050namespace {
5051
Chris Lattnerc317d392004-02-16 01:20:27 +00005052// XorSelf - Implements: X ^ X --> 0
5053struct XorSelf {
5054 Value *RHS;
5055 XorSelf(Value *rhs) : RHS(rhs) {}
5056 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5057 Instruction *apply(BinaryOperator &Xor) const {
5058 return &Xor;
5059 }
5060};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005061
Dan Gohman844731a2008-05-13 00:00:25 +00005062}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005063
Chris Lattner7e708292002-06-25 16:13:24 +00005064Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005065 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005066 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005067
Evan Chengd34af782008-03-25 20:07:13 +00005068 if (isa<UndefValue>(Op1)) {
5069 if (isa<UndefValue>(Op0))
5070 // Handle undef ^ undef -> 0 special case. This is a common
5071 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005072 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005073 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005074 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005075
Chris Lattnerc317d392004-02-16 01:20:27 +00005076 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005077 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005078 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005079 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005080 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005081
5082 // See if we can simplify any instructions used by the instruction whose sole
5083 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005084 if (SimplifyDemandedInstructionBits(I))
5085 return &I;
5086 if (isa<VectorType>(I.getType()))
5087 if (isa<ConstantAggregateZero>(Op1))
5088 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005089
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005090 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005091 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005092 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5093 if (Op0I->getOpcode() == Instruction::And ||
5094 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005095 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5096 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5097 if (dyn_castNotVal(Op0I->getOperand(1)))
5098 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005099 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005100 Value *NotY =
5101 Builder->CreateNot(Op0I->getOperand(1),
5102 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005103 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005104 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005105 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005106 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005107
5108 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5109 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5110 if (isFreeToInvert(Op0I->getOperand(0)) &&
5111 isFreeToInvert(Op0I->getOperand(1))) {
5112 Value *NotX =
5113 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5114 Value *NotY =
5115 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5116 if (Op0I->getOpcode() == Instruction::And)
5117 return BinaryOperator::CreateOr(NotX, NotY);
5118 return BinaryOperator::CreateAnd(NotX, NotY);
5119 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005120 }
5121 }
5122 }
5123
5124
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005125 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005126 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005127 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005128 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005129 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005130 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005131
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005132 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005133 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005134 FCI->getOperand(0), FCI->getOperand(1));
5135 }
5136
Nick Lewycky517e1f52008-05-31 19:01:33 +00005137 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5138 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5139 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5140 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5141 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005142 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5143 (RHS == ConstantExpr::getCast(Opcode,
5144 ConstantInt::getTrue(*Context),
5145 Op0C->getDestTy()))) {
5146 CI->setPredicate(CI->getInversePredicate());
5147 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005148 }
5149 }
5150 }
5151 }
5152
Reid Spencere4d87aa2006-12-23 06:05:41 +00005153 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005154 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005155 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5156 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005157 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5158 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005159 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005160 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005161 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005162
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005163 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005164 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005165 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005166 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005167 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005168 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005169 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005170 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005171 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005172 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005173 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005174 Constant *C = ConstantInt::get(*Context,
5175 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005176 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005177
Chris Lattner7c4049c2004-01-12 19:35:11 +00005178 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005179 } else if (Op0I->getOpcode() == Instruction::Or) {
5180 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005181 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005182 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005183 // Anything in both C1 and C2 is known to be zero, remove it from
5184 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005185 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5186 NewRHS = ConstantExpr::getAnd(NewRHS,
5187 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005188 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005189 I.setOperand(0, Op0I->getOperand(0));
5190 I.setOperand(1, NewRHS);
5191 return &I;
5192 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005193 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005194 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005195 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005196
5197 // Try to fold constant and into select arguments.
5198 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005199 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005200 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005201 if (isa<PHINode>(Op0))
5202 if (Instruction *NV = FoldOpIntoPhi(I))
5203 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005204 }
5205
Dan Gohman186a6362009-08-12 16:04:34 +00005206 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005207 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005208 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005209
Dan Gohman186a6362009-08-12 16:04:34 +00005210 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005211 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005212 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005213
Chris Lattner318bf792007-03-18 22:51:34 +00005214
5215 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5216 if (Op1I) {
5217 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005218 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005219 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005220 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005221 I.swapOperands();
5222 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005223 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005224 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005225 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005226 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005227 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005228 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005229 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005230 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005231 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005232 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005233 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005234 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005235 std::swap(A, B);
5236 }
Chris Lattner318bf792007-03-18 22:51:34 +00005237 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005238 I.swapOperands(); // Simplified below.
5239 std::swap(Op0, Op1);
5240 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005241 }
Chris Lattner318bf792007-03-18 22:51:34 +00005242 }
5243
5244 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5245 if (Op0I) {
5246 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005247 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005248 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005249 if (A == Op1) // (B|A)^B == (A|B)^B
5250 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005251 if (B == Op1) // (A|B)^B == A & ~B
5252 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005253 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005254 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005255 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005256 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005257 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005258 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005259 if (A == Op1) // (A&B)^A -> (B&A)^A
5260 std::swap(A, B);
5261 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005262 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005263 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005264 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005265 }
Chris Lattner318bf792007-03-18 22:51:34 +00005266 }
5267
5268 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5269 if (Op0I && Op1I && Op0I->isShift() &&
5270 Op0I->getOpcode() == Op1I->getOpcode() &&
5271 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5272 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005273 Value *NewOp =
5274 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5275 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005276 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005277 Op1I->getOperand(1));
5278 }
5279
5280 if (Op0I && Op1I) {
5281 Value *A, *B, *C, *D;
5282 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005283 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5284 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005285 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005286 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005287 }
5288 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005289 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5290 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005291 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005292 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005293 }
5294
5295 // (A & B)^(C & D)
5296 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005297 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5298 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005299 // (X & Y)^(X & Y) -> (Y^Z) & X
5300 Value *X = 0, *Y = 0, *Z = 0;
5301 if (A == C)
5302 X = A, Y = B, Z = D;
5303 else if (A == D)
5304 X = A, Y = B, Z = C;
5305 else if (B == C)
5306 X = B, Y = A, Z = D;
5307 else if (B == D)
5308 X = B, Y = A, Z = C;
5309
5310 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005311 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005312 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005313 }
5314 }
5315 }
5316
Reid Spencere4d87aa2006-12-23 06:05:41 +00005317 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5318 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005319 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005320 return R;
5321
Chris Lattner6fc205f2006-05-05 06:39:07 +00005322 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005323 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005324 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005325 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5326 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005327 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005328 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005329 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5330 I.getType(), TD) &&
5331 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5332 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005333 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5334 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005335 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005336 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005337 }
Chris Lattner99c65742007-10-24 05:38:08 +00005338 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005339
Chris Lattner7e708292002-06-25 16:13:24 +00005340 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005341}
5342
Owen Andersond672ecb2009-07-03 00:17:18 +00005343static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005344 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005345 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005346}
Chris Lattnera96879a2004-09-29 17:40:11 +00005347
Dan Gohman6de29f82009-06-15 22:12:54 +00005348static bool HasAddOverflow(ConstantInt *Result,
5349 ConstantInt *In1, ConstantInt *In2,
5350 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005351 if (IsSigned)
5352 if (In2->getValue().isNegative())
5353 return Result->getValue().sgt(In1->getValue());
5354 else
5355 return Result->getValue().slt(In1->getValue());
5356 else
5357 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005358}
5359
Dan Gohman6de29f82009-06-15 22:12:54 +00005360/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005361/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005362static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005363 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005364 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005365 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005366
Dan Gohman6de29f82009-06-15 22:12:54 +00005367 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5368 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005369 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005370 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5371 ExtractElement(In1, Idx, Context),
5372 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005373 IsSigned))
5374 return true;
5375 }
5376 return false;
5377 }
5378
5379 return HasAddOverflow(cast<ConstantInt>(Result),
5380 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5381 IsSigned);
5382}
5383
5384static bool HasSubOverflow(ConstantInt *Result,
5385 ConstantInt *In1, ConstantInt *In2,
5386 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005387 if (IsSigned)
5388 if (In2->getValue().isNegative())
5389 return Result->getValue().slt(In1->getValue());
5390 else
5391 return Result->getValue().sgt(In1->getValue());
5392 else
5393 return Result->getValue().ugt(In1->getValue());
5394}
5395
Dan Gohman6de29f82009-06-15 22:12:54 +00005396/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5397/// overflowed for this type.
5398static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005399 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005400 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005401 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005402
5403 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5404 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005405 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005406 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5407 ExtractElement(In1, Idx, Context),
5408 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005409 IsSigned))
5410 return true;
5411 }
5412 return false;
5413 }
5414
5415 return HasSubOverflow(cast<ConstantInt>(Result),
5416 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5417 IsSigned);
5418}
5419
Chris Lattner574da9b2005-01-13 20:14:25 +00005420/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5421/// code necessary to compute the offset from the base pointer (without adding
5422/// in the base pointer). Return the result as a signed integer of intptr size.
5423static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005424 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005425 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005426 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005427 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005428
5429 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005430 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005431 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005432
Gabor Greif177dd3f2008-06-12 21:37:33 +00005433 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5434 ++i, ++GTI) {
5435 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005436 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005437 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5438 if (OpC->isZero()) continue;
5439
5440 // Handle a struct index, which adds its field offset to the pointer.
5441 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5442 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5443
Chris Lattner74381062009-08-30 07:44:24 +00005444 Result = IC.Builder->CreateAdd(Result,
5445 ConstantInt::get(IntPtrTy, Size),
5446 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005447 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005448 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005449
Owen Andersoneed707b2009-07-24 23:12:02 +00005450 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005451 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005452 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5453 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005454 // Emit an add instruction.
5455 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005456 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005457 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005458 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005459 if (Op->getType() != IntPtrTy)
5460 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005461 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005462 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005463 // We'll let instcombine(mul) convert this to a shl if possible.
5464 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005465 }
5466
5467 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005468 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005469 }
5470 return Result;
5471}
5472
Chris Lattner10c0d912008-04-22 02:53:33 +00005473
Dan Gohman8f080f02009-07-17 22:16:21 +00005474/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5475/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5476/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5477/// be complex, and scales are involved. The above expression would also be
5478/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5479/// This later form is less amenable to optimization though, and we are allowed
5480/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005481///
5482/// If we can't emit an optimized form for this expression, this returns null.
5483///
5484static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5485 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005486 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005487 gep_type_iterator GTI = gep_type_begin(GEP);
5488
5489 // Check to see if this gep only has a single variable index. If so, and if
5490 // any constant indices are a multiple of its scale, then we can compute this
5491 // in terms of the scale of the variable index. For example, if the GEP
5492 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5493 // because the expression will cross zero at the same point.
5494 unsigned i, e = GEP->getNumOperands();
5495 int64_t Offset = 0;
5496 for (i = 1; i != e; ++i, ++GTI) {
5497 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5498 // Compute the aggregate offset of constant indices.
5499 if (CI->isZero()) continue;
5500
5501 // Handle a struct index, which adds its field offset to the pointer.
5502 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5503 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5504 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005505 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005506 Offset += Size*CI->getSExtValue();
5507 }
5508 } else {
5509 // Found our variable index.
5510 break;
5511 }
5512 }
5513
5514 // If there are no variable indices, we must have a constant offset, just
5515 // evaluate it the general way.
5516 if (i == e) return 0;
5517
5518 Value *VariableIdx = GEP->getOperand(i);
5519 // Determine the scale factor of the variable element. For example, this is
5520 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005521 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005522
5523 // Verify that there are no other variable indices. If so, emit the hard way.
5524 for (++i, ++GTI; i != e; ++i, ++GTI) {
5525 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5526 if (!CI) return 0;
5527
5528 // Compute the aggregate offset of constant indices.
5529 if (CI->isZero()) continue;
5530
5531 // Handle a struct index, which adds its field offset to the pointer.
5532 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5533 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5534 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005535 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005536 Offset += Size*CI->getSExtValue();
5537 }
5538 }
5539
5540 // Okay, we know we have a single variable index, which must be a
5541 // pointer/array/vector index. If there is no offset, life is simple, return
5542 // the index.
5543 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5544 if (Offset == 0) {
5545 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5546 // we don't need to bother extending: the extension won't affect where the
5547 // computation crosses zero.
5548 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005549 VariableIdx = new TruncInst(VariableIdx,
5550 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005551 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005552 return VariableIdx;
5553 }
5554
5555 // Otherwise, there is an index. The computation we will do will be modulo
5556 // the pointer size, so get it.
5557 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5558
5559 Offset &= PtrSizeMask;
5560 VariableScale &= PtrSizeMask;
5561
5562 // To do this transformation, any constant index must be a multiple of the
5563 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5564 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5565 // multiple of the variable scale.
5566 int64_t NewOffs = Offset / (int64_t)VariableScale;
5567 if (Offset != NewOffs*(int64_t)VariableScale)
5568 return 0;
5569
5570 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005571 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005572 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005573 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005574 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005575 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005576 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005577 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005578}
5579
5580
Reid Spencere4d87aa2006-12-23 06:05:41 +00005581/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005582/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005583Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005584 ICmpInst::Predicate Cond,
5585 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005586 // Look through bitcasts.
5587 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5588 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005589
Chris Lattner574da9b2005-01-13 20:14:25 +00005590 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005591 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005592 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005593 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005594 // know pointers can't overflow since the gep is inbounds. See if we can
5595 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005596 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5597
5598 // If not, synthesize the offset the hard way.
5599 if (Offset == 0)
5600 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005601 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005602 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005603 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005604 // If the base pointers are different, but the indices are the same, just
5605 // compare the base pointer.
5606 if (PtrBase != GEPRHS->getOperand(0)) {
5607 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005608 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005609 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005610 if (IndicesTheSame)
5611 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5612 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5613 IndicesTheSame = false;
5614 break;
5615 }
5616
5617 // If all indices are the same, just compare the base pointers.
5618 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005619 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005620 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005621
5622 // Otherwise, the base pointers are different and the indices are
5623 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005624 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005625 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005626
Chris Lattnere9d782b2005-01-13 22:25:21 +00005627 // If one of the GEPs has all zero indices, recurse.
5628 bool AllZeros = true;
5629 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5630 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5631 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5632 AllZeros = false;
5633 break;
5634 }
5635 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005636 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5637 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005638
5639 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005640 AllZeros = true;
5641 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5642 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5643 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5644 AllZeros = false;
5645 break;
5646 }
5647 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005648 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005649
Chris Lattner4401c9c2005-01-14 00:20:05 +00005650 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5651 // If the GEPs only differ by one index, compare it.
5652 unsigned NumDifferences = 0; // Keep track of # differences.
5653 unsigned DiffOperand = 0; // The operand that differs.
5654 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5655 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005656 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5657 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005658 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005659 NumDifferences = 2;
5660 break;
5661 } else {
5662 if (NumDifferences++) break;
5663 DiffOperand = i;
5664 }
5665 }
5666
5667 if (NumDifferences == 0) // SAME GEP?
5668 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005669 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005670 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005671
Chris Lattner4401c9c2005-01-14 00:20:05 +00005672 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005673 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5674 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005675 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005676 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005677 }
5678 }
5679
Reid Spencere4d87aa2006-12-23 06:05:41 +00005680 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005681 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005682 if (TD &&
5683 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005684 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5685 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5686 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5687 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005688 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005689 }
5690 }
5691 return 0;
5692}
5693
Chris Lattnera5406232008-05-19 20:18:56 +00005694/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5695///
5696Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5697 Instruction *LHSI,
5698 Constant *RHSC) {
5699 if (!isa<ConstantFP>(RHSC)) return 0;
5700 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5701
5702 // Get the width of the mantissa. We don't want to hack on conversions that
5703 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005704 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005705 if (MantissaWidth == -1) return 0; // Unknown.
5706
5707 // Check to see that the input is converted from an integer type that is small
5708 // enough that preserves all bits. TODO: check here for "known" sign bits.
5709 // 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 +00005710 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005711
5712 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005713 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5714 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005715 ++InputSize;
5716
5717 // If the conversion would lose info, don't hack on this.
5718 if ((int)InputSize > MantissaWidth)
5719 return 0;
5720
5721 // Otherwise, we can potentially simplify the comparison. We know that it
5722 // will always come through as an integer value and we know the constant is
5723 // not a NAN (it would have been previously simplified).
5724 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5725
5726 ICmpInst::Predicate Pred;
5727 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005728 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005729 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005730 case FCmpInst::FCMP_OEQ:
5731 Pred = ICmpInst::ICMP_EQ;
5732 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005733 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005734 case FCmpInst::FCMP_OGT:
5735 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5736 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005737 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005738 case FCmpInst::FCMP_OGE:
5739 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5740 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005741 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005742 case FCmpInst::FCMP_OLT:
5743 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5744 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005745 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005746 case FCmpInst::FCMP_OLE:
5747 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5748 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005749 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005750 case FCmpInst::FCMP_ONE:
5751 Pred = ICmpInst::ICMP_NE;
5752 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005753 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005754 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005755 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005756 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005757 }
5758
5759 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5760
5761 // Now we know that the APFloat is a normal number, zero or inf.
5762
Chris Lattner85162782008-05-20 03:50:52 +00005763 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005764 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005765 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005766
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005767 if (!LHSUnsigned) {
5768 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5769 // and large values.
5770 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5771 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5772 APFloat::rmNearestTiesToEven);
5773 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5774 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5775 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005776 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5777 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005778 }
5779 } else {
5780 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5781 // +INF and large values.
5782 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5783 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5784 APFloat::rmNearestTiesToEven);
5785 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5786 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5787 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005788 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5789 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005790 }
Chris Lattnera5406232008-05-19 20:18:56 +00005791 }
5792
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005793 if (!LHSUnsigned) {
5794 // See if the RHS value is < SignedMin.
5795 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5796 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5797 APFloat::rmNearestTiesToEven);
5798 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5799 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5800 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005801 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5802 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005803 }
Chris Lattnera5406232008-05-19 20:18:56 +00005804 }
5805
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005806 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5807 // [0, UMAX], but it may still be fractional. See if it is fractional by
5808 // casting the FP value to the integer value and back, checking for equality.
5809 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005810 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005811 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5812 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005813 if (!RHS.isZero()) {
5814 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005815 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5816 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005817 if (!Equal) {
5818 // If we had a comparison against a fractional value, we have to adjust
5819 // the compare predicate and sometimes the value. RHSC is rounded towards
5820 // zero at this point.
5821 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005822 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005823 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005824 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005825 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005826 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005827 case ICmpInst::ICMP_ULE:
5828 // (float)int <= 4.4 --> int <= 4
5829 // (float)int <= -4.4 --> false
5830 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005831 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005832 break;
5833 case ICmpInst::ICMP_SLE:
5834 // (float)int <= 4.4 --> int <= 4
5835 // (float)int <= -4.4 --> int < -4
5836 if (RHS.isNegative())
5837 Pred = ICmpInst::ICMP_SLT;
5838 break;
5839 case ICmpInst::ICMP_ULT:
5840 // (float)int < -4.4 --> false
5841 // (float)int < 4.4 --> int <= 4
5842 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005843 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005844 Pred = ICmpInst::ICMP_ULE;
5845 break;
5846 case ICmpInst::ICMP_SLT:
5847 // (float)int < -4.4 --> int < -4
5848 // (float)int < 4.4 --> int <= 4
5849 if (!RHS.isNegative())
5850 Pred = ICmpInst::ICMP_SLE;
5851 break;
5852 case ICmpInst::ICMP_UGT:
5853 // (float)int > 4.4 --> int > 4
5854 // (float)int > -4.4 --> true
5855 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005856 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005857 break;
5858 case ICmpInst::ICMP_SGT:
5859 // (float)int > 4.4 --> int > 4
5860 // (float)int > -4.4 --> int >= -4
5861 if (RHS.isNegative())
5862 Pred = ICmpInst::ICMP_SGE;
5863 break;
5864 case ICmpInst::ICMP_UGE:
5865 // (float)int >= -4.4 --> true
5866 // (float)int >= 4.4 --> int > 4
5867 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005868 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005869 Pred = ICmpInst::ICMP_UGT;
5870 break;
5871 case ICmpInst::ICMP_SGE:
5872 // (float)int >= -4.4 --> int >= -4
5873 // (float)int >= 4.4 --> int > 4
5874 if (!RHS.isNegative())
5875 Pred = ICmpInst::ICMP_SGT;
5876 break;
5877 }
Chris Lattnera5406232008-05-19 20:18:56 +00005878 }
5879 }
5880
5881 // Lower this FP comparison into an appropriate integer version of the
5882 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005883 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005884}
5885
Reid Spencere4d87aa2006-12-23 06:05:41 +00005886Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5887 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005888 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005889
Chris Lattner58e97462007-01-14 19:42:17 +00005890 // Fold trivial predicates.
5891 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005892 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005893 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005894 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005895
5896 // Simplify 'fcmp pred X, X'
5897 if (Op0 == Op1) {
5898 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005899 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005900 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5901 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5902 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner9e17b632009-09-02 05:12:37 +00005903 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005904 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5905 case FCmpInst::FCMP_OLT: // True if ordered and less than
5906 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner9e17b632009-09-02 05:12:37 +00005907 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005908
5909 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5910 case FCmpInst::FCMP_ULT: // True if unordered or less than
5911 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5912 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5913 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5914 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005915 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005916 return &I;
5917
5918 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5919 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5920 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5921 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5922 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5923 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005924 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005925 return &I;
5926 }
5927 }
5928
Reid Spencere4d87aa2006-12-23 06:05:41 +00005929 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005930 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005931
Reid Spencere4d87aa2006-12-23 06:05:41 +00005932 // Handle fcmp with constant RHS
5933 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005934 // If the constant is a nan, see if we can fold the comparison based on it.
5935 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5936 if (CFP->getValueAPF().isNaN()) {
5937 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005938 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005939 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5940 "Comparison must be either ordered or unordered!");
5941 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005942 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005943 }
5944 }
5945
Reid Spencere4d87aa2006-12-23 06:05:41 +00005946 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5947 switch (LHSI->getOpcode()) {
5948 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005949 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5950 // block. If in the same block, we're encouraging jump threading. If
5951 // not, we are just pessimizing the code by making an i1 phi.
5952 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00005953 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005954 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005955 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005956 case Instruction::SIToFP:
5957 case Instruction::UIToFP:
5958 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5959 return NV;
5960 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005961 case Instruction::Select:
5962 // If either operand of the select is a constant, we can fold the
5963 // comparison into the select arms, which will cause one to be
5964 // constant folded and the select turned into a bitwise or.
5965 Value *Op1 = 0, *Op2 = 0;
5966 if (LHSI->hasOneUse()) {
5967 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5968 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005969 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005970 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005971 Op2 = Builder->CreateFCmp(I.getPredicate(),
5972 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005973 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5974 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005975 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005976 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005977 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5978 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005979 }
5980 }
5981
5982 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005983 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005984 break;
5985 }
5986 }
5987
5988 return Changed ? &I : 0;
5989}
5990
5991Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5992 bool Changed = SimplifyCompare(I);
5993 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5994 const Type *Ty = Op0->getType();
5995
5996 // icmp X, X
5997 if (Op0 == Op1)
Chris Lattner9e17b632009-09-02 05:12:37 +00005998 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005999 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00006000
6001 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00006002 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006003
Reid Spencere4d87aa2006-12-23 06:05:41 +00006004 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00006005 // addresses never equal each other! We already know that Op0 != Op1.
Chris Lattnerbbc33852009-10-05 02:47:47 +00006006 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
Misha Brukmanfd939082005-04-21 23:48:37 +00006007 isa<ConstantPointerNull>(Op0)) &&
Chris Lattnerbbc33852009-10-05 02:47:47 +00006008 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00006009 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00006010 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006011 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00006012
Reid Spencere4d87aa2006-12-23 06:05:41 +00006013 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006014 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006015 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006016 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006017 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006018 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006019 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006020 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006021 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006022 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006023
Reid Spencere4d87aa2006-12-23 06:05:41 +00006024 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006025 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006026 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006027 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006028 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006029 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006030 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006031 case ICmpInst::ICMP_SGT:
6032 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006033 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006034 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006035 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006036 return BinaryOperator::CreateAnd(Not, Op0);
6037 }
6038 case ICmpInst::ICMP_UGE:
6039 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6040 // FALL THROUGH
6041 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006042 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006043 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006044 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006045 case ICmpInst::ICMP_SGE:
6046 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6047 // FALL THROUGH
6048 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006049 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006050 return BinaryOperator::CreateOr(Not, Op0);
6051 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006052 }
Chris Lattner8b170942002-08-09 23:47:40 +00006053 }
6054
Dan Gohman1c8491e2009-04-25 17:12:48 +00006055 unsigned BitWidth = 0;
6056 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006057 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6058 else if (Ty->isIntOrIntVector())
6059 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006060
6061 bool isSignBit = false;
6062
Dan Gohman81b28ce2008-09-16 18:46:06 +00006063 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006064 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006065 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006066
Chris Lattnerb6566012008-01-05 01:18:20 +00006067 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6068 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006069 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006070 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006071 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006072 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006073
Dan Gohman81b28ce2008-09-16 18:46:06 +00006074 // If we have an icmp le or icmp ge instruction, turn it into the
6075 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6076 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006077 switch (I.getPredicate()) {
6078 default: break;
6079 case ICmpInst::ICMP_ULE:
6080 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006081 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006082 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006083 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006084 case ICmpInst::ICMP_SLE:
6085 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006086 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006087 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006088 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006089 case ICmpInst::ICMP_UGE:
6090 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006091 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006092 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006093 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006094 case ICmpInst::ICMP_SGE:
6095 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006096 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006097 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006098 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006099 }
6100
Chris Lattner183661e2008-07-11 05:40:05 +00006101 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006102 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006103 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006104 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6105 }
6106
6107 // See if we can fold the comparison based on range information we can get
6108 // by checking whether bits are known to be zero or one in the input.
6109 if (BitWidth != 0) {
6110 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6111 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6112
6113 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006114 isSignBit ? APInt::getSignBit(BitWidth)
6115 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006116 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006117 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006118 if (SimplifyDemandedBits(I.getOperandUse(1),
6119 APInt::getAllOnesValue(BitWidth),
6120 Op1KnownZero, Op1KnownOne, 0))
6121 return &I;
6122
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006123 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006124 // in. Compute the Min, Max and RHS values based on the known bits. For the
6125 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006126 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6127 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006128 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006129 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6130 Op0Min, Op0Max);
6131 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6132 Op1Min, Op1Max);
6133 } else {
6134 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6135 Op0Min, Op0Max);
6136 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6137 Op1Min, Op1Max);
6138 }
6139
Chris Lattner183661e2008-07-11 05:40:05 +00006140 // If Min and Max are known to be the same, then SimplifyDemandedBits
6141 // figured out that the LHS is a constant. Just constant fold this now so
6142 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006143 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006144 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006145 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006146 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006147 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006148 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006149
Chris Lattner183661e2008-07-11 05:40:05 +00006150 // Based on the range information we know about the LHS, see if we can
6151 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006152 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006153 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006154 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006155 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006156 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006157 break;
6158 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006160 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006161 break;
6162 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006164 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006165 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006166 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006168 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006169 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6170 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006171 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006172 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006173
6174 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6175 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006176 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006177 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006178 }
Chris Lattner84dff672008-07-11 05:08:55 +00006179 break;
6180 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006181 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006182 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006183 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006184 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006185
6186 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006187 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006188 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6189 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006190 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006191 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006192
6193 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6194 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006195 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006196 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006197 }
Chris Lattner84dff672008-07-11 05:08:55 +00006198 break;
6199 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006200 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006201 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006202 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006203 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006204 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006205 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6207 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006208 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006209 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006210 }
Chris Lattner84dff672008-07-11 05:08:55 +00006211 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006212 case ICmpInst::ICMP_SGT:
6213 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006214 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006215 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006216 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006217
6218 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006219 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006220 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6221 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006222 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006223 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006224 }
6225 break;
6226 case ICmpInst::ICMP_SGE:
6227 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6228 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006229 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006230 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006231 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006232 break;
6233 case ICmpInst::ICMP_SLE:
6234 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6235 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006236 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006237 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006238 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006239 break;
6240 case ICmpInst::ICMP_UGE:
6241 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6242 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006243 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006244 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006245 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006246 break;
6247 case ICmpInst::ICMP_ULE:
6248 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6249 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006250 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006251 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006252 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006253 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006254 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006255
6256 // Turn a signed comparison into an unsigned one if both operands
6257 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006258 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006259 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6260 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006261 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006262 }
6263
6264 // Test if the ICmpInst instruction is used exclusively by a select as
6265 // part of a minimum or maximum operation. If so, refrain from doing
6266 // any other folding. This helps out other analyses which understand
6267 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6268 // and CodeGen. And in this case, at least one of the comparison
6269 // operands has at least one user besides the compare (the select),
6270 // which would often largely negate the benefit of folding anyway.
6271 if (I.hasOneUse())
6272 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6273 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6274 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6275 return 0;
6276
6277 // See if we are doing a comparison between a constant and an instruction that
6278 // can be folded into the comparison.
6279 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006280 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006281 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006282 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006283 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006284 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6285 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006286 }
6287
Chris Lattner01deb9d2007-04-03 17:43:25 +00006288 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006289 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6290 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6291 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006292 case Instruction::GetElementPtr:
6293 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006294 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006295 bool isAllZeros = true;
6296 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6297 if (!isa<Constant>(LHSI->getOperand(i)) ||
6298 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6299 isAllZeros = false;
6300 break;
6301 }
6302 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006303 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006304 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006305 }
6306 break;
6307
Chris Lattner6970b662005-04-23 15:31:55 +00006308 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006309 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006310 // block. If in the same block, we're encouraging jump threading. If
6311 // not, we are just pessimizing the code by making an i1 phi.
6312 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006313 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006314 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006315 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006316 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006317 // If either operand of the select is a constant, we can fold the
6318 // comparison into the select arms, which will cause one to be
6319 // constant folded and the select turned into a bitwise or.
6320 Value *Op1 = 0, *Op2 = 0;
6321 if (LHSI->hasOneUse()) {
6322 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6323 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006324 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006325 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006326 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6327 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006328 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6329 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006330 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006331 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006332 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6333 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006334 }
6335 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006336
Chris Lattner6970b662005-04-23 15:31:55 +00006337 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006338 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006339 break;
6340 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006341 case Instruction::Call:
6342 // If we have (malloc != null), and if the malloc has a single use, we
6343 // can assume it is successful and remove the malloc.
6344 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6345 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006346 // Need to explicitly erase malloc call here, instead of adding it to
6347 // Worklist, because it won't get DCE'd from the Worklist since
6348 // isInstructionTriviallyDead() returns false for function calls.
6349 // It is OK to replace LHSI/MallocCall with Undef because the
6350 // instruction that uses it will be erased via Worklist.
6351 if (extractMallocCall(LHSI)) {
6352 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6353 EraseInstFromFunction(*LHSI);
6354 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006355 ConstantInt::get(Type::getInt1Ty(*Context),
6356 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006357 }
6358 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6359 if (MallocCall->hasOneUse()) {
6360 MallocCall->replaceAllUsesWith(
6361 UndefValue::get(MallocCall->getType()));
6362 EraseInstFromFunction(*MallocCall);
6363 Worklist.Add(LHSI); // The malloc's bitcast use.
6364 return ReplaceInstUsesWith(I,
6365 ConstantInt::get(Type::getInt1Ty(*Context),
6366 !I.isTrueWhenEqual()));
6367 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006368 }
6369 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006370 }
Chris Lattner6970b662005-04-23 15:31:55 +00006371 }
6372
Reid Spencere4d87aa2006-12-23 06:05:41 +00006373 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006374 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006375 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006376 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006377 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006378 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6379 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006380 return NI;
6381
Reid Spencere4d87aa2006-12-23 06:05:41 +00006382 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006383 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6384 // now.
6385 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6386 if (isa<PointerType>(Op0->getType()) &&
6387 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006388 // We keep moving the cast from the left operand over to the right
6389 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006390 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006391
Chris Lattner57d86372007-01-06 01:45:59 +00006392 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6393 // so eliminate it as well.
6394 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6395 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006396
Chris Lattnerde90b762003-11-03 04:25:02 +00006397 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006398 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006399 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006400 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006401 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006402 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006403 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006404 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006405 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006406 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006407 }
Chris Lattner57d86372007-01-06 01:45:59 +00006408 }
6409
6410 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006411 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006412 // This comes up when you have code like
6413 // int X = A < B;
6414 // if (X) ...
6415 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006416 // with a constant or another cast from the same type.
6417 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006418 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006419 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006420 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006421
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006422 // See if it's the same type of instruction on the left and right.
6423 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6424 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006425 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006426 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006427 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006428 default: break;
6429 case Instruction::Add:
6430 case Instruction::Sub:
6431 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006432 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006433 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006434 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006435 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6436 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6437 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006438 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006439 ? I.getUnsignedPredicate()
6440 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006441 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006442 Op1I->getOperand(0));
6443 }
6444
6445 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006446 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006447 ? I.getUnsignedPredicate()
6448 : I.getSignedPredicate();
6449 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006450 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006451 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006452 }
6453 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006454 break;
6455 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006456 if (!I.isEquality())
6457 break;
6458
Nick Lewycky5d52c452008-08-21 05:56:10 +00006459 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6460 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6461 // Mask = -1 >> count-trailing-zeros(Cst).
6462 if (!CI->isZero() && !CI->isOne()) {
6463 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006464 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006465 APInt::getLowBitsSet(AP.getBitWidth(),
6466 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006467 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006468 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6469 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006470 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006471 }
6472 }
6473 break;
6474 }
6475 }
6476 }
6477 }
6478
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006479 // ~x < ~y --> y < x
6480 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006481 if (match(Op0, m_Not(m_Value(A))) &&
6482 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006483 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006484 }
6485
Chris Lattner65b72ba2006-09-18 04:22:48 +00006486 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006487 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006488
6489 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006490 if (match(Op0, m_Neg(m_Value(A))) &&
6491 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006492 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006493
Dan Gohman4ae51262009-08-12 16:23:25 +00006494 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006495 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6496 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006497 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006498 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006499 }
6500
Dan Gohman4ae51262009-08-12 16:23:25 +00006501 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006502 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006503 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006504 if (match(B, m_ConstantInt(C1)) &&
6505 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006506 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006507 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006508 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6509 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006510 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006511
6512 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006513 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6514 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6515 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6516 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006517 }
6518 }
6519
Dan Gohman4ae51262009-08-12 16:23:25 +00006520 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006521 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006522 // A == (A^B) -> B == 0
6523 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006524 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006525 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006526 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006527
6528 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006529 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006530 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006531 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006532
6533 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006534 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006535 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006536 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006537
Chris Lattner9c2328e2006-11-14 06:06:06 +00006538 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6539 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006540 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6541 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006542 Value *X = 0, *Y = 0, *Z = 0;
6543
6544 if (A == C) {
6545 X = B; Y = D; Z = A;
6546 } else if (A == D) {
6547 X = B; Y = C; Z = A;
6548 } else if (B == C) {
6549 X = A; Y = D; Z = B;
6550 } else if (B == D) {
6551 X = A; Y = C; Z = B;
6552 }
6553
6554 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006555 Op1 = Builder->CreateXor(X, Y, "tmp");
6556 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006557 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006558 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006559 return &I;
6560 }
6561 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006562 }
Chris Lattner7e708292002-06-25 16:13:24 +00006563 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006564}
6565
Chris Lattner562ef782007-06-20 23:46:26 +00006566
6567/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6568/// and CmpRHS are both known to be integer constants.
6569Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6570 ConstantInt *DivRHS) {
6571 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6572 const APInt &CmpRHSV = CmpRHS->getValue();
6573
6574 // FIXME: If the operand types don't match the type of the divide
6575 // then don't attempt this transform. The code below doesn't have the
6576 // logic to deal with a signed divide and an unsigned compare (and
6577 // vice versa). This is because (x /s C1) <s C2 produces different
6578 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6579 // (x /u C1) <u C2. Simply casting the operands and result won't
6580 // work. :( The if statement below tests that condition and bails
6581 // if it finds it.
6582 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00006583 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00006584 return 0;
6585 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006586 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006587 if (DivIsSigned && DivRHS->isAllOnesValue())
6588 return 0; // The overflow computation also screws up here
6589 if (DivRHS->isOne())
6590 return 0; // Not worth bothering, and eliminates some funny cases
6591 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006592
6593 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6594 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6595 // C2 (CI). By solving for X we can turn this into a range check
6596 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006597 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006598
6599 // Determine if the product overflows by seeing if the product is
6600 // not equal to the divide. Make sure we do the same kind of divide
6601 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006602 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6603 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006604
6605 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006606 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006607
Chris Lattner1dbfd482007-06-21 18:11:19 +00006608 // Figure out the interval that is being checked. For example, a comparison
6609 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6610 // Compute this interval based on the constants involved and the signedness of
6611 // the compare/divide. This computes a half-open interval, keeping track of
6612 // whether either value in the interval overflows. After analysis each
6613 // overflow variable is set to 0 if it's corresponding bound variable is valid
6614 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6615 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006616 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006617
Chris Lattner562ef782007-06-20 23:46:26 +00006618 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006619 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006620 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006621 HiOverflow = LoOverflow = ProdOV;
6622 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006623 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006624 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006625 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006626 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006627 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006628 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006629 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006630 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6631 HiOverflow = LoOverflow = ProdOV;
6632 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006633 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006634 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006635 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006636 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006637 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6638 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006639 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006640 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006641 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006642 true) ? -1 : 0;
6643 }
Chris Lattner562ef782007-06-20 23:46:26 +00006644 }
Dan Gohman76491272008-02-13 22:09:18 +00006645 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006646 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006647 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006648 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006649 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006650 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6651 HiOverflow = 1; // [INTMIN+1, overflow)
6652 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6653 }
Dan Gohman76491272008-02-13 22:09:18 +00006654 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006655 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006656 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006657 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006658 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006659 LoOverflow = AddWithOverflow(LoBound, HiBound,
6660 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006661 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006662 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6663 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006664 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006665 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006666 }
6667
Chris Lattner1dbfd482007-06-21 18:11:19 +00006668 // Dividing by a negative swaps the condition. LT <-> GT
6669 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006670 }
6671
6672 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006673 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006674 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006675 case ICmpInst::ICMP_EQ:
6676 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006677 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006678 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006679 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006680 ICmpInst::ICMP_UGE, X, LoBound);
6681 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006682 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006683 ICmpInst::ICMP_ULT, X, HiBound);
6684 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006685 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006686 case ICmpInst::ICMP_NE:
6687 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006688 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006689 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006690 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006691 ICmpInst::ICMP_ULT, X, LoBound);
6692 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006693 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006694 ICmpInst::ICMP_UGE, X, HiBound);
6695 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006696 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006697 case ICmpInst::ICMP_ULT:
6698 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006699 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006700 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006701 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006702 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006703 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006704 case ICmpInst::ICMP_UGT:
6705 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006706 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006707 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006708 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006709 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006710 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006711 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006712 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006713 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006714 }
6715}
6716
6717
Chris Lattner01deb9d2007-04-03 17:43:25 +00006718/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6719///
6720Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6721 Instruction *LHSI,
6722 ConstantInt *RHS) {
6723 const APInt &RHSV = RHS->getValue();
6724
6725 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006726 case Instruction::Trunc:
6727 if (ICI.isEquality() && LHSI->hasOneUse()) {
6728 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6729 // of the high bits truncated out of x are known.
6730 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6731 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6732 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6733 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6734 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6735
6736 // If all the high bits are known, we can do this xform.
6737 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6738 // Pull in the high bits from known-ones set.
6739 APInt NewRHS(RHS->getValue());
6740 NewRHS.zext(SrcBits);
6741 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006742 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006743 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006744 }
6745 }
6746 break;
6747
Duncan Sands0091bf22007-04-04 06:42:45 +00006748 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006749 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6750 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6751 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006752 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6753 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006754 Value *CompareVal = LHSI->getOperand(0);
6755
6756 // If the sign bit of the XorCST is not set, there is no change to
6757 // the operation, just stop using the Xor.
6758 if (!XorCST->getValue().isNegative()) {
6759 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006760 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006761 return &ICI;
6762 }
6763
6764 // Was the old condition true if the operand is positive?
6765 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6766
6767 // If so, the new one isn't.
6768 isTrueIfPositive ^= true;
6769
6770 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006771 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006772 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006773 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006774 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006775 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006776 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006777
6778 if (LHSI->hasOneUse()) {
6779 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6780 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6781 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006782 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006783 ? ICI.getUnsignedPredicate()
6784 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006785 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006786 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006787 }
6788
6789 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006790 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006791 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006792 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006793 ? ICI.getUnsignedPredicate()
6794 : ICI.getSignedPredicate();
6795 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006796 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006797 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006798 }
6799 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006800 }
6801 break;
6802 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6803 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6804 LHSI->getOperand(0)->hasOneUse()) {
6805 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6806
6807 // If the LHS is an AND of a truncating cast, we can widen the
6808 // and/compare to be the input width without changing the value
6809 // produced, eliminating a cast.
6810 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6811 // We can do this transformation if either the AND constant does not
6812 // have its sign bit set or if it is an equality comparison.
6813 // Extending a relational comparison when we're checking the sign
6814 // bit would not work.
6815 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006816 (ICI.isEquality() ||
6817 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006818 uint32_t BitWidth =
6819 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6820 APInt NewCST = AndCST->getValue();
6821 NewCST.zext(BitWidth);
6822 APInt NewCI = RHSV;
6823 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006824 Value *NewAnd =
6825 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006826 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006827 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006828 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006829 }
6830 }
6831
6832 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6833 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6834 // happens a LOT in code produced by the C front-end, for bitfield
6835 // access.
6836 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6837 if (Shift && !Shift->isShift())
6838 Shift = 0;
6839
6840 ConstantInt *ShAmt;
6841 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6842 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6843 const Type *AndTy = AndCST->getType(); // Type of the and.
6844
6845 // We can fold this as long as we can't shift unknown bits
6846 // into the mask. This can only happen with signed shift
6847 // rights, as they sign-extend.
6848 if (ShAmt) {
6849 bool CanFold = Shift->isLogicalShift();
6850 if (!CanFold) {
6851 // To test for the bad case of the signed shr, see if any
6852 // of the bits shifted in could be tested after the mask.
6853 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6854 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6855
6856 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6857 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6858 AndCST->getValue()) == 0)
6859 CanFold = true;
6860 }
6861
6862 if (CanFold) {
6863 Constant *NewCst;
6864 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006865 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006866 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006867 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006868
6869 // Check to see if we are shifting out any of the bits being
6870 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006871 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006872 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006873 // If we shifted bits out, the fold is not going to work out.
6874 // As a special case, check to see if this means that the
6875 // result is always true or false now.
6876 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006877 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006878 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006879 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006880 } else {
6881 ICI.setOperand(1, NewCst);
6882 Constant *NewAndCST;
6883 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006884 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006885 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006886 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006887 LHSI->setOperand(1, NewAndCST);
6888 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006889 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006890 return &ICI;
6891 }
6892 }
6893 }
6894
6895 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6896 // preferable because it allows the C<<Y expression to be hoisted out
6897 // of a loop if Y is invariant and X is not.
6898 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006899 ICI.isEquality() && !Shift->isArithmeticShift() &&
6900 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006901 // Compute C << Y.
6902 Value *NS;
6903 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006904 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006905 } else {
6906 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006907 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006908 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006909
6910 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006911 Value *NewAnd =
6912 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006913
6914 ICI.setOperand(0, NewAnd);
6915 return &ICI;
6916 }
6917 }
6918 break;
6919
Chris Lattnera0141b92007-07-15 20:42:37 +00006920 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6921 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6922 if (!ShAmt) break;
6923
6924 uint32_t TypeBits = RHSV.getBitWidth();
6925
6926 // Check that the shift amount is in range. If not, don't perform
6927 // undefined shifts. When the shift is visited it will be
6928 // simplified.
6929 if (ShAmt->uge(TypeBits))
6930 break;
6931
6932 if (ICI.isEquality()) {
6933 // If we are comparing against bits always shifted out, the
6934 // comparison cannot succeed.
6935 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006936 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006937 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006938 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6939 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006940 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006941 return ReplaceInstUsesWith(ICI, Cst);
6942 }
6943
6944 if (LHSI->hasOneUse()) {
6945 // Otherwise strength reduce the shift into an and.
6946 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6947 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006948 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006949 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006950
Chris Lattner74381062009-08-30 07:44:24 +00006951 Value *And =
6952 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006953 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006954 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006955 }
6956 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006957
6958 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6959 bool TrueIfSigned = false;
6960 if (LHSI->hasOneUse() &&
6961 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6962 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006963 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006964 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006965 Value *And =
6966 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006967 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006968 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006969 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006970 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006971 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006972
6973 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006974 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006975 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006976 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006977 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006978
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006979 // Check that the shift amount is in range. If not, don't perform
6980 // undefined shifts. When the shift is visited it will be
6981 // simplified.
6982 uint32_t TypeBits = RHSV.getBitWidth();
6983 if (ShAmt->uge(TypeBits))
6984 break;
6985
6986 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006987
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006988 // If we are comparing against bits always shifted out, the
6989 // comparison cannot succeed.
6990 APInt Comp = RHSV << ShAmtVal;
6991 if (LHSI->getOpcode() == Instruction::LShr)
6992 Comp = Comp.lshr(ShAmtVal);
6993 else
6994 Comp = Comp.ashr(ShAmtVal);
6995
6996 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6997 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006998 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006999 return ReplaceInstUsesWith(ICI, Cst);
7000 }
7001
7002 // Otherwise, check to see if the bits shifted out are known to be zero.
7003 // If so, we can compare against the unshifted value:
7004 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007005 if (LHSI->hasOneUse() &&
7006 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007007 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007008 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007009 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007010 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007011
Evan Chengf30752c2008-04-23 00:38:06 +00007012 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007013 // Otherwise strength reduce the shift into an and.
7014 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007015 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007016
Chris Lattner74381062009-08-30 07:44:24 +00007017 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7018 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007019 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007020 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007021 }
7022 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007023 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007024
7025 case Instruction::SDiv:
7026 case Instruction::UDiv:
7027 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7028 // Fold this div into the comparison, producing a range check.
7029 // Determine, based on the divide type, what the range is being
7030 // checked. If there is an overflow on the low or high side, remember
7031 // it, otherwise compute the range [low, hi) bounding the new value.
7032 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007033 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7034 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7035 DivRHS))
7036 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007037 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007038
7039 case Instruction::Add:
7040 // Fold: icmp pred (add, X, C1), C2
7041
7042 if (!ICI.isEquality()) {
7043 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7044 if (!LHSC) break;
7045 const APInt &LHSV = LHSC->getValue();
7046
7047 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7048 .subtract(LHSV);
7049
Nick Lewycky4a134af2009-10-25 05:20:17 +00007050 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007051 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007052 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007053 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007054 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007055 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007056 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007057 }
7058 } else {
7059 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007060 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007061 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007062 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007063 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007064 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007065 }
7066 }
7067 }
7068 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007069 }
7070
7071 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7072 if (ICI.isEquality()) {
7073 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7074
7075 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7076 // the second operand is a constant, simplify a bit.
7077 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7078 switch (BO->getOpcode()) {
7079 case Instruction::SRem:
7080 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7081 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7082 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7083 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007084 Value *NewRem =
7085 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7086 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007087 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007088 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007089 }
7090 }
7091 break;
7092 case Instruction::Add:
7093 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7094 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7095 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007096 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007097 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007098 } else if (RHSV == 0) {
7099 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7100 // efficiently invertible, or if the add has just this one use.
7101 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7102
Dan Gohman186a6362009-08-12 16:04:34 +00007103 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007104 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007105 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007106 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007107 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007108 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007109 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007110 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007111 }
7112 }
7113 break;
7114 case Instruction::Xor:
7115 // For the xor case, we can xor two constants together, eliminating
7116 // the explicit xor.
7117 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007118 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007119 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007120
7121 // FALLTHROUGH
7122 case Instruction::Sub:
7123 // Replace (([sub|xor] A, B) != 0) with (A != B)
7124 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007125 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007126 BO->getOperand(1));
7127 break;
7128
7129 case Instruction::Or:
7130 // If bits are being or'd in that are not present in the constant we
7131 // are comparing against, then the comparison could never succeed!
7132 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007133 Constant *NotCI = ConstantExpr::getNot(RHS);
7134 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007135 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007136 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007137 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007138 }
7139 break;
7140
7141 case Instruction::And:
7142 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7143 // If bits are being compared against that are and'd out, then the
7144 // comparison can never succeed!
7145 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007146 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007147 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007148 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007149
7150 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7151 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007152 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007153 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007154 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007155
7156 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007157 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007158 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007159 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007160 ICmpInst::Predicate pred = isICMP_NE ?
7161 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007162 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007163 }
7164
7165 // ((X & ~7) == 0) --> X < 8
7166 if (RHSV == 0 && isHighOnes(BOC)) {
7167 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007168 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007169 ICmpInst::Predicate pred = isICMP_NE ?
7170 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007171 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007172 }
7173 }
7174 default: break;
7175 }
7176 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7177 // Handle icmp {eq|ne} <intrinsic>, intcst.
7178 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007179 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007180 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007181 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007182 return &ICI;
7183 }
7184 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007185 }
7186 return 0;
7187}
7188
7189/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7190/// We only handle extending casts so far.
7191///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007192Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7193 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007194 Value *LHSCIOp = LHSCI->getOperand(0);
7195 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007196 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007197 Value *RHSCIOp;
7198
Chris Lattner8c756c12007-05-05 22:41:33 +00007199 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7200 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007201 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7202 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007203 cast<IntegerType>(DestTy)->getBitWidth()) {
7204 Value *RHSOp = 0;
7205 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007206 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007207 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7208 RHSOp = RHSC->getOperand(0);
7209 // If the pointer types don't match, insert a bitcast.
7210 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007211 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007212 }
7213
7214 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007215 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007216 }
7217
7218 // The code below only handles extension cast instructions, so far.
7219 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007220 if (LHSCI->getOpcode() != Instruction::ZExt &&
7221 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007222 return 0;
7223
Reid Spencere4d87aa2006-12-23 06:05:41 +00007224 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007225 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007226
Reid Spencere4d87aa2006-12-23 06:05:41 +00007227 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007228 // Not an extension from the same type?
7229 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007230 if (RHSCIOp->getType() != LHSCIOp->getType())
7231 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007232
Nick Lewycky4189a532008-01-28 03:48:02 +00007233 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007234 // and the other is a zext), then we can't handle this.
7235 if (CI->getOpcode() != LHSCI->getOpcode())
7236 return 0;
7237
Nick Lewycky4189a532008-01-28 03:48:02 +00007238 // Deal with equality cases early.
7239 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007240 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007241
7242 // A signed comparison of sign extended values simplifies into a
7243 // signed comparison.
7244 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007245 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007246
7247 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007248 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007249 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007250
Reid Spencere4d87aa2006-12-23 06:05:41 +00007251 // If we aren't dealing with a constant on the RHS, exit early
7252 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7253 if (!CI)
7254 return 0;
7255
7256 // Compute the constant that would happen if we truncated to SrcTy then
7257 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007258 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7259 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007260 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007261
7262 // If the re-extended constant didn't change...
7263 if (Res2 == CI) {
7264 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7265 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007266 // %A = sext i16 %X to i32
7267 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007268 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007269 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007270 // because %A may have negative value.
7271 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007272 // However, we allow this when the compare is EQ/NE, because they are
7273 // signless.
7274 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007275 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007276 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007277 }
7278
7279 // The re-extended constant changed so the constant cannot be represented
7280 // in the shorter type. Consequently, we cannot emit a simple comparison.
7281
7282 // First, handle some easy cases. We know the result cannot be equal at this
7283 // point so handle the ICI.isEquality() cases
7284 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007285 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007286 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007287 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007288
7289 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7290 // should have been folded away previously and not enter in here.
7291 Value *Result;
7292 if (isSignedCmp) {
7293 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007294 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007295 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007296 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007297 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007298 } else {
7299 // We're performing an unsigned comparison.
7300 if (isSignedExt) {
7301 // We're performing an unsigned comp with a sign extended value.
7302 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007303 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007304 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007305 } else {
7306 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007307 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007308 }
7309 }
7310
7311 // Finally, return the value computed.
7312 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007313 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007314 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007315
7316 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7317 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7318 "ICmp should be folded!");
7319 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007320 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007321 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007322}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007323
Reid Spencer832254e2007-02-02 02:16:23 +00007324Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7325 return commonShiftTransforms(I);
7326}
7327
7328Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7329 return commonShiftTransforms(I);
7330}
7331
7332Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007333 if (Instruction *R = commonShiftTransforms(I))
7334 return R;
7335
7336 Value *Op0 = I.getOperand(0);
7337
7338 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7339 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7340 if (CSI->isAllOnesValue())
7341 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007342
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007343 // See if we can turn a signed shr into an unsigned shr.
7344 if (MaskedValueIsZero(Op0,
7345 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7346 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7347
7348 // Arithmetic shifting an all-sign-bit value is a no-op.
7349 unsigned NumSignBits = ComputeNumSignBits(Op0);
7350 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7351 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007352
Chris Lattner348f6652007-12-06 01:59:46 +00007353 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007354}
7355
7356Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7357 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007358 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007359
7360 // shl X, 0 == X and shr X, 0 == X
7361 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007362 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7363 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007364 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007365
Reid Spencere4d87aa2006-12-23 06:05:41 +00007366 if (isa<UndefValue>(Op0)) {
7367 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007368 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007369 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007370 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007371 }
7372 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007373 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7374 return ReplaceInstUsesWith(I, Op0);
7375 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007376 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007377 }
7378
Dan Gohman9004c8a2009-05-21 02:28:33 +00007379 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007380 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007381 return &I;
7382
Chris Lattner2eefe512004-04-09 19:05:30 +00007383 // Try to fold constant and into select arguments.
7384 if (isa<Constant>(Op0))
7385 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007386 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007387 return R;
7388
Reid Spencerb83eb642006-10-20 07:07:24 +00007389 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007390 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7391 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007392 return 0;
7393}
7394
Reid Spencerb83eb642006-10-20 07:07:24 +00007395Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007396 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007397 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007398
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007399 // See if we can simplify any instructions used by the instruction whose sole
7400 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007401 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007402
Dan Gohmana119de82009-06-14 23:30:43 +00007403 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7404 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007405 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007406 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007407 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007408 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007409 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007410 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007411 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007412 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007413 }
7414
7415 // ((X*C1) << C2) == (X * (C1 << C2))
7416 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7417 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7418 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007419 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007420 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007421
7422 // Try to fold constant and into select arguments.
7423 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7424 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7425 return R;
7426 if (isa<PHINode>(Op0))
7427 if (Instruction *NV = FoldOpIntoPhi(I))
7428 return NV;
7429
Chris Lattner8999dd32007-12-22 09:07:47 +00007430 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7431 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7432 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7433 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7434 // place. Don't try to do this transformation in this case. Also, we
7435 // require that the input operand is a shift-by-constant so that we have
7436 // confidence that the shifts will get folded together. We could do this
7437 // xform in more cases, but it is unlikely to be profitable.
7438 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7439 isa<ConstantInt>(TrOp->getOperand(1))) {
7440 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007441 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007442 // (shift2 (shift1 & 0x00FF), c2)
7443 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007444
7445 // For logical shifts, the truncation has the effect of making the high
7446 // part of the register be zeros. Emulate this by inserting an AND to
7447 // clear the top bits as needed. This 'and' will usually be zapped by
7448 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007449 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7450 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007451 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7452
7453 // The mask we constructed says what the trunc would do if occurring
7454 // between the shifts. We want to know the effect *after* the second
7455 // shift. We know that it is a logical shift by a constant, so adjust the
7456 // mask as appropriate.
7457 if (I.getOpcode() == Instruction::Shl)
7458 MaskV <<= Op1->getZExtValue();
7459 else {
7460 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7461 MaskV = MaskV.lshr(Op1->getZExtValue());
7462 }
7463
Chris Lattner74381062009-08-30 07:44:24 +00007464 // shift1 & 0x00FF
7465 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7466 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007467
7468 // Return the value truncated to the interesting size.
7469 return new TruncInst(And, I.getType());
7470 }
7471 }
7472
Chris Lattner4d5542c2006-01-06 07:12:35 +00007473 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007474 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7475 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7476 Value *V1, *V2;
7477 ConstantInt *CC;
7478 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007479 default: break;
7480 case Instruction::Add:
7481 case Instruction::And:
7482 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007483 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007484 // These operators commute.
7485 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007486 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007487 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007488 m_Specific(Op1)))) {
7489 Value *YS = // (Y << C)
7490 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7491 // (X + (Y << C))
7492 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7493 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007494 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007495 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007496 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007497 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007498
Chris Lattner150f12a2005-09-18 06:30:59 +00007499 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007500 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007501 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007502 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007503 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007504 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007505 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007506 Value *YS = // (Y << C)
7507 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7508 Op0BO->getName());
7509 // X & (CC << C)
7510 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7511 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007512 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007513 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007514 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007515
Reid Spencera07cb7d2007-02-02 14:41:37 +00007516 // FALL THROUGH.
7517 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007518 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007519 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007520 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007521 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007522 Value *YS = // (Y << C)
7523 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7524 // (X + (Y << C))
7525 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7526 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007527 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007528 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007529 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007530 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007531
Chris Lattner13d4ab42006-05-31 21:14:00 +00007532 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007533 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7534 match(Op0BO->getOperand(0),
7535 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007536 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007537 cast<BinaryOperator>(Op0BO->getOperand(0))
7538 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007539 Value *YS = // (Y << C)
7540 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7541 // X & (CC << C)
7542 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7543 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007544
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007545 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007546 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007547
Chris Lattner11021cb2005-09-18 05:12:10 +00007548 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007549 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007550 }
7551
7552
7553 // If the operand is an bitwise operator with a constant RHS, and the
7554 // shift is the only use, we can pull it out of the shift.
7555 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7556 bool isValid = true; // Valid only for And, Or, Xor
7557 bool highBitSet = false; // Transform if high bit of constant set?
7558
7559 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007560 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007561 case Instruction::Add:
7562 isValid = isLeftShift;
7563 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007564 case Instruction::Or:
7565 case Instruction::Xor:
7566 highBitSet = false;
7567 break;
7568 case Instruction::And:
7569 highBitSet = true;
7570 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007571 }
7572
7573 // If this is a signed shift right, and the high bit is modified
7574 // by the logical operation, do not perform the transformation.
7575 // The highBitSet boolean indicates the value of the high bit of
7576 // the constant which would cause it to be modified for this
7577 // operation.
7578 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007579 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007580 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007581
7582 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007583 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007584
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007585 Value *NewShift =
7586 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007587 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007588
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007589 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007590 NewRHS);
7591 }
7592 }
7593 }
7594 }
7595
Chris Lattnerad0124c2006-01-06 07:52:12 +00007596 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007597 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7598 if (ShiftOp && !ShiftOp->isShift())
7599 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007600
Reid Spencerb83eb642006-10-20 07:07:24 +00007601 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007602 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007603 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7604 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007605 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7606 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7607 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007608
Zhou Sheng4351c642007-04-02 08:20:41 +00007609 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007610
7611 const IntegerType *Ty = cast<IntegerType>(I.getType());
7612
7613 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007614 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007615 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7616 // saturates.
7617 if (AmtSum >= TypeBits) {
7618 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007619 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007620 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7621 }
7622
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007623 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007624 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007625 }
7626
7627 if (ShiftOp->getOpcode() == Instruction::LShr &&
7628 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007629 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007630 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007631
Chris Lattnerb87056f2007-02-05 00:57:54 +00007632 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007633 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007634 }
7635
7636 if (ShiftOp->getOpcode() == Instruction::AShr &&
7637 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007638 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007639 if (AmtSum >= TypeBits)
7640 AmtSum = TypeBits-1;
7641
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007642 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007643
Zhou Shenge9e03f62007-03-28 15:02:20 +00007644 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007645 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007646 }
7647
Chris Lattnerb87056f2007-02-05 00:57:54 +00007648 // Okay, if we get here, one shift must be left, and the other shift must be
7649 // right. See if the amounts are equal.
7650 if (ShiftAmt1 == ShiftAmt2) {
7651 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7652 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007653 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007654 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007655 }
7656 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7657 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007658 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007659 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007660 }
7661 // We can simplify ((X << C) >>s C) into a trunc + sext.
7662 // NOTE: we could do this for any C, but that would make 'unusual' integer
7663 // types. For now, just stick to ones well-supported by the code
7664 // generators.
7665 const Type *SExtType = 0;
7666 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007667 case 1 :
7668 case 8 :
7669 case 16 :
7670 case 32 :
7671 case 64 :
7672 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007673 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007674 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007675 default: break;
7676 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007677 if (SExtType)
7678 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007679 // Otherwise, we can't handle it yet.
7680 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007681 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007682
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007683 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007684 if (I.getOpcode() == Instruction::Shl) {
7685 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7686 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007687 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007688
Reid Spencer55702aa2007-03-25 21:11:44 +00007689 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007690 return BinaryOperator::CreateAnd(Shift,
7691 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007692 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007693
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007694 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007695 if (I.getOpcode() == Instruction::LShr) {
7696 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007697 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007698
Reid Spencerd5e30f02007-03-26 17:18:58 +00007699 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007700 return BinaryOperator::CreateAnd(Shift,
7701 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007702 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007703
7704 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7705 } else {
7706 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007707 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007708
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007709 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007710 if (I.getOpcode() == Instruction::Shl) {
7711 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7712 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007713 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7714 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007715
Reid Spencer55702aa2007-03-25 21:11:44 +00007716 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007717 return BinaryOperator::CreateAnd(Shift,
7718 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007719 }
7720
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007721 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007722 if (I.getOpcode() == Instruction::LShr) {
7723 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007724 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007725
Reid Spencer68d27cf2007-03-26 23:45:51 +00007726 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007727 return BinaryOperator::CreateAnd(Shift,
7728 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007729 }
7730
7731 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007732 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007733 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007734 return 0;
7735}
7736
Chris Lattnera1be5662002-05-02 17:06:02 +00007737
Chris Lattnercfd65102005-10-29 04:36:15 +00007738/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7739/// expression. If so, decompose it, returning some value X, such that Val is
7740/// X*Scale+Offset.
7741///
7742static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007743 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007744 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7745 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007746 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007747 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007748 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007749 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007750 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7751 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7752 if (I->getOpcode() == Instruction::Shl) {
7753 // This is a value scaled by '1 << the shift amt'.
7754 Scale = 1U << RHS->getZExtValue();
7755 Offset = 0;
7756 return I->getOperand(0);
7757 } else if (I->getOpcode() == Instruction::Mul) {
7758 // This value is scaled by 'RHS'.
7759 Scale = RHS->getZExtValue();
7760 Offset = 0;
7761 return I->getOperand(0);
7762 } else if (I->getOpcode() == Instruction::Add) {
7763 // We have X+C. Check to see if we really have (X*C2)+C1,
7764 // where C1 is divisible by C2.
7765 unsigned SubScale;
7766 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007767 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7768 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007769 Offset += RHS->getZExtValue();
7770 Scale = SubScale;
7771 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007772 }
7773 }
7774 }
7775
7776 // Otherwise, we can't look past this.
7777 Scale = 1;
7778 Offset = 0;
7779 return Val;
7780}
7781
7782
Chris Lattnerb3f83972005-10-24 06:03:58 +00007783/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7784/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007785Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00007786 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007787 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007788
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007789 BuilderTy AllocaBuilder(*Builder);
7790 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7791
Chris Lattnerb53c2382005-10-24 06:22:12 +00007792 // Remove any uses of AI that are dead.
7793 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007794
Chris Lattnerb53c2382005-10-24 06:22:12 +00007795 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7796 Instruction *User = cast<Instruction>(*UI++);
7797 if (isInstructionTriviallyDead(User)) {
7798 while (UI != E && *UI == User)
7799 ++UI; // If this instruction uses AI more than once, don't break UI.
7800
Chris Lattnerb53c2382005-10-24 06:22:12 +00007801 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007802 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007803 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007804 }
7805 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007806
7807 // This requires TargetData to get the alloca alignment and size information.
7808 if (!TD) return 0;
7809
Chris Lattnerb3f83972005-10-24 06:03:58 +00007810 // Get the type really allocated and the type casted to.
7811 const Type *AllocElTy = AI.getAllocatedType();
7812 const Type *CastElTy = PTy->getElementType();
7813 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007814
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007815 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7816 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007817 if (CastElTyAlign < AllocElTyAlign) return 0;
7818
Chris Lattner39387a52005-10-24 06:35:18 +00007819 // If the allocation has multiple uses, only promote it if we are strictly
7820 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007821 // same, we open the door to infinite loops of various kinds. (A reference
7822 // from a dbg.declare doesn't count as a use for this purpose.)
7823 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7824 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007825
Duncan Sands777d2302009-05-09 07:06:46 +00007826 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7827 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007828 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007829
Chris Lattner455fcc82005-10-29 03:19:53 +00007830 // See if we can satisfy the modulus by pulling a scale out of the array
7831 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007832 unsigned ArraySizeScale;
7833 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007834 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007835 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7836 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007837
Chris Lattner455fcc82005-10-29 03:19:53 +00007838 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7839 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007840 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7841 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007842
Chris Lattner455fcc82005-10-29 03:19:53 +00007843 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7844 Value *Amt = 0;
7845 if (Scale == 1) {
7846 Amt = NumElements;
7847 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007848 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007849 // Insert before the alloca, not before the cast.
7850 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007851 }
7852
Jeff Cohen86796be2007-04-04 16:58:57 +00007853 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007854 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007855 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007856 }
7857
Victor Hernandez7b929da2009-10-23 21:09:37 +00007858 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007859 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007860 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007861
Dale Johannesena0a66372009-03-05 00:39:02 +00007862 // If the allocation has one real use plus a dbg.declare, just remove the
7863 // declare.
7864 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7865 EraseInstFromFunction(*DI);
7866 }
7867 // If the allocation has multiple real uses, insert a cast and change all
7868 // things that used it to use the new cast. This will also hack on CI, but it
7869 // will die soon.
7870 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007871 // New is the allocation instruction, pointer typed. AI is the original
7872 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007873 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007874 AI.replaceAllUsesWith(NewCast);
7875 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007876 return ReplaceInstUsesWith(CI, New);
7877}
7878
Chris Lattner70074e02006-05-13 02:06:03 +00007879/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007880/// and return it as type Ty without inserting any new casts and without
7881/// changing the computed value. This is used by code that tries to decide
7882/// whether promoting or shrinking integer operations to wider or smaller types
7883/// will allow us to eliminate a truncate or extend.
7884///
7885/// This is a truncation operation if Ty is smaller than V->getType(), or an
7886/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007887///
7888/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7889/// should return true if trunc(V) can be computed by computing V in the smaller
7890/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7891/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7892/// efficiently truncated.
7893///
7894/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7895/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7896/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007897bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007898 unsigned CastOpc,
7899 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007900 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007901 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007902 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007903
7904 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007905 if (!I) return false;
7906
Dan Gohman6de29f82009-06-15 22:12:54 +00007907 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007908
Chris Lattner951626b2007-08-02 06:11:14 +00007909 // If this is an extension or truncate, we can often eliminate it.
7910 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7911 // If this is a cast from the destination type, we can trivially eliminate
7912 // it, and this will remove a cast overall.
7913 if (I->getOperand(0)->getType() == Ty) {
7914 // If the first operand is itself a cast, and is eliminable, do not count
7915 // this as an eliminable cast. We would prefer to eliminate those two
7916 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007917 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007918 ++NumCastsRemoved;
7919 return true;
7920 }
7921 }
7922
7923 // We can't extend or shrink something that has multiple uses: doing so would
7924 // require duplicating the instruction in general, which isn't profitable.
7925 if (!I->hasOneUse()) return false;
7926
Evan Chengf35fd542009-01-15 17:01:23 +00007927 unsigned Opc = I->getOpcode();
7928 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007929 case Instruction::Add:
7930 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007931 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007932 case Instruction::And:
7933 case Instruction::Or:
7934 case Instruction::Xor:
7935 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007936 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007937 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007938 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007939 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007940
Eli Friedman070a9812009-07-13 22:46:01 +00007941 case Instruction::UDiv:
7942 case Instruction::URem: {
7943 // UDiv and URem can be truncated if all the truncated bits are zero.
7944 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7945 uint32_t BitWidth = Ty->getScalarSizeInBits();
7946 if (BitWidth < OrigBitWidth) {
7947 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7948 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7949 MaskedValueIsZero(I->getOperand(1), Mask)) {
7950 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7951 NumCastsRemoved) &&
7952 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7953 NumCastsRemoved);
7954 }
7955 }
7956 break;
7957 }
Chris Lattner46b96052006-11-29 07:18:39 +00007958 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007959 // If we are truncating the result of this SHL, and if it's a shift of a
7960 // constant amount, we can always perform a SHL in a smaller type.
7961 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007962 uint32_t BitWidth = Ty->getScalarSizeInBits();
7963 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007964 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007965 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007966 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007967 }
7968 break;
7969 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007970 // If this is a truncate of a logical shr, we can truncate it to a smaller
7971 // lshr iff we know that the bits we would otherwise be shifting in are
7972 // already zeros.
7973 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007974 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7975 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007976 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007977 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007978 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7979 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007980 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007981 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007982 }
7983 }
Chris Lattner46b96052006-11-29 07:18:39 +00007984 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007985 case Instruction::ZExt:
7986 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007987 case Instruction::Trunc:
7988 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007989 // can safely replace it. Note that replacing it does not reduce the number
7990 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007991 if (Opc == CastOpc)
7992 return true;
7993
7994 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007995 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007996 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007997 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007998 case Instruction::Select: {
7999 SelectInst *SI = cast<SelectInst>(I);
8000 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008001 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008002 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008003 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008004 }
Chris Lattner8114b712008-06-18 04:00:49 +00008005 case Instruction::PHI: {
8006 // We can change a phi if we can change all operands.
8007 PHINode *PN = cast<PHINode>(I);
8008 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8009 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008010 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008011 return false;
8012 return true;
8013 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008014 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008015 // TODO: Can handle more cases here.
8016 break;
8017 }
8018
8019 return false;
8020}
8021
8022/// EvaluateInDifferentType - Given an expression that
8023/// CanEvaluateInDifferentType returns true for, actually insert the code to
8024/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008025Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008026 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008027 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00008028 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00008029 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008030
8031 // Otherwise, it must be an instruction.
8032 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008033 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008034 unsigned Opc = I->getOpcode();
8035 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008036 case Instruction::Add:
8037 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008038 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008039 case Instruction::And:
8040 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008041 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008042 case Instruction::AShr:
8043 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008044 case Instruction::Shl:
8045 case Instruction::UDiv:
8046 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008047 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008048 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008049 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008050 break;
8051 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008052 case Instruction::Trunc:
8053 case Instruction::ZExt:
8054 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008055 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008056 // just return the source. There's no need to insert it because it is not
8057 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008058 if (I->getOperand(0)->getType() == Ty)
8059 return I->getOperand(0);
8060
Chris Lattner8114b712008-06-18 04:00:49 +00008061 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008062 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008063 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008064 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008065 case Instruction::Select: {
8066 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8067 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8068 Res = SelectInst::Create(I->getOperand(0), True, False);
8069 break;
8070 }
Chris Lattner8114b712008-06-18 04:00:49 +00008071 case Instruction::PHI: {
8072 PHINode *OPN = cast<PHINode>(I);
8073 PHINode *NPN = PHINode::Create(Ty);
8074 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8075 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8076 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8077 }
8078 Res = NPN;
8079 break;
8080 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008081 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008082 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008083 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008084 break;
8085 }
8086
Chris Lattner8114b712008-06-18 04:00:49 +00008087 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008088 return InsertNewInstBefore(Res, *I);
8089}
8090
Reid Spencer3da59db2006-11-27 01:05:10 +00008091/// @brief Implement the transforms common to all CastInst visitors.
8092Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008093 Value *Src = CI.getOperand(0);
8094
Dan Gohman23d9d272007-05-11 21:10:54 +00008095 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008096 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008097 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008098 if (Instruction::CastOps opc =
8099 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8100 // The first cast (CSrc) is eliminable so we need to fix up or replace
8101 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008102 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008103 }
8104 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008105
Reid Spencer3da59db2006-11-27 01:05:10 +00008106 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008107 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8108 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8109 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008110
8111 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008112 if (isa<PHINode>(Src))
8113 if (Instruction *NV = FoldOpIntoPhi(CI))
8114 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008115
Reid Spencer3da59db2006-11-27 01:05:10 +00008116 return 0;
8117}
8118
Chris Lattner46cd5a12009-01-09 05:44:56 +00008119/// FindElementAtOffset - Given a type and a constant offset, determine whether
8120/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008121/// the specified offset. If so, fill them into NewIndices and return the
8122/// resultant element type, otherwise return null.
8123static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8124 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008125 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008126 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008127 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008128 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008129
8130 // Start with the index over the outer type. Note that the type size
8131 // might be zero (even if the offset isn't zero) if the indexed type
8132 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008133 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008134 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008135 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008136 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008137 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008138
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008139 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008140 if (Offset < 0) {
8141 --FirstIdx;
8142 Offset += TySize;
8143 assert(Offset >= 0);
8144 }
8145 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8146 }
8147
Owen Andersoneed707b2009-07-24 23:12:02 +00008148 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008149
8150 // Index into the types. If we fail, set OrigBase to null.
8151 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008152 // Indexing into tail padding between struct/array elements.
8153 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008154 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008155
Chris Lattner46cd5a12009-01-09 05:44:56 +00008156 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8157 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008158 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8159 "Offset must stay within the indexed type");
8160
Chris Lattner46cd5a12009-01-09 05:44:56 +00008161 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008162 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008163
8164 Offset -= SL->getElementOffset(Elt);
8165 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008166 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008167 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008168 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008169 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008170 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008171 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008172 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008173 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008174 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008175 }
8176 }
8177
Chris Lattner3914f722009-01-24 01:00:13 +00008178 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008179}
8180
Chris Lattnerd3e28342007-04-27 17:44:50 +00008181/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8182Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8183 Value *Src = CI.getOperand(0);
8184
Chris Lattnerd3e28342007-04-27 17:44:50 +00008185 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008186 // If casting the result of a getelementptr instruction with no offset, turn
8187 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008188 if (GEP->hasAllZeroIndices()) {
8189 // Changing the cast operand is usually not a good idea but it is safe
8190 // here because the pointer operand is being replaced with another
8191 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008192 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008193 CI.setOperand(0, GEP->getOperand(0));
8194 return &CI;
8195 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008196
8197 // If the GEP has a single use, and the base pointer is a bitcast, and the
8198 // GEP computes a constant offset, see if we can convert these three
8199 // instructions into fewer. This typically happens with unions and other
8200 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008201 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008202 if (GEP->hasAllConstantIndices()) {
8203 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008204 ConstantInt *OffsetV =
8205 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008206 int64_t Offset = OffsetV->getSExtValue();
8207
8208 // Get the base pointer input of the bitcast, and the type it points to.
8209 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8210 const Type *GEPIdxTy =
8211 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008212 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008213 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008214 // If we were able to index down into an element, create the GEP
8215 // and bitcast the result. This eliminates one bitcast, potentially
8216 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008217 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8218 Builder->CreateInBoundsGEP(OrigBase,
8219 NewIndices.begin(), NewIndices.end()) :
8220 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008221 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008222
Chris Lattner46cd5a12009-01-09 05:44:56 +00008223 if (isa<BitCastInst>(CI))
8224 return new BitCastInst(NGEP, CI.getType());
8225 assert(isa<PtrToIntInst>(CI));
8226 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008227 }
8228 }
8229 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008230 }
8231
8232 return commonCastTransforms(CI);
8233}
8234
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008235/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8236/// type like i42. We don't want to introduce operations on random non-legal
8237/// integer types where they don't already exist in the code. In the future,
8238/// we should consider making this based off target-data, so that 32-bit targets
8239/// won't get i64 operations etc.
8240static bool isSafeIntegerType(const Type *Ty) {
8241 switch (Ty->getPrimitiveSizeInBits()) {
8242 case 8:
8243 case 16:
8244 case 32:
8245 case 64:
8246 return true;
8247 default:
8248 return false;
8249 }
8250}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008251
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008252/// commonIntCastTransforms - This function implements the common transforms
8253/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008254Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8255 if (Instruction *Result = commonCastTransforms(CI))
8256 return Result;
8257
8258 Value *Src = CI.getOperand(0);
8259 const Type *SrcTy = Src->getType();
8260 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008261 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8262 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008263
Reid Spencer3da59db2006-11-27 01:05:10 +00008264 // See if we can simplify any instructions used by the LHS whose sole
8265 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008266 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008267 return &CI;
8268
8269 // If the source isn't an instruction or has more than one use then we
8270 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008271 Instruction *SrcI = dyn_cast<Instruction>(Src);
8272 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008273 return 0;
8274
Chris Lattnerc739cd62007-03-03 05:27:34 +00008275 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008276 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008277 // Only do this if the dest type is a simple type, don't convert the
8278 // expression tree to something weird like i93 unless the source is also
8279 // strange.
8280 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008281 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8282 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008283 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008284 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008285 // eliminates the cast, so it is always a win. If this is a zero-extension,
8286 // we need to do an AND to maintain the clear top-part of the computation,
8287 // so we require that the input have eliminated at least one cast. If this
8288 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008289 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008290 bool DoXForm = false;
8291 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008292 switch (CI.getOpcode()) {
8293 default:
8294 // All the others use floating point so we shouldn't actually
8295 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008296 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008297 case Instruction::Trunc:
8298 DoXForm = true;
8299 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008300 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008301 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008302 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008303 // If it's unnecessary to issue an AND to clear the high bits, it's
8304 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008305 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008306 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8307 if (MaskedValueIsZero(TryRes, Mask))
8308 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008309
8310 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008311 if (TryI->use_empty())
8312 EraseInstFromFunction(*TryI);
8313 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008314 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008315 }
Evan Chengf35fd542009-01-15 17:01:23 +00008316 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008317 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008318 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008319 // If we do not have to emit the truncate + sext pair, then it's always
8320 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008321 //
8322 // It's not safe to eliminate the trunc + sext pair if one of the
8323 // eliminated cast is a truncate. e.g.
8324 // t2 = trunc i32 t1 to i16
8325 // t3 = sext i16 t2 to i32
8326 // !=
8327 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008328 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008329 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8330 if (NumSignBits > (DestBitSize - SrcBitSize))
8331 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008332
8333 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008334 if (TryI->use_empty())
8335 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008336 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008337 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008338 }
Evan Chengf35fd542009-01-15 17:01:23 +00008339 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008340
8341 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008342 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8343 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008344 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8345 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008346 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008347 // Just replace this cast with the result.
8348 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008349
Reid Spencer3da59db2006-11-27 01:05:10 +00008350 assert(Res->getType() == DestTy);
8351 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008352 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008353 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008354 // Just replace this cast with the result.
8355 return ReplaceInstUsesWith(CI, Res);
8356 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008357 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008358
8359 // If the high bits are already zero, just replace this cast with the
8360 // result.
8361 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8362 if (MaskedValueIsZero(Res, Mask))
8363 return ReplaceInstUsesWith(CI, Res);
8364
8365 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008366 Constant *C = ConstantInt::get(*Context,
8367 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008368 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008369 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008370 case Instruction::SExt: {
8371 // If the high bits are already filled with sign bit, just replace this
8372 // cast with the result.
8373 unsigned NumSignBits = ComputeNumSignBits(Res);
8374 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008375 return ReplaceInstUsesWith(CI, Res);
8376
Reid Spencer3da59db2006-11-27 01:05:10 +00008377 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008378 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008379 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008380 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008381 }
8382 }
8383
8384 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8385 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8386
8387 switch (SrcI->getOpcode()) {
8388 case Instruction::Add:
8389 case Instruction::Mul:
8390 case Instruction::And:
8391 case Instruction::Or:
8392 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008393 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008394 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8395 // Don't insert two casts unless at least one can be eliminated.
8396 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008397 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008398 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8399 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008400 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008401 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008402 }
8403 }
8404
8405 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8406 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8407 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008408 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008409 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008410 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008411 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008412 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008413 }
8414 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008415
Eli Friedman65445c52009-07-13 21:45:57 +00008416 case Instruction::Shl: {
8417 // Canonicalize trunc inside shl, if we can.
8418 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8419 if (CI && DestBitSize < SrcBitSize &&
8420 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008421 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8422 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008423 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008424 }
8425 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008426 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008427 }
8428 return 0;
8429}
8430
Chris Lattner8a9f5712007-04-11 06:57:46 +00008431Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008432 if (Instruction *Result = commonIntCastTransforms(CI))
8433 return Result;
8434
8435 Value *Src = CI.getOperand(0);
8436 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008437 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8438 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008439
8440 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008441 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008442 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008443 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008444 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008445 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008446 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008447
Chris Lattner4f9797d2009-03-24 18:15:30 +00008448 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8449 ConstantInt *ShAmtV = 0;
8450 Value *ShiftOp = 0;
8451 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008452 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008453 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8454
8455 // Get a mask for the bits shifting in.
8456 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8457 if (MaskedValueIsZero(ShiftOp, Mask)) {
8458 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008459 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008460
8461 // Okay, we can shrink this. Truncate the input, then return a new
8462 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008463 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008464 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008465 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008466 }
8467 }
8468
8469 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008470}
8471
Evan Chengb98a10e2008-03-24 00:21:34 +00008472/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8473/// in order to eliminate the icmp.
8474Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8475 bool DoXform) {
8476 // If we are just checking for a icmp eq of a single bit and zext'ing it
8477 // to an integer, then shift the bit to the appropriate place and then
8478 // cast to integer to avoid the comparison.
8479 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8480 const APInt &Op1CV = Op1C->getValue();
8481
8482 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8483 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8484 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8485 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8486 if (!DoXform) return ICI;
8487
8488 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008489 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008490 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008491 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008492 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008493 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008494
8495 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008496 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008497 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008498 }
8499
8500 return ReplaceInstUsesWith(CI, In);
8501 }
8502
8503
8504
8505 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8506 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8507 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8508 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8509 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8510 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8511 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8512 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8513 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8514 // This only works for EQ and NE
8515 ICI->isEquality()) {
8516 // If Op1C some other power of two, convert:
8517 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8518 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8519 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8520 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8521
8522 APInt KnownZeroMask(~KnownZero);
8523 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8524 if (!DoXform) return ICI;
8525
8526 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8527 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8528 // (X&4) == 2 --> false
8529 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008530 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008531 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008532 return ReplaceInstUsesWith(CI, Res);
8533 }
8534
8535 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8536 Value *In = ICI->getOperand(0);
8537 if (ShiftAmt) {
8538 // Perform a logical shr by shiftamt.
8539 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008540 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8541 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008542 }
8543
8544 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008545 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008546 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008547 }
8548
8549 if (CI.getType() == In->getType())
8550 return ReplaceInstUsesWith(CI, In);
8551 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008552 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008553 }
8554 }
8555 }
8556
8557 return 0;
8558}
8559
Chris Lattner8a9f5712007-04-11 06:57:46 +00008560Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008561 // If one of the common conversion will work ..
8562 if (Instruction *Result = commonIntCastTransforms(CI))
8563 return Result;
8564
8565 Value *Src = CI.getOperand(0);
8566
Chris Lattnera84f47c2009-02-17 20:47:23 +00008567 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8568 // types and if the sizes are just right we can convert this into a logical
8569 // 'and' which will be much cheaper than the pair of casts.
8570 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8571 // Get the sizes of the types involved. We know that the intermediate type
8572 // will be smaller than A or C, but don't know the relation between A and C.
8573 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008574 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8575 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8576 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008577 // If we're actually extending zero bits, then if
8578 // SrcSize < DstSize: zext(a & mask)
8579 // SrcSize == DstSize: a & mask
8580 // SrcSize > DstSize: trunc(a) & mask
8581 if (SrcSize < DstSize) {
8582 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008583 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008584 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008585 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008586 }
8587
8588 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008589 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008590 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008591 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008592 }
8593 if (SrcSize > DstSize) {
8594 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008595 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008596 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008597 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008598 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008599 }
8600 }
8601
Evan Chengb98a10e2008-03-24 00:21:34 +00008602 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8603 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008604
Evan Chengb98a10e2008-03-24 00:21:34 +00008605 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8606 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8607 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8608 // of the (zext icmp) will be transformed.
8609 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8610 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8611 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8612 (transformZExtICmp(LHS, CI, false) ||
8613 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008614 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8615 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008616 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008617 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008618 }
8619
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008620 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008621 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8622 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8623 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8624 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008625 if (TI0->getType() == CI.getType())
8626 return
8627 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008628 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008629 }
8630
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008631 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8632 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8633 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8634 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8635 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8636 And->getOperand(1) == C)
8637 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8638 Value *TI0 = TI->getOperand(0);
8639 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008640 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008641 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008642 return BinaryOperator::CreateXor(NewAnd, ZC);
8643 }
8644 }
8645
Reid Spencer3da59db2006-11-27 01:05:10 +00008646 return 0;
8647}
8648
Chris Lattner8a9f5712007-04-11 06:57:46 +00008649Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008650 if (Instruction *I = commonIntCastTransforms(CI))
8651 return I;
8652
Chris Lattner8a9f5712007-04-11 06:57:46 +00008653 Value *Src = CI.getOperand(0);
8654
Dan Gohman1975d032008-10-30 20:40:10 +00008655 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008656 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008657 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008658 Constant::getAllOnesValue(CI.getType()),
8659 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008660
8661 // See if the value being truncated is already sign extended. If so, just
8662 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008663 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008664 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008665 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8666 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8667 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008668 unsigned NumSignBits = ComputeNumSignBits(Op);
8669
8670 if (OpBits == DestBits) {
8671 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8672 // bits, it is already ready.
8673 if (NumSignBits > DestBits-MidBits)
8674 return ReplaceInstUsesWith(CI, Op);
8675 } else if (OpBits < DestBits) {
8676 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8677 // bits, just sext from i32.
8678 if (NumSignBits > OpBits-MidBits)
8679 return new SExtInst(Op, CI.getType(), "tmp");
8680 } else {
8681 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8682 // bits, just truncate to i32.
8683 if (NumSignBits > OpBits-MidBits)
8684 return new TruncInst(Op, CI.getType(), "tmp");
8685 }
8686 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008687
8688 // If the input is a shl/ashr pair of a same constant, then this is a sign
8689 // extension from a smaller value. If we could trust arbitrary bitwidth
8690 // integers, we could turn this into a truncate to the smaller bit and then
8691 // use a sext for the whole extension. Since we don't, look deeper and check
8692 // for a truncate. If the source and dest are the same type, eliminate the
8693 // trunc and extend and just do shifts. For example, turn:
8694 // %a = trunc i32 %i to i8
8695 // %b = shl i8 %a, 6
8696 // %c = ashr i8 %b, 6
8697 // %d = sext i8 %c to i32
8698 // into:
8699 // %a = shl i32 %i, 30
8700 // %d = ashr i32 %a, 30
8701 Value *A = 0;
8702 ConstantInt *BA = 0, *CA = 0;
8703 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008704 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008705 BA == CA && isa<TruncInst>(A)) {
8706 Value *I = cast<TruncInst>(A)->getOperand(0);
8707 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008708 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8709 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008710 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008711 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008712 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008713 return BinaryOperator::CreateAShr(I, ShAmtV);
8714 }
8715 }
8716
Chris Lattnerba417832007-04-11 06:12:58 +00008717 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008718}
8719
Chris Lattnerb7530652008-01-27 05:29:54 +00008720/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8721/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008722static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008723 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008724 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008725 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008726 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8727 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008728 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008729 return 0;
8730}
8731
8732/// LookThroughFPExtensions - If this is an fp extension instruction, look
8733/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008734static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008735 if (Instruction *I = dyn_cast<Instruction>(V))
8736 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008737 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008738
8739 // If this value is a constant, return the constant in the smallest FP type
8740 // that can accurately represent it. This allows us to turn
8741 // (float)((double)X+2.0) into x+2.0f.
8742 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008743 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008744 return V; // No constant folding of this.
8745 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008746 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008747 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008748 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008749 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008750 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008751 return V;
8752 // Don't try to shrink to various long double types.
8753 }
8754
8755 return V;
8756}
8757
8758Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8759 if (Instruction *I = commonCastTransforms(CI))
8760 return I;
8761
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008762 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008763 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008764 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008765 // many builtins (sqrt, etc).
8766 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8767 if (OpI && OpI->hasOneUse()) {
8768 switch (OpI->getOpcode()) {
8769 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008770 case Instruction::FAdd:
8771 case Instruction::FSub:
8772 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008773 case Instruction::FDiv:
8774 case Instruction::FRem:
8775 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008776 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8777 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008778 if (LHSTrunc->getType() != SrcTy &&
8779 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008780 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008781 // If the source types were both smaller than the destination type of
8782 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008783 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8784 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008785 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8786 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008787 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008788 }
8789 }
8790 break;
8791 }
8792 }
8793 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008794}
8795
8796Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8797 return commonCastTransforms(CI);
8798}
8799
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008800Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008801 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8802 if (OpI == 0)
8803 return commonCastTransforms(FI);
8804
8805 // fptoui(uitofp(X)) --> X
8806 // fptoui(sitofp(X)) --> X
8807 // This is safe if the intermediate type has enough bits in its mantissa to
8808 // accurately represent all values of X. For example, do not do this with
8809 // i64->float->i64. This is also safe for sitofp case, because any negative
8810 // 'X' value would cause an undefined result for the fptoui.
8811 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8812 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008813 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008814 OpI->getType()->getFPMantissaWidth())
8815 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008816
8817 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008818}
8819
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008820Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008821 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8822 if (OpI == 0)
8823 return commonCastTransforms(FI);
8824
8825 // fptosi(sitofp(X)) --> X
8826 // fptosi(uitofp(X)) --> X
8827 // This is safe if the intermediate type has enough bits in its mantissa to
8828 // accurately represent all values of X. For example, do not do this with
8829 // i64->float->i64. This is also safe for sitofp case, because any negative
8830 // 'X' value would cause an undefined result for the fptoui.
8831 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8832 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008833 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008834 OpI->getType()->getFPMantissaWidth())
8835 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008836
8837 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008838}
8839
8840Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8841 return commonCastTransforms(CI);
8842}
8843
8844Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8845 return commonCastTransforms(CI);
8846}
8847
Chris Lattnera0e69692009-03-24 18:35:40 +00008848Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8849 // If the destination integer type is smaller than the intptr_t type for
8850 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8851 // trunc to be exposed to other transforms. Don't do this for extending
8852 // ptrtoint's, because we don't know if the target sign or zero extends its
8853 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008854 if (TD &&
8855 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008856 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8857 TD->getIntPtrType(CI.getContext()),
8858 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008859 return new TruncInst(P, CI.getType());
8860 }
8861
Chris Lattnerd3e28342007-04-27 17:44:50 +00008862 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008863}
8864
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008865Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008866 // If the source integer type is larger than the intptr_t type for
8867 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8868 // allows the trunc to be exposed to other transforms. Don't do this for
8869 // extending inttoptr's, because we don't know if the target sign or zero
8870 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008871 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008872 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008873 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8874 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008875 return new IntToPtrInst(P, CI.getType());
8876 }
8877
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008878 if (Instruction *I = commonCastTransforms(CI))
8879 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008880
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008881 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008882}
8883
Chris Lattnerd3e28342007-04-27 17:44:50 +00008884Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008885 // If the operands are integer typed then apply the integer transforms,
8886 // otherwise just apply the common ones.
8887 Value *Src = CI.getOperand(0);
8888 const Type *SrcTy = Src->getType();
8889 const Type *DestTy = CI.getType();
8890
Eli Friedman7e25d452009-07-13 20:53:00 +00008891 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008892 if (Instruction *I = commonPointerCastTransforms(CI))
8893 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008894 } else {
8895 if (Instruction *Result = commonCastTransforms(CI))
8896 return Result;
8897 }
8898
8899
8900 // Get rid of casts from one type to the same type. These are useless and can
8901 // be replaced by the operand.
8902 if (DestTy == Src->getType())
8903 return ReplaceInstUsesWith(CI, Src);
8904
Reid Spencer3da59db2006-11-27 01:05:10 +00008905 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008906 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8907 const Type *DstElTy = DstPTy->getElementType();
8908 const Type *SrcElTy = SrcPTy->getElementType();
8909
Nate Begeman83ad90a2008-03-31 00:22:16 +00008910 // If the address spaces don't match, don't eliminate the bitcast, which is
8911 // required for changing types.
8912 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8913 return 0;
8914
Victor Hernandez83d63912009-09-18 22:35:49 +00008915 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008916 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008917 // There is no need to modify malloc calls because it is their bitcast that
8918 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00008919 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00008920 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8921 return V;
8922
Chris Lattnerd717c182007-05-05 22:32:24 +00008923 // If the source and destination are pointers, and this cast is equivalent
8924 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008925 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008926 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008927 unsigned NumZeros = 0;
8928 while (SrcElTy != DstElTy &&
8929 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8930 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8931 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8932 ++NumZeros;
8933 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008934
Chris Lattnerd3e28342007-04-27 17:44:50 +00008935 // If we found a path from the src to dest, create the getelementptr now.
8936 if (SrcElTy == DstElTy) {
8937 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008938 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8939 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008940 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008941 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008942
Eli Friedman2451a642009-07-18 23:06:53 +00008943 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8944 if (DestVTy->getNumElements() == 1) {
8945 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008946 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008947 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008948 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008949 }
8950 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8951 }
8952 }
8953
8954 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8955 if (SrcVTy->getNumElements() == 1) {
8956 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008957 Value *Elem =
8958 Builder->CreateExtractElement(Src,
8959 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008960 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8961 }
8962 }
8963 }
8964
Reid Spencer3da59db2006-11-27 01:05:10 +00008965 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8966 if (SVI->hasOneUse()) {
8967 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8968 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008969 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008970 cast<VectorType>(DestTy)->getNumElements() ==
8971 SVI->getType()->getNumElements() &&
8972 SVI->getType()->getNumElements() ==
8973 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008974 CastInst *Tmp;
8975 // If either of the operands is a cast from CI.getType(), then
8976 // evaluating the shuffle in the casted destination's type will allow
8977 // us to eliminate at least one cast.
8978 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8979 Tmp->getOperand(0)->getType() == DestTy) ||
8980 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8981 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008982 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8983 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008984 // Return a new shuffle vector. Use the same element ID's, as we
8985 // know the vector types match #elts.
8986 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008987 }
8988 }
8989 }
8990 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008991 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008992}
8993
Chris Lattnere576b912004-04-09 23:46:01 +00008994/// GetSelectFoldableOperands - We want to turn code that looks like this:
8995/// %C = or %A, %B
8996/// %D = select %cond, %C, %A
8997/// into:
8998/// %C = select %cond, %B, 0
8999/// %D = or %A, %C
9000///
9001/// Assuming that the specified instruction is an operand to the select, return
9002/// a bitmask indicating which operands of this instruction are foldable if they
9003/// equal the other incoming value of the select.
9004///
9005static unsigned GetSelectFoldableOperands(Instruction *I) {
9006 switch (I->getOpcode()) {
9007 case Instruction::Add:
9008 case Instruction::Mul:
9009 case Instruction::And:
9010 case Instruction::Or:
9011 case Instruction::Xor:
9012 return 3; // Can fold through either operand.
9013 case Instruction::Sub: // Can only fold on the amount subtracted.
9014 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009015 case Instruction::LShr:
9016 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009017 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009018 default:
9019 return 0; // Cannot fold
9020 }
9021}
9022
9023/// GetSelectFoldableConstant - For the same transformation as the previous
9024/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009025static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009026 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009027 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009028 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009029 case Instruction::Add:
9030 case Instruction::Sub:
9031 case Instruction::Or:
9032 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009033 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009034 case Instruction::LShr:
9035 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009036 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009037 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009038 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009039 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009040 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009041 }
9042}
9043
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009044/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9045/// have the same opcode and only one use each. Try to simplify this.
9046Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9047 Instruction *FI) {
9048 if (TI->getNumOperands() == 1) {
9049 // If this is a non-volatile load or a cast from the same type,
9050 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009051 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009052 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9053 return 0;
9054 } else {
9055 return 0; // unknown unary op.
9056 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009057
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009058 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009059 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009060 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009061 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009062 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009063 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009064 }
9065
Reid Spencer832254e2007-02-02 02:16:23 +00009066 // Only handle binary operators here.
9067 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009068 return 0;
9069
9070 // Figure out if the operations have any operands in common.
9071 Value *MatchOp, *OtherOpT, *OtherOpF;
9072 bool MatchIsOpZero;
9073 if (TI->getOperand(0) == FI->getOperand(0)) {
9074 MatchOp = TI->getOperand(0);
9075 OtherOpT = TI->getOperand(1);
9076 OtherOpF = FI->getOperand(1);
9077 MatchIsOpZero = true;
9078 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9079 MatchOp = TI->getOperand(1);
9080 OtherOpT = TI->getOperand(0);
9081 OtherOpF = FI->getOperand(0);
9082 MatchIsOpZero = false;
9083 } else if (!TI->isCommutative()) {
9084 return 0;
9085 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9086 MatchOp = TI->getOperand(0);
9087 OtherOpT = TI->getOperand(1);
9088 OtherOpF = FI->getOperand(0);
9089 MatchIsOpZero = true;
9090 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9091 MatchOp = TI->getOperand(1);
9092 OtherOpT = TI->getOperand(0);
9093 OtherOpF = FI->getOperand(1);
9094 MatchIsOpZero = true;
9095 } else {
9096 return 0;
9097 }
9098
9099 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009100 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9101 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009102 InsertNewInstBefore(NewSI, SI);
9103
9104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9105 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009106 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009107 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009108 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009109 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009110 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009111 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009112}
9113
Evan Chengde621922009-03-31 20:42:45 +00009114static bool isSelect01(Constant *C1, Constant *C2) {
9115 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9116 if (!C1I)
9117 return false;
9118 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9119 if (!C2I)
9120 return false;
9121 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9122}
9123
9124/// FoldSelectIntoOp - Try fold the select into one of the operands to
9125/// facilitate further optimization.
9126Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9127 Value *FalseVal) {
9128 // See the comment above GetSelectFoldableOperands for a description of the
9129 // transformation we are doing here.
9130 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9131 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9132 !isa<Constant>(FalseVal)) {
9133 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9134 unsigned OpToFold = 0;
9135 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9136 OpToFold = 1;
9137 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9138 OpToFold = 2;
9139 }
9140
9141 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009142 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009143 Value *OOp = TVI->getOperand(2-OpToFold);
9144 // Avoid creating select between 2 constants unless it's selecting
9145 // between 0 and 1.
9146 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9147 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9148 InsertNewInstBefore(NewSel, SI);
9149 NewSel->takeName(TVI);
9150 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9151 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009152 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009153 }
9154 }
9155 }
9156 }
9157 }
9158
9159 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9160 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9161 !isa<Constant>(TrueVal)) {
9162 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9163 unsigned OpToFold = 0;
9164 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9165 OpToFold = 1;
9166 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9167 OpToFold = 2;
9168 }
9169
9170 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009171 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009172 Value *OOp = FVI->getOperand(2-OpToFold);
9173 // Avoid creating select between 2 constants unless it's selecting
9174 // between 0 and 1.
9175 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9176 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9177 InsertNewInstBefore(NewSel, SI);
9178 NewSel->takeName(FVI);
9179 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9180 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009181 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009182 }
9183 }
9184 }
9185 }
9186 }
9187
9188 return 0;
9189}
9190
Dan Gohman81b28ce2008-09-16 18:46:06 +00009191/// visitSelectInstWithICmp - Visit a SelectInst that has an
9192/// ICmpInst as its first operand.
9193///
9194Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9195 ICmpInst *ICI) {
9196 bool Changed = false;
9197 ICmpInst::Predicate Pred = ICI->getPredicate();
9198 Value *CmpLHS = ICI->getOperand(0);
9199 Value *CmpRHS = ICI->getOperand(1);
9200 Value *TrueVal = SI.getTrueValue();
9201 Value *FalseVal = SI.getFalseValue();
9202
9203 // Check cases where the comparison is with a constant that
9204 // can be adjusted to fit the min/max idiom. We may edit ICI in
9205 // place here, so make sure the select is the only user.
9206 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009207 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009208 switch (Pred) {
9209 default: break;
9210 case ICmpInst::ICMP_ULT:
9211 case ICmpInst::ICMP_SLT: {
9212 // X < MIN ? T : F --> F
9213 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9214 return ReplaceInstUsesWith(SI, FalseVal);
9215 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009216 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009217 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9218 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9219 Pred = ICmpInst::getSwappedPredicate(Pred);
9220 CmpRHS = AdjustedRHS;
9221 std::swap(FalseVal, TrueVal);
9222 ICI->setPredicate(Pred);
9223 ICI->setOperand(1, CmpRHS);
9224 SI.setOperand(1, TrueVal);
9225 SI.setOperand(2, FalseVal);
9226 Changed = true;
9227 }
9228 break;
9229 }
9230 case ICmpInst::ICMP_UGT:
9231 case ICmpInst::ICMP_SGT: {
9232 // X > MAX ? T : F --> F
9233 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9234 return ReplaceInstUsesWith(SI, FalseVal);
9235 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009236 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009237 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9238 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9239 Pred = ICmpInst::getSwappedPredicate(Pred);
9240 CmpRHS = AdjustedRHS;
9241 std::swap(FalseVal, TrueVal);
9242 ICI->setPredicate(Pred);
9243 ICI->setOperand(1, CmpRHS);
9244 SI.setOperand(1, TrueVal);
9245 SI.setOperand(2, FalseVal);
9246 Changed = true;
9247 }
9248 break;
9249 }
9250 }
9251
Dan Gohman1975d032008-10-30 20:40:10 +00009252 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9253 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009254 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009255 if (match(TrueVal, m_ConstantInt<-1>()) &&
9256 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009257 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009258 else if (match(TrueVal, m_ConstantInt<0>()) &&
9259 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009260 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9261
Dan Gohman1975d032008-10-30 20:40:10 +00009262 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9263 // If we are just checking for a icmp eq of a single bit and zext'ing it
9264 // to an integer, then shift the bit to the appropriate place and then
9265 // cast to integer to avoid the comparison.
9266 const APInt &Op1CV = CI->getValue();
9267
9268 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9269 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9270 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009271 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009272 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009273 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009274 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009275 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009276 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009277 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009278 if (In->getType() != SI.getType())
9279 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009280 true/*SExt*/, "tmp", ICI);
9281
9282 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009283 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009284 In->getName()+".not"), *ICI);
9285
9286 return ReplaceInstUsesWith(SI, In);
9287 }
9288 }
9289 }
9290
Dan Gohman81b28ce2008-09-16 18:46:06 +00009291 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9292 // Transform (X == Y) ? X : Y -> Y
9293 if (Pred == ICmpInst::ICMP_EQ)
9294 return ReplaceInstUsesWith(SI, FalseVal);
9295 // Transform (X != Y) ? X : Y -> X
9296 if (Pred == ICmpInst::ICMP_NE)
9297 return ReplaceInstUsesWith(SI, TrueVal);
9298 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9299
9300 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9301 // Transform (X == Y) ? Y : X -> X
9302 if (Pred == ICmpInst::ICMP_EQ)
9303 return ReplaceInstUsesWith(SI, FalseVal);
9304 // Transform (X != Y) ? Y : X -> Y
9305 if (Pred == ICmpInst::ICMP_NE)
9306 return ReplaceInstUsesWith(SI, TrueVal);
9307 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9308 }
9309
9310 /// NOTE: if we wanted to, this is where to detect integer ABS
9311
9312 return Changed ? &SI : 0;
9313}
9314
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009315
Chris Lattner7f239582009-10-22 00:17:26 +00009316/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9317/// PHI node (but the two may be in different blocks). See if the true/false
9318/// values (V) are live in all of the predecessor blocks of the PHI. For
9319/// example, cases like this cannot be mapped:
9320///
9321/// X = phi [ C1, BB1], [C2, BB2]
9322/// Y = add
9323/// Z = select X, Y, 0
9324///
9325/// because Y is not live in BB1/BB2.
9326///
9327static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9328 const SelectInst &SI) {
9329 // If the value is a non-instruction value like a constant or argument, it
9330 // can always be mapped.
9331 const Instruction *I = dyn_cast<Instruction>(V);
9332 if (I == 0) return true;
9333
9334 // If V is a PHI node defined in the same block as the condition PHI, we can
9335 // map the arguments.
9336 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9337
9338 if (const PHINode *VP = dyn_cast<PHINode>(I))
9339 if (VP->getParent() == CondPHI->getParent())
9340 return true;
9341
9342 // Otherwise, if the PHI and select are defined in the same block and if V is
9343 // defined in a different block, then we can transform it.
9344 if (SI.getParent() == CondPHI->getParent() &&
9345 I->getParent() != CondPHI->getParent())
9346 return true;
9347
9348 // Otherwise we have a 'hard' case and we can't tell without doing more
9349 // detailed dominator based analysis, punt.
9350 return false;
9351}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009352
Chris Lattner3d69f462004-03-12 05:52:32 +00009353Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009354 Value *CondVal = SI.getCondition();
9355 Value *TrueVal = SI.getTrueValue();
9356 Value *FalseVal = SI.getFalseValue();
9357
9358 // select true, X, Y -> X
9359 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009360 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009361 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009362
9363 // select C, X, X -> X
9364 if (TrueVal == FalseVal)
9365 return ReplaceInstUsesWith(SI, TrueVal);
9366
Chris Lattnere87597f2004-10-16 18:11:37 +00009367 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9368 return ReplaceInstUsesWith(SI, FalseVal);
9369 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9370 return ReplaceInstUsesWith(SI, TrueVal);
9371 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9372 if (isa<Constant>(TrueVal))
9373 return ReplaceInstUsesWith(SI, TrueVal);
9374 else
9375 return ReplaceInstUsesWith(SI, FalseVal);
9376 }
9377
Owen Anderson1d0be152009-08-13 21:58:54 +00009378 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009379 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009380 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009381 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009382 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009383 } else {
9384 // Change: A = select B, false, C --> A = and !B, C
9385 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009386 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009387 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009388 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009389 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009390 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009391 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009392 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009393 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009394 } else {
9395 // Change: A = select B, C, true --> A = or !B, C
9396 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009397 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009398 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009399 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009400 }
9401 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009402
9403 // select a, b, a -> a&b
9404 // select a, a, b -> a|b
9405 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009406 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009407 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009408 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009409 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009410
Chris Lattner2eefe512004-04-09 19:05:30 +00009411 // Selecting between two integer constants?
9412 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9413 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009414 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009415 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009416 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009417 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009418 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009419 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009420 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009421 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009422 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009423 }
Chris Lattner457dd822004-06-09 07:59:58 +00009424
Reid Spencere4d87aa2006-12-23 06:05:41 +00009425 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009426 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009427 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009428 // non-constant value, eliminate this whole mess. This corresponds to
9429 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009430 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009431 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009432 cast<Constant>(IC->getOperand(1))->isNullValue())
9433 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9434 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009435 isa<ConstantInt>(ICA->getOperand(1)) &&
9436 (ICA->getOperand(1) == TrueValC ||
9437 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009438 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9439 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009440 // know whether we have a icmp_ne or icmp_eq and whether the
9441 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009442 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009443 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009444 Value *V = ICA;
9445 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009446 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009447 Instruction::Xor, V, ICA->getOperand(1)), SI);
9448 return ReplaceInstUsesWith(SI, V);
9449 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009450 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009451 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009452
9453 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009454 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9455 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009456 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009457 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9458 // This is not safe in general for floating point:
9459 // consider X== -0, Y== +0.
9460 // It becomes safe if either operand is a nonzero constant.
9461 ConstantFP *CFPt, *CFPf;
9462 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9463 !CFPt->getValueAPF().isZero()) ||
9464 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9465 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009466 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009467 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009468 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009469 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009470 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009471 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009472
Reid Spencere4d87aa2006-12-23 06:05:41 +00009473 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009474 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009475 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9476 // This is not safe in general for floating point:
9477 // consider X== -0, Y== +0.
9478 // It becomes safe if either operand is a nonzero constant.
9479 ConstantFP *CFPt, *CFPf;
9480 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9481 !CFPt->getValueAPF().isZero()) ||
9482 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9483 !CFPf->getValueAPF().isZero()))
9484 return ReplaceInstUsesWith(SI, FalseVal);
9485 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009486 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009487 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9488 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009489 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009490 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009491 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009492 }
9493
9494 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009495 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9496 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9497 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009498
Chris Lattner87875da2005-01-13 22:52:24 +00009499 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9500 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9501 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009502 Instruction *AddOp = 0, *SubOp = 0;
9503
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009504 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9505 if (TI->getOpcode() == FI->getOpcode())
9506 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9507 return IV;
9508
9509 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9510 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009511 if ((TI->getOpcode() == Instruction::Sub &&
9512 FI->getOpcode() == Instruction::Add) ||
9513 (TI->getOpcode() == Instruction::FSub &&
9514 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009515 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009516 } else if ((FI->getOpcode() == Instruction::Sub &&
9517 TI->getOpcode() == Instruction::Add) ||
9518 (FI->getOpcode() == Instruction::FSub &&
9519 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009520 AddOp = TI; SubOp = FI;
9521 }
9522
9523 if (AddOp) {
9524 Value *OtherAddOp = 0;
9525 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9526 OtherAddOp = AddOp->getOperand(1);
9527 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9528 OtherAddOp = AddOp->getOperand(0);
9529 }
9530
9531 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009532 // So at this point we know we have (Y -> OtherAddOp):
9533 // select C, (add X, Y), (sub X, Z)
9534 Value *NegVal; // Compute -Z
9535 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009536 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009537 } else {
9538 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009539 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009540 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009541 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009542
9543 Value *NewTrueOp = OtherAddOp;
9544 Value *NewFalseOp = NegVal;
9545 if (AddOp != TI)
9546 std::swap(NewTrueOp, NewFalseOp);
9547 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009548 SelectInst::Create(CondVal, NewTrueOp,
9549 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009550
9551 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009552 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009553 }
9554 }
9555 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009556
Chris Lattnere576b912004-04-09 23:46:01 +00009557 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009558 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009559 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9560 if (FoldI)
9561 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009562 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009563
Chris Lattner7f239582009-10-22 00:17:26 +00009564 // See if we can fold the select into a phi node if the condition is a select.
9565 if (isa<PHINode>(SI.getCondition()))
9566 // The true/false values have to be live in the PHI predecessor's blocks.
9567 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9568 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9569 if (Instruction *NV = FoldOpIntoPhi(SI))
9570 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00009571
Chris Lattnera1df33c2005-04-24 07:30:14 +00009572 if (BinaryOperator::isNot(CondVal)) {
9573 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9574 SI.setOperand(1, FalseVal);
9575 SI.setOperand(2, TrueVal);
9576 return &SI;
9577 }
9578
Chris Lattner3d69f462004-03-12 05:52:32 +00009579 return 0;
9580}
9581
Dan Gohmaneee962e2008-04-10 18:43:06 +00009582/// EnforceKnownAlignment - If the specified pointer points to an object that
9583/// we control, modify the object's alignment to PrefAlign. This isn't
9584/// often possible though. If alignment is important, a more reliable approach
9585/// is to simply align all global variables and allocation instructions to
9586/// their preferred alignment from the beginning.
9587///
9588static unsigned EnforceKnownAlignment(Value *V,
9589 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009590
Dan Gohmaneee962e2008-04-10 18:43:06 +00009591 User *U = dyn_cast<User>(V);
9592 if (!U) return Align;
9593
Dan Gohmanca178902009-07-17 20:47:02 +00009594 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009595 default: break;
9596 case Instruction::BitCast:
9597 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9598 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009599 // If all indexes are zero, it is just the alignment of the base pointer.
9600 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009601 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009602 if (!isa<Constant>(*i) ||
9603 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009604 AllZeroOperands = false;
9605 break;
9606 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009607
9608 if (AllZeroOperands) {
9609 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009610 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009611 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009612 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009613 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009614 }
9615
9616 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9617 // If there is a large requested alignment and we can, bump up the alignment
9618 // of the global.
9619 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009620 if (GV->getAlignment() >= PrefAlign)
9621 Align = GV->getAlignment();
9622 else {
9623 GV->setAlignment(PrefAlign);
9624 Align = PrefAlign;
9625 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009626 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009627 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9628 // If there is a requested alignment and if this is an alloca, round up.
9629 if (AI->getAlignment() >= PrefAlign)
9630 Align = AI->getAlignment();
9631 else {
9632 AI->setAlignment(PrefAlign);
9633 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009634 }
9635 }
9636
9637 return Align;
9638}
9639
9640/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9641/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9642/// and it is more than the alignment of the ultimate object, see if we can
9643/// increase the alignment of the ultimate object, making this check succeed.
9644unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9645 unsigned PrefAlign) {
9646 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9647 sizeof(PrefAlign) * CHAR_BIT;
9648 APInt Mask = APInt::getAllOnesValue(BitWidth);
9649 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9650 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9651 unsigned TrailZ = KnownZero.countTrailingOnes();
9652 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9653
9654 if (PrefAlign > Align)
9655 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9656
9657 // We don't need to make any adjustment.
9658 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009659}
9660
Chris Lattnerf497b022008-01-13 23:50:23 +00009661Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009662 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009663 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009664 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009665 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009666
9667 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009668 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009669 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009670 return MI;
9671 }
9672
9673 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9674 // load/store.
9675 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9676 if (MemOpLength == 0) return 0;
9677
Chris Lattner37ac6082008-01-14 00:28:35 +00009678 // Source and destination pointer types are always "i8*" for intrinsic. See
9679 // if the size is something we can handle with a single primitive load/store.
9680 // A single load+store correctly handles overlapping memory in the memmove
9681 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009682 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009683 if (Size == 0) return MI; // Delete this mem transfer.
9684
9685 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009686 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009687
Chris Lattner37ac6082008-01-14 00:28:35 +00009688 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009689 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009690 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009691
9692 // Memcpy forces the use of i8* for the source and destination. That means
9693 // that if you're using memcpy to move one double around, you'll get a cast
9694 // from double* to i8*. We'd much rather use a double load+store rather than
9695 // an i64 load+store, here because this improves the odds that the source or
9696 // dest address will be promotable. See if we can find a better type than the
9697 // integer datatype.
9698 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9699 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009700 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009701 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9702 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009703 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009704 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9705 if (STy->getNumElements() == 1)
9706 SrcETy = STy->getElementType(0);
9707 else
9708 break;
9709 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9710 if (ATy->getNumElements() == 1)
9711 SrcETy = ATy->getElementType();
9712 else
9713 break;
9714 } else
9715 break;
9716 }
9717
Dan Gohman8f8e2692008-05-23 01:52:21 +00009718 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009719 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009720 }
9721 }
9722
9723
Chris Lattnerf497b022008-01-13 23:50:23 +00009724 // If the memcpy/memmove provides better alignment info than we can
9725 // infer, use it.
9726 SrcAlign = std::max(SrcAlign, CopyAlign);
9727 DstAlign = std::max(DstAlign, CopyAlign);
9728
Chris Lattner08142f22009-08-30 19:47:22 +00009729 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9730 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009731 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9732 InsertNewInstBefore(L, *MI);
9733 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9734
9735 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009736 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009737 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009738}
Chris Lattner3d69f462004-03-12 05:52:32 +00009739
Chris Lattner69ea9d22008-04-30 06:39:11 +00009740Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9741 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009742 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009743 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009744 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009745 return MI;
9746 }
9747
9748 // Extract the length and alignment and fill if they are constant.
9749 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9750 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009751 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009752 return 0;
9753 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009754 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009755
9756 // If the length is zero, this is a no-op
9757 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9758
9759 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9760 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009761 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009762
9763 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009764 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009765
9766 // Alignment 0 is identity for alignment 1 for memset, but not store.
9767 if (Alignment == 0) Alignment = 1;
9768
9769 // Extract the fill value and store.
9770 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009771 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009772 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009773
9774 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009775 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009776 return MI;
9777 }
9778
9779 return 0;
9780}
9781
9782
Chris Lattner8b0ea312006-01-13 20:11:04 +00009783/// visitCallInst - CallInst simplification. This mostly only handles folding
9784/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9785/// the heavy lifting.
9786///
Chris Lattner9fe38862003-06-19 17:00:31 +00009787Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00009788 if (isFreeCall(&CI))
9789 return visitFree(CI);
9790
Chris Lattneraab6ec42009-05-13 17:39:14 +00009791 // If the caller function is nounwind, mark the call as nounwind, even if the
9792 // callee isn't.
9793 if (CI.getParent()->getParent()->doesNotThrow() &&
9794 !CI.doesNotThrow()) {
9795 CI.setDoesNotThrow();
9796 return &CI;
9797 }
9798
Chris Lattner8b0ea312006-01-13 20:11:04 +00009799 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9800 if (!II) return visitCallSite(&CI);
9801
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009802 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9803 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009804 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009805 bool Changed = false;
9806
9807 // memmove/cpy/set of zero bytes is a noop.
9808 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9809 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9810
Chris Lattner35b9e482004-10-12 04:52:52 +00009811 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009812 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009813 // Replace the instruction with just byte operations. We would
9814 // transform other cases to loads/stores, but we don't know if
9815 // alignment is sufficient.
9816 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009817 }
9818
Chris Lattner35b9e482004-10-12 04:52:52 +00009819 // If we have a memmove and the source operation is a constant global,
9820 // then the source and dest pointers can't alias, so we can change this
9821 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009822 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009823 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9824 if (GVSrc->isConstant()) {
9825 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009826 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9827 const Type *Tys[1];
9828 Tys[0] = CI.getOperand(3)->getType();
9829 CI.setOperand(0,
9830 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009831 Changed = true;
9832 }
Chris Lattnera935db82008-05-28 05:30:41 +00009833
9834 // memmove(x,x,size) -> noop.
9835 if (MMI->getSource() == MMI->getDest())
9836 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009837 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009838
Chris Lattner95a959d2006-03-06 20:18:44 +00009839 // If we can determine a pointer alignment that is bigger than currently
9840 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009841 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009842 if (Instruction *I = SimplifyMemTransfer(MI))
9843 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009844 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9845 if (Instruction *I = SimplifyMemSet(MSI))
9846 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009847 }
9848
Chris Lattner8b0ea312006-01-13 20:11:04 +00009849 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009850 }
9851
9852 switch (II->getIntrinsicID()) {
9853 default: break;
9854 case Intrinsic::bswap:
9855 // bswap(bswap(x)) -> x
9856 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9857 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9858 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9859 break;
9860 case Intrinsic::ppc_altivec_lvx:
9861 case Intrinsic::ppc_altivec_lvxl:
9862 case Intrinsic::x86_sse_loadu_ps:
9863 case Intrinsic::x86_sse2_loadu_pd:
9864 case Intrinsic::x86_sse2_loadu_dq:
9865 // Turn PPC lvx -> load if the pointer is known aligned.
9866 // Turn X86 loadups -> load if the pointer is known aligned.
9867 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009868 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9869 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009870 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009871 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009872 break;
9873 case Intrinsic::ppc_altivec_stvx:
9874 case Intrinsic::ppc_altivec_stvxl:
9875 // Turn stvx -> store if the pointer is known aligned.
9876 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9877 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009878 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009879 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009880 return new StoreInst(II->getOperand(1), Ptr);
9881 }
9882 break;
9883 case Intrinsic::x86_sse_storeu_ps:
9884 case Intrinsic::x86_sse2_storeu_pd:
9885 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009886 // Turn X86 storeu -> store if the pointer is known aligned.
9887 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9888 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009889 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009890 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009891 return new StoreInst(II->getOperand(2), Ptr);
9892 }
9893 break;
9894
9895 case Intrinsic::x86_sse_cvttss2si: {
9896 // These intrinsics only demands the 0th element of its input vector. If
9897 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009898 unsigned VWidth =
9899 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9900 APInt DemandedElts(VWidth, 1);
9901 APInt UndefElts(VWidth, 0);
9902 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009903 UndefElts)) {
9904 II->setOperand(1, V);
9905 return II;
9906 }
9907 break;
9908 }
9909
9910 case Intrinsic::ppc_altivec_vperm:
9911 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9912 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9913 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009914
Chris Lattner0521e3c2008-06-18 04:33:20 +00009915 // Check that all of the elements are integer constants or undefs.
9916 bool AllEltsOk = true;
9917 for (unsigned i = 0; i != 16; ++i) {
9918 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9919 !isa<UndefValue>(Mask->getOperand(i))) {
9920 AllEltsOk = false;
9921 break;
9922 }
9923 }
9924
9925 if (AllEltsOk) {
9926 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009927 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9928 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009929 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009930
Chris Lattner0521e3c2008-06-18 04:33:20 +00009931 // Only extract each element once.
9932 Value *ExtractedElts[32];
9933 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9934
Chris Lattnere2ed0572006-04-06 19:19:17 +00009935 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009936 if (isa<UndefValue>(Mask->getOperand(i)))
9937 continue;
9938 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9939 Idx &= 31; // Match the hardware behavior.
9940
9941 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009942 ExtractedElts[Idx] =
9943 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9944 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9945 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009946 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009947
Chris Lattner0521e3c2008-06-18 04:33:20 +00009948 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009949 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9950 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9951 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009952 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009953 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009954 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009955 }
9956 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009957
Chris Lattner0521e3c2008-06-18 04:33:20 +00009958 case Intrinsic::stackrestore: {
9959 // If the save is right next to the restore, remove the restore. This can
9960 // happen when variable allocas are DCE'd.
9961 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9962 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9963 BasicBlock::iterator BI = SS;
9964 if (&*++BI == II)
9965 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009966 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009967 }
9968
9969 // Scan down this block to see if there is another stack restore in the
9970 // same block without an intervening call/alloca.
9971 BasicBlock::iterator BI = II;
9972 TerminatorInst *TI = II->getParent()->getTerminator();
9973 bool CannotRemove = false;
9974 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009975 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009976 CannotRemove = true;
9977 break;
9978 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009979 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9980 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9981 // If there is a stackrestore below this one, remove this one.
9982 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9983 return EraseInstFromFunction(CI);
9984 // Otherwise, ignore the intrinsic.
9985 } else {
9986 // If we found a non-intrinsic call, we can't remove the stack
9987 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009988 CannotRemove = true;
9989 break;
9990 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009991 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009992 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009993
9994 // If the stack restore is in a return/unwind block and if there are no
9995 // allocas or calls between the restore and the return, nuke the restore.
9996 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9997 return EraseInstFromFunction(CI);
9998 break;
9999 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010000 }
10001
Chris Lattner8b0ea312006-01-13 20:11:04 +000010002 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010003}
10004
10005// InvokeInst simplification
10006//
10007Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010008 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010009}
10010
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010011/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10012/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010013static bool isSafeToEliminateVarargsCast(const CallSite CS,
10014 const CastInst * const CI,
10015 const TargetData * const TD,
10016 const int ix) {
10017 if (!CI->isLosslessCast())
10018 return false;
10019
10020 // The size of ByVal arguments is derived from the type, so we
10021 // can't change to a type with a different size. If the size were
10022 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010023 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010024 return true;
10025
10026 const Type* SrcTy =
10027 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10028 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10029 if (!SrcTy->isSized() || !DstTy->isSized())
10030 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010031 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010032 return false;
10033 return true;
10034}
10035
Chris Lattnera44d8a22003-10-07 22:32:43 +000010036// visitCallSite - Improvements for call and invoke instructions.
10037//
10038Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010039 bool Changed = false;
10040
10041 // If the callee is a constexpr cast of a function, attempt to move the cast
10042 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010043 if (transformConstExprCastCall(CS)) return 0;
10044
Chris Lattner6c266db2003-10-07 22:54:13 +000010045 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010046
Chris Lattner08b22ec2005-05-13 07:09:09 +000010047 if (Function *CalleeF = dyn_cast<Function>(Callee))
10048 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10049 Instruction *OldCall = CS.getInstruction();
10050 // If the call and callee calling conventions don't match, this call must
10051 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010052 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010053 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010054 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010055 // If OldCall dues not return void then replaceAllUsesWith undef.
10056 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010057 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010058 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010059 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10060 return EraseInstFromFunction(*OldCall);
10061 return 0;
10062 }
10063
Chris Lattner17be6352004-10-18 02:59:09 +000010064 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10065 // This instruction is not reachable, just remove it. We insert a store to
10066 // undef so that we know that this code is not reachable, despite the fact
10067 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010068 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010069 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010070 CS.getInstruction());
10071
Devang Patel228ebd02009-10-13 22:56:32 +000010072 // If CS dues not return void then replaceAllUsesWith undef.
10073 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010074 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010075 CS.getInstruction()->
10076 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010077
10078 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10079 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010080 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010081 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010082 }
Chris Lattner17be6352004-10-18 02:59:09 +000010083 return EraseInstFromFunction(*CS.getInstruction());
10084 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010085
Duncan Sandscdb6d922007-09-17 10:26:40 +000010086 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10087 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10088 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10089 return transformCallThroughTrampoline(CS);
10090
Chris Lattner6c266db2003-10-07 22:54:13 +000010091 const PointerType *PTy = cast<PointerType>(Callee->getType());
10092 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10093 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010094 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010095 // See if we can optimize any arguments passed through the varargs area of
10096 // the call.
10097 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010098 E = CS.arg_end(); I != E; ++I, ++ix) {
10099 CastInst *CI = dyn_cast<CastInst>(*I);
10100 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10101 *I = CI->getOperand(0);
10102 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010103 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010104 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010105 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010106
Duncan Sandsf0c33542007-12-19 21:13:37 +000010107 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010108 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010109 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010110 Changed = true;
10111 }
10112
Chris Lattner6c266db2003-10-07 22:54:13 +000010113 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010114}
10115
Chris Lattner9fe38862003-06-19 17:00:31 +000010116// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10117// attempt to move the cast to the arguments of the call/invoke.
10118//
10119bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10120 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10121 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010122 if (CE->getOpcode() != Instruction::BitCast ||
10123 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010124 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010125 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010126 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010127 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010128
10129 // Okay, this is a cast from a function to a different type. Unless doing so
10130 // would cause a type conversion of one of our arguments, change this call to
10131 // be a direct call with arguments casted to the appropriate types.
10132 //
10133 const FunctionType *FT = Callee->getFunctionType();
10134 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010135 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010136
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010137 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010138 return false; // TODO: Handle multiple return values.
10139
Chris Lattnerf78616b2004-01-14 06:06:08 +000010140 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010141 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010142 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010143 // Conversion is ok if changing from one pointer type to another or from
10144 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010145 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010146 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010147 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010148 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010149 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010150
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010151 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010152 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010153 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010154 return false; // Cannot transform this return value.
10155
Chris Lattner58d74912008-03-12 17:45:29 +000010156 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010157 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010158 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010159 return false; // Attribute not compatible with transformed value.
10160 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010161
Chris Lattnerf78616b2004-01-14 06:06:08 +000010162 // If the callsite is an invoke instruction, and the return value is used by
10163 // a PHI node in a successor, we cannot change the return type of the call
10164 // because there is no place to put the cast instruction (without breaking
10165 // the critical edge). Bail out in this case.
10166 if (!Caller->use_empty())
10167 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10168 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10169 UI != E; ++UI)
10170 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10171 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010172 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010173 return false;
10174 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010175
10176 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10177 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010178
Chris Lattner9fe38862003-06-19 17:00:31 +000010179 CallSite::arg_iterator AI = CS.arg_begin();
10180 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10181 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010182 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010183
10184 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010185 return false; // Cannot transform this parameter value.
10186
Devang Patel19c87462008-09-26 22:53:05 +000010187 if (CallerPAL.getParamAttributes(i + 1)
10188 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010189 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010190
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010191 // Converting from one pointer type to another or between a pointer and an
10192 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010193 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010194 (TD && ((isa<PointerType>(ParamTy) ||
10195 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10196 (isa<PointerType>(ActTy) ||
10197 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010198 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010199 }
10200
10201 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010202 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010203 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010204
Chris Lattner58d74912008-03-12 17:45:29 +000010205 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10206 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010207 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010208 // won't be dropping them. Check that these extra arguments have attributes
10209 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010210 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10211 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010212 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010213 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010214 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010215 return false;
10216 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010217
Chris Lattner9fe38862003-06-19 17:00:31 +000010218 // Okay, we decided that this is a safe thing to do: go ahead and start
10219 // inserting cast instructions as necessary...
10220 std::vector<Value*> Args;
10221 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010222 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010223 attrVec.reserve(NumCommonArgs);
10224
10225 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010226 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010227
10228 // If the return value is not being used, the type may not be compatible
10229 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010230 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010231
10232 // Add the new return attributes.
10233 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010234 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010235
10236 AI = CS.arg_begin();
10237 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10238 const Type *ParamTy = FT->getParamType(i);
10239 if ((*AI)->getType() == ParamTy) {
10240 Args.push_back(*AI);
10241 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010242 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010243 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010244 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010245 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010246
10247 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010248 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010249 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010250 }
10251
10252 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010253 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010254 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010255 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010256
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010257 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010258 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010259 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010260 errs() << "WARNING: While resolving call to function '"
10261 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010262 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010263 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010264 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10265 const Type *PTy = getPromotedType((*AI)->getType());
10266 if (PTy != (*AI)->getType()) {
10267 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010268 Instruction::CastOps opcode =
10269 CastInst::getCastOpcode(*AI, false, PTy, false);
10270 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010271 } else {
10272 Args.push_back(*AI);
10273 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010274
Duncan Sandse1e520f2008-01-13 08:02:44 +000010275 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010276 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010277 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010278 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010279 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010280 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010281
Devang Patel19c87462008-09-26 22:53:05 +000010282 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10283 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10284
Devang Patel9674d152009-10-14 17:29:00 +000010285 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010286 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010287
Eric Christophera66297a2009-07-25 02:45:27 +000010288 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10289 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010290
Chris Lattner9fe38862003-06-19 17:00:31 +000010291 Instruction *NC;
10292 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010293 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010294 Args.begin(), Args.end(),
10295 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010296 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010297 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010298 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010299 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10300 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010301 CallInst *CI = cast<CallInst>(Caller);
10302 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010303 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010304 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010305 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010306 }
10307
Chris Lattner6934a042007-02-11 01:23:03 +000010308 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010309 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010310 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010311 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010312 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010313 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010314 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010315
10316 // If this is an invoke instruction, we should insert it after the first
10317 // non-phi, instruction in the normal successor block.
10318 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010319 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010320 InsertNewInstBefore(NC, *I);
10321 } else {
10322 // Otherwise, it's a call, just insert cast right after the call instr
10323 InsertNewInstBefore(NC, *Caller);
10324 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010325 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010326 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010327 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010328 }
10329 }
10330
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010331
Chris Lattner931f8f32009-08-31 05:17:58 +000010332 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010333 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010334
10335 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010336 return true;
10337}
10338
Duncan Sandscdb6d922007-09-17 10:26:40 +000010339// transformCallThroughTrampoline - Turn a call to a function created by the
10340// init_trampoline intrinsic into a direct call to the underlying function.
10341//
10342Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10343 Value *Callee = CS.getCalledValue();
10344 const PointerType *PTy = cast<PointerType>(Callee->getType());
10345 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010346 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010347
10348 // If the call already has the 'nest' attribute somewhere then give up -
10349 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010350 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010351 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010352
10353 IntrinsicInst *Tramp =
10354 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10355
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010356 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010357 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10358 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10359
Devang Patel05988662008-09-25 21:00:45 +000010360 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010361 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010362 unsigned NestIdx = 1;
10363 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010364 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010365
10366 // Look for a parameter marked with the 'nest' attribute.
10367 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10368 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010369 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010370 // Record the parameter type and any other attributes.
10371 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010372 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010373 break;
10374 }
10375
10376 if (NestTy) {
10377 Instruction *Caller = CS.getInstruction();
10378 std::vector<Value*> NewArgs;
10379 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10380
Devang Patel05988662008-09-25 21:00:45 +000010381 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010382 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010383
Duncan Sandscdb6d922007-09-17 10:26:40 +000010384 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010385 // mean appending it. Likewise for attributes.
10386
Devang Patel19c87462008-09-26 22:53:05 +000010387 // Add any result attributes.
10388 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010389 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010390
Duncan Sandscdb6d922007-09-17 10:26:40 +000010391 {
10392 unsigned Idx = 1;
10393 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10394 do {
10395 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010396 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010397 Value *NestVal = Tramp->getOperand(3);
10398 if (NestVal->getType() != NestTy)
10399 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10400 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010401 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010402 }
10403
10404 if (I == E)
10405 break;
10406
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010407 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010408 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010409 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010410 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010411 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010412
10413 ++Idx, ++I;
10414 } while (1);
10415 }
10416
Devang Patel19c87462008-09-26 22:53:05 +000010417 // Add any function attributes.
10418 if (Attributes Attr = Attrs.getFnAttributes())
10419 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10420
Duncan Sandscdb6d922007-09-17 10:26:40 +000010421 // The trampoline may have been bitcast to a bogus type (FTy).
10422 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010423 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010424
Duncan Sandscdb6d922007-09-17 10:26:40 +000010425 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010426 NewTypes.reserve(FTy->getNumParams()+1);
10427
Duncan Sandscdb6d922007-09-17 10:26:40 +000010428 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010429 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010430 {
10431 unsigned Idx = 1;
10432 FunctionType::param_iterator I = FTy->param_begin(),
10433 E = FTy->param_end();
10434
10435 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010436 if (Idx == NestIdx)
10437 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010438 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010439
10440 if (I == E)
10441 break;
10442
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010443 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010444 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010445
10446 ++Idx, ++I;
10447 } while (1);
10448 }
10449
10450 // Replace the trampoline call with a direct call. Let the generic
10451 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010452 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010453 FTy->isVarArg());
10454 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010455 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010456 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010457 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010458 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10459 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010460
10461 Instruction *NewCaller;
10462 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010463 NewCaller = InvokeInst::Create(NewCallee,
10464 II->getNormalDest(), II->getUnwindDest(),
10465 NewArgs.begin(), NewArgs.end(),
10466 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010467 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010468 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010469 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010470 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10471 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010472 if (cast<CallInst>(Caller)->isTailCall())
10473 cast<CallInst>(NewCaller)->setTailCall();
10474 cast<CallInst>(NewCaller)->
10475 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010476 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010477 }
Devang Patel9674d152009-10-14 17:29:00 +000010478 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010479 Caller->replaceAllUsesWith(NewCaller);
10480 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010481 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010482 return 0;
10483 }
10484 }
10485
10486 // Replace the trampoline call with a direct call. Since there is no 'nest'
10487 // parameter, there is no need to adjust the argument list. Let the generic
10488 // code sort out any function type mismatches.
10489 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010490 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010491 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010492 CS.setCalledFunction(NewCallee);
10493 return CS.getInstruction();
10494}
10495
Dan Gohman9ad29202009-09-16 16:50:24 +000010496/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10497/// 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 +000010498/// and a single binop.
10499Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10500 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010501 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010502 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010503 Value *LHSVal = FirstInst->getOperand(0);
10504 Value *RHSVal = FirstInst->getOperand(1);
10505
10506 const Type *LHSType = LHSVal->getType();
10507 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010508
Dan Gohman9ad29202009-09-16 16:50:24 +000010509 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010510 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010511 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010512 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010513 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010514 // types or GEP's with different index types.
10515 I->getOperand(0)->getType() != LHSType ||
10516 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010517 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010518
10519 // If they are CmpInst instructions, check their predicates
10520 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10521 if (cast<CmpInst>(I)->getPredicate() !=
10522 cast<CmpInst>(FirstInst)->getPredicate())
10523 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010524
10525 // Keep track of which operand needs a phi node.
10526 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10527 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010528 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010529
10530 // If both LHS and RHS would need a PHI, don't do this transformation,
10531 // because it would increase the number of PHIs entering the block,
10532 // which leads to higher register pressure. This is especially
10533 // bad when the PHIs are in the header of a loop.
10534 if (!LHSVal && !RHSVal)
10535 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010536
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010537 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010538
Chris Lattner7da52b22006-11-01 04:51:18 +000010539 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010540 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010541 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010542 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010543 NewLHS = PHINode::Create(LHSType,
10544 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010545 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10546 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010547 InsertNewInstBefore(NewLHS, PN);
10548 LHSVal = NewLHS;
10549 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010550
10551 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010552 NewRHS = PHINode::Create(RHSType,
10553 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010554 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10555 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010556 InsertNewInstBefore(NewRHS, PN);
10557 RHSVal = NewRHS;
10558 }
10559
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010560 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010561 if (NewLHS || NewRHS) {
10562 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10563 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10564 if (NewLHS) {
10565 Value *NewInLHS = InInst->getOperand(0);
10566 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10567 }
10568 if (NewRHS) {
10569 Value *NewInRHS = InInst->getOperand(1);
10570 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10571 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010572 }
10573 }
10574
Chris Lattner7da52b22006-11-01 04:51:18 +000010575 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010576 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010577 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010578 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010579 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010580}
10581
Chris Lattner05f18922008-12-01 02:34:36 +000010582Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10583 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10584
10585 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10586 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010587 // This is true if all GEP bases are allocas and if all indices into them are
10588 // constants.
10589 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010590
10591 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010592 // more than one phi, which leads to higher register pressure. This is
10593 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010594 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010595
Dan Gohman9ad29202009-09-16 16:50:24 +000010596 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010597 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10598 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10599 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10600 GEP->getNumOperands() != FirstInst->getNumOperands())
10601 return 0;
10602
Chris Lattner36d3e322009-02-21 00:46:50 +000010603 // Keep track of whether or not all GEPs are of alloca pointers.
10604 if (AllBasePointersAreAllocas &&
10605 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10606 !GEP->hasAllConstantIndices()))
10607 AllBasePointersAreAllocas = false;
10608
Chris Lattner05f18922008-12-01 02:34:36 +000010609 // Compare the operand lists.
10610 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10611 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10612 continue;
10613
10614 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10615 // if one of the PHIs has a constant for the index. The index may be
10616 // substantially cheaper to compute for the constants, so making it a
10617 // variable index could pessimize the path. This also handles the case
10618 // for struct indices, which must always be constant.
10619 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10620 isa<ConstantInt>(GEP->getOperand(op)))
10621 return 0;
10622
10623 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10624 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010625
10626 // If we already needed a PHI for an earlier operand, and another operand
10627 // also requires a PHI, we'd be introducing more PHIs than we're
10628 // eliminating, which increases register pressure on entry to the PHI's
10629 // block.
10630 if (NeededPhi)
10631 return 0;
10632
Chris Lattner05f18922008-12-01 02:34:36 +000010633 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010634 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010635 }
10636 }
10637
Chris Lattner36d3e322009-02-21 00:46:50 +000010638 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010639 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010640 // offset calculation, but all the predecessors will have to materialize the
10641 // stack address into a register anyway. We'd actually rather *clone* the
10642 // load up into the predecessors so that we have a load of a gep of an alloca,
10643 // which can usually all be folded into the load.
10644 if (AllBasePointersAreAllocas)
10645 return 0;
10646
Chris Lattner05f18922008-12-01 02:34:36 +000010647 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10648 // that is variable.
10649 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10650
10651 bool HasAnyPHIs = false;
10652 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10653 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10654 Value *FirstOp = FirstInst->getOperand(i);
10655 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10656 FirstOp->getName()+".pn");
10657 InsertNewInstBefore(NewPN, PN);
10658
10659 NewPN->reserveOperandSpace(e);
10660 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10661 OperandPhis[i] = NewPN;
10662 FixedOperands[i] = NewPN;
10663 HasAnyPHIs = true;
10664 }
10665
10666
10667 // Add all operands to the new PHIs.
10668 if (HasAnyPHIs) {
10669 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10670 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10671 BasicBlock *InBB = PN.getIncomingBlock(i);
10672
10673 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10674 if (PHINode *OpPhi = OperandPhis[op])
10675 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10676 }
10677 }
10678
10679 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010680 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10681 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10682 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010683 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10684 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010685}
10686
10687
Chris Lattner21550882009-02-23 05:56:17 +000010688/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10689/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010690/// obvious the value of the load is not changed from the point of the load to
10691/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010692///
10693/// Finally, it is safe, but not profitable, to sink a load targetting a
10694/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10695/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010696static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010697 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10698
10699 for (++BBI; BBI != E; ++BBI)
10700 if (BBI->mayWriteToMemory())
10701 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010702
10703 // Check for non-address taken alloca. If not address-taken already, it isn't
10704 // profitable to do this xform.
10705 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10706 bool isAddressTaken = false;
10707 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10708 UI != E; ++UI) {
10709 if (isa<LoadInst>(UI)) continue;
10710 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10711 // If storing TO the alloca, then the address isn't taken.
10712 if (SI->getOperand(1) == AI) continue;
10713 }
10714 isAddressTaken = true;
10715 break;
10716 }
10717
Chris Lattner36d3e322009-02-21 00:46:50 +000010718 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010719 return false;
10720 }
10721
Chris Lattner36d3e322009-02-21 00:46:50 +000010722 // If this load is a load from a GEP with a constant offset from an alloca,
10723 // then we don't want to sink it. In its present form, it will be
10724 // load [constant stack offset]. Sinking it will cause us to have to
10725 // materialize the stack addresses in each predecessor in a register only to
10726 // do a shared load from register in the successor.
10727 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10728 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10729 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10730 return false;
10731
Chris Lattner76c73142006-11-01 07:13:54 +000010732 return true;
10733}
10734
Chris Lattner751a3622009-11-01 20:04:24 +000010735Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10736 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10737
10738 // When processing loads, we need to propagate two bits of information to the
10739 // sunk load: whether it is volatile, and what its alignment is. We currently
10740 // don't sink loads when some have their alignment specified and some don't.
10741 // visitLoadInst will propagate an alignment onto the load when TD is around,
10742 // and if TD isn't around, we can't handle the mixed case.
10743 bool isVolatile = FirstLI->isVolatile();
10744 unsigned LoadAlignment = FirstLI->getAlignment();
10745
10746 // We can't sink the load if the loaded value could be modified between the
10747 // load and the PHI.
10748 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10749 !isSafeAndProfitableToSinkLoad(FirstLI))
10750 return 0;
10751
10752 // If the PHI is of volatile loads and the load block has multiple
10753 // successors, sinking it would remove a load of the volatile value from
10754 // the path through the other successor.
10755 if (isVolatile &&
10756 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10757 return 0;
10758
10759 // Check to see if all arguments are the same operation.
10760 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10761 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10762 if (!LI || !LI->hasOneUse())
10763 return 0;
10764
10765 // We can't sink the load if the loaded value could be modified between
10766 // the load and the PHI.
10767 if (LI->isVolatile() != isVolatile ||
10768 LI->getParent() != PN.getIncomingBlock(i) ||
10769 !isSafeAndProfitableToSinkLoad(LI))
10770 return 0;
10771
10772 // If some of the loads have an alignment specified but not all of them,
10773 // we can't do the transformation.
10774 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10775 return 0;
10776
Chris Lattnera664bb72009-11-01 20:07:07 +000010777 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000010778
10779 // If the PHI is of volatile loads and the load block has multiple
10780 // successors, sinking it would remove a load of the volatile value from
10781 // the path through the other successor.
10782 if (isVolatile &&
10783 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10784 return 0;
10785 }
10786
10787 // Okay, they are all the same operation. Create a new PHI node of the
10788 // correct type, and PHI together all of the LHS's of the instructions.
10789 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10790 PN.getName()+".in");
10791 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10792
10793 Value *InVal = FirstLI->getOperand(0);
10794 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10795
10796 // Add all operands to the new PHI.
10797 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10798 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10799 if (NewInVal != InVal)
10800 InVal = 0;
10801 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10802 }
10803
10804 Value *PhiVal;
10805 if (InVal) {
10806 // The new PHI unions all of the same values together. This is really
10807 // common, so we handle it intelligently here for compile-time speed.
10808 PhiVal = InVal;
10809 delete NewPN;
10810 } else {
10811 InsertNewInstBefore(NewPN, PN);
10812 PhiVal = NewPN;
10813 }
10814
10815 // If this was a volatile load that we are merging, make sure to loop through
10816 // and mark all the input loads as non-volatile. If we don't do this, we will
10817 // insert a new volatile load and the old ones will not be deletable.
10818 if (isVolatile)
10819 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10820 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10821
10822 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
10823}
10824
Chris Lattner9fe38862003-06-19 17:00:31 +000010825
Chris Lattnerbac32862004-11-14 19:13:23 +000010826// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10827// operator and they all are only used by the PHI, PHI together their
10828// inputs, and do the operation once, to the result of the PHI.
10829Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10830 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10831
Chris Lattner751a3622009-11-01 20:04:24 +000010832 if (isa<GetElementPtrInst>(FirstInst))
10833 return FoldPHIArgGEPIntoPHI(PN);
10834 if (isa<LoadInst>(FirstInst))
10835 return FoldPHIArgLoadIntoPHI(PN);
10836
Chris Lattnerbac32862004-11-14 19:13:23 +000010837 // Scan the instruction, looking for input operations that can be folded away.
10838 // If all input operands to the phi are the same instruction (e.g. a cast from
10839 // the same type or "+42") we can pull the operation through the PHI, reducing
10840 // code size and simplifying code.
10841 Constant *ConstantOp = 0;
10842 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000010843
Chris Lattnerbac32862004-11-14 19:13:23 +000010844 if (isa<CastInst>(FirstInst)) {
10845 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010846 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010847 // Can fold binop, compare or shift here if the RHS is a constant,
10848 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010849 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010850 if (ConstantOp == 0)
10851 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010852 } else {
10853 return 0; // Cannot fold this operation.
10854 }
10855
10856 // Check to see if all arguments are the same operation.
10857 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000010858 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10859 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010860 return 0;
10861 if (CastSrcTy) {
10862 if (I->getOperand(0)->getType() != CastSrcTy)
10863 return 0; // Cast operation must match.
10864 } else if (I->getOperand(1) != ConstantOp) {
10865 return 0;
10866 }
10867 }
10868
10869 // Okay, they are all the same operation. Create a new PHI node of the
10870 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010871 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10872 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010873 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010874
10875 Value *InVal = FirstInst->getOperand(0);
10876 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010877
10878 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010879 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10880 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10881 if (NewInVal != InVal)
10882 InVal = 0;
10883 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10884 }
10885
10886 Value *PhiVal;
10887 if (InVal) {
10888 // The new PHI unions all of the same values together. This is really
10889 // common, so we handle it intelligently here for compile-time speed.
10890 PhiVal = InVal;
10891 delete NewPN;
10892 } else {
10893 InsertNewInstBefore(NewPN, PN);
10894 PhiVal = NewPN;
10895 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010896
Chris Lattnerbac32862004-11-14 19:13:23 +000010897 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000010898 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010899 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000010900
Chris Lattner54545ac2008-04-29 17:13:43 +000010901 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010902 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000010903
Chris Lattner751a3622009-11-01 20:04:24 +000010904 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10905 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10906 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000010907}
Chris Lattnera1be5662002-05-02 17:06:02 +000010908
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010909/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10910/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010911static bool DeadPHICycle(PHINode *PN,
10912 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010913 if (PN->use_empty()) return true;
10914 if (!PN->hasOneUse()) return false;
10915
10916 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010917 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010918 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010919
10920 // Don't scan crazily complex things.
10921 if (PotentiallyDeadPHIs.size() == 16)
10922 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010923
10924 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10925 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010926
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010927 return false;
10928}
10929
Chris Lattnercf5008a2007-11-06 21:52:06 +000010930/// PHIsEqualValue - Return true if this phi node is always equal to
10931/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10932/// z = some value; x = phi (y, z); y = phi (x, z)
10933static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10934 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10935 // See if we already saw this PHI node.
10936 if (!ValueEqualPHIs.insert(PN))
10937 return true;
10938
10939 // Don't scan crazily complex things.
10940 if (ValueEqualPHIs.size() == 16)
10941 return false;
10942
10943 // Scan the operands to see if they are either phi nodes or are equal to
10944 // the value.
10945 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10946 Value *Op = PN->getIncomingValue(i);
10947 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10948 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10949 return false;
10950 } else if (Op != NonPhiInVal)
10951 return false;
10952 }
10953
10954 return true;
10955}
10956
10957
Chris Lattner473945d2002-05-06 18:06:38 +000010958// PHINode simplification
10959//
Chris Lattner7e708292002-06-25 16:13:24 +000010960Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010961 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010962 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010963
Owen Anderson7e057142006-07-10 22:03:18 +000010964 if (Value *V = PN.hasConstantValue())
10965 return ReplaceInstUsesWith(PN, V);
10966
Owen Anderson7e057142006-07-10 22:03:18 +000010967 // If all PHI operands are the same operation, pull them through the PHI,
10968 // reducing code size.
10969 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010970 isa<Instruction>(PN.getIncomingValue(1)) &&
10971 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10972 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10973 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10974 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010975 PN.getIncomingValue(0)->hasOneUse())
10976 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10977 return Result;
10978
10979 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10980 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10981 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010982 if (PN.hasOneUse()) {
10983 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10984 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010985 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010986 PotentiallyDeadPHIs.insert(&PN);
10987 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010988 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010989 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010990
10991 // If this phi has a single use, and if that use just computes a value for
10992 // the next iteration of a loop, delete the phi. This occurs with unused
10993 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10994 // common case here is good because the only other things that catch this
10995 // are induction variable analysis (sometimes) and ADCE, which is only run
10996 // late.
10997 if (PHIUser->hasOneUse() &&
10998 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10999 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011000 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011001 }
11002 }
Owen Anderson7e057142006-07-10 22:03:18 +000011003
Chris Lattnercf5008a2007-11-06 21:52:06 +000011004 // We sometimes end up with phi cycles that non-obviously end up being the
11005 // same value, for example:
11006 // z = some value; x = phi (y, z); y = phi (x, z)
11007 // where the phi nodes don't necessarily need to be in the same block. Do a
11008 // quick check to see if the PHI node only contains a single non-phi value, if
11009 // so, scan to see if the phi cycle is actually equal to that value.
11010 {
11011 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11012 // Scan for the first non-phi operand.
11013 while (InValNo != NumOperandVals &&
11014 isa<PHINode>(PN.getIncomingValue(InValNo)))
11015 ++InValNo;
11016
11017 if (InValNo != NumOperandVals) {
11018 Value *NonPhiInVal = PN.getOperand(InValNo);
11019
11020 // Scan the rest of the operands to see if there are any conflicts, if so
11021 // there is no need to recursively scan other phis.
11022 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11023 Value *OpVal = PN.getIncomingValue(InValNo);
11024 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11025 break;
11026 }
11027
11028 // If we scanned over all operands, then we have one unique value plus
11029 // phi values. Scan PHI nodes to see if they all merge in each other or
11030 // the value.
11031 if (InValNo == NumOperandVals) {
11032 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11033 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11034 return ReplaceInstUsesWith(PN, NonPhiInVal);
11035 }
11036 }
11037 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011038
Dan Gohman5b097012009-10-31 14:22:52 +000011039 // If there are multiple PHIs, sort their operands so that they all list
11040 // the blocks in the same order. This will help identical PHIs be eliminated
11041 // by other passes. Other passes shouldn't depend on this for correctness
11042 // however.
11043 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11044 if (&PN != FirstPN)
11045 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011046 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000011047 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11048 if (BBA != BBB) {
11049 Value *VA = PN.getIncomingValue(i);
11050 unsigned j = PN.getBasicBlockIndex(BBB);
11051 Value *VB = PN.getIncomingValue(j);
11052 PN.setIncomingBlock(i, BBB);
11053 PN.setIncomingValue(i, VB);
11054 PN.setIncomingBlock(j, BBA);
11055 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000011056 // NOTE: Instcombine normally would want us to "return &PN" if we
11057 // modified any of the operands of an instruction. However, since we
11058 // aren't adding or removing uses (just rearranging them) we don't do
11059 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000011060 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011061 }
11062
Chris Lattner60921c92003-12-19 05:58:40 +000011063 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011064}
11065
Chris Lattner7e708292002-06-25 16:13:24 +000011066Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000011067 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000011068 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011069 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011070 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011071
Chris Lattnere87597f2004-10-16 18:11:37 +000011072 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011073 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011074
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011075 bool HasZeroPointerIndex = false;
11076 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11077 HasZeroPointerIndex = C->isNullValue();
11078
11079 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011080 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011081
Chris Lattner28977af2004-04-05 01:30:19 +000011082 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011083 if (TD) {
11084 bool MadeChange = false;
11085 unsigned PtrSize = TD->getPointerSizeInBits();
11086
11087 gep_type_iterator GTI = gep_type_begin(GEP);
11088 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11089 I != E; ++I, ++GTI) {
11090 if (!isa<SequentialType>(*GTI)) continue;
11091
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011092 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011093 // to what we need. If narrower, sign-extend it to what we need. This
11094 // explicit cast can make subsequent optimizations more obvious.
11095 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000011096 if (OpBits == PtrSize)
11097 continue;
11098
Chris Lattner2345d1d2009-08-30 20:01:10 +000011099 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011100 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011101 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011102 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011103 }
Chris Lattner28977af2004-04-05 01:30:19 +000011104
Chris Lattner90ac28c2002-08-02 19:29:35 +000011105 // Combine Indices - If the source pointer to this getelementptr instruction
11106 // is a getelementptr instruction, combine the indices of the two
11107 // getelementptr instructions into a single instruction.
11108 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011109 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011110 // Note that if our source is a gep chain itself that we wait for that
11111 // chain to be resolved before we perform this transformation. This
11112 // avoids us creating a TON of code in some cases.
11113 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011114 if (GetElementPtrInst *SrcGEP =
11115 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11116 if (SrcGEP->getNumOperands() == 2)
11117 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011118
Chris Lattner72588fc2007-02-15 22:48:32 +000011119 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011120
11121 // Find out whether the last index in the source GEP is a sequential idx.
11122 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011123 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11124 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011125 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011126
Chris Lattner90ac28c2002-08-02 19:29:35 +000011127 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011128 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011129 // Replace: gep (gep %P, long B), long A, ...
11130 // With: T = long A+B; gep %P, T, ...
11131 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011132 Value *Sum;
11133 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11134 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011135 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011136 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011137 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011138 Sum = SO1;
11139 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011140 // If they aren't the same type, then the input hasn't been processed
11141 // by the loop above yet (which canonicalizes sequential index types to
11142 // intptr_t). Just avoid transforming this until the input has been
11143 // normalized.
11144 if (SO1->getType() != GO1->getType())
11145 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011146 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000011147 }
Chris Lattner620ce142004-05-07 22:09:22 +000011148
Chris Lattnerab984842009-08-30 05:30:55 +000011149 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011150 if (Src->getNumOperands() == 2) {
11151 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011152 GEP.setOperand(1, Sum);
11153 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011154 }
Chris Lattnerab984842009-08-30 05:30:55 +000011155 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011156 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011157 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011158 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011159 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011160 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011161 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011162 Indices.append(Src->op_begin()+1, Src->op_end());
11163 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011164 }
11165
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011166 if (!Indices.empty())
11167 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11168 Src->isInBounds()) ?
11169 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11170 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011171 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011172 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011173 }
11174
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011175 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11176 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011177 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011178
Chris Lattner2de23192009-08-30 20:38:21 +000011179 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11180 // want to change the gep until the bitcasts are eliminated.
11181 if (getBitCastOperand(X)) {
11182 Worklist.AddValue(PtrOp);
11183 return 0;
11184 }
11185
Chris Lattner963f4ba2009-08-30 20:36:46 +000011186 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11187 // into : GEP [10 x i8]* X, i32 0, ...
11188 //
11189 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11190 // into : GEP i8* X, ...
11191 //
11192 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011193 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011194 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11195 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011196 if (const ArrayType *CATy =
11197 dyn_cast<ArrayType>(CPTy->getElementType())) {
11198 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11199 if (CATy->getElementType() == XTy->getElementType()) {
11200 // -> GEP i8* X, ...
11201 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011202 return cast<GEPOperator>(&GEP)->isInBounds() ?
11203 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11204 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011205 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11206 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011207 }
11208
11209 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011210 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011211 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011212 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011213 // At this point, we know that the cast source type is a pointer
11214 // to an array of the same type as the destination pointer
11215 // array. Because the array type is never stepped over (there
11216 // is a leading zero) we can fold the cast into this GEP.
11217 GEP.setOperand(0, X);
11218 return &GEP;
11219 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011220 }
11221 }
Chris Lattnereed48272005-09-13 00:40:14 +000011222 } else if (GEP.getNumOperands() == 2) {
11223 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011224 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11225 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011226 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11227 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011228 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011229 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11230 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011231 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011232 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011233 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011234 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11235 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011236 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011237 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011238 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011239 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011240
11241 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011242 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011243 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011244 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011245
Owen Anderson1d0be152009-08-13 21:58:54 +000011246 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011247 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011248 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011249
11250 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11251 // allow either a mul, shift, or constant here.
11252 Value *NewIdx = 0;
11253 ConstantInt *Scale = 0;
11254 if (ArrayEltSize == 1) {
11255 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011256 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011257 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011258 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011259 Scale = CI;
11260 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11261 if (Inst->getOpcode() == Instruction::Shl &&
11262 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011263 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11264 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011265 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011266 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011267 NewIdx = Inst->getOperand(0);
11268 } else if (Inst->getOpcode() == Instruction::Mul &&
11269 isa<ConstantInt>(Inst->getOperand(1))) {
11270 Scale = cast<ConstantInt>(Inst->getOperand(1));
11271 NewIdx = Inst->getOperand(0);
11272 }
11273 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011274
Chris Lattner7835cdd2005-09-13 18:36:04 +000011275 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011276 // out, perform the transformation. Note, we don't know whether Scale is
11277 // signed or not. We'll use unsigned version of division/modulo
11278 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011279 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011280 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011281 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011282 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011283 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011284 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11285 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011286 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011287 }
11288
11289 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011290 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011291 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011292 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011293 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11294 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11295 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011296 // The NewGEP must be pointer typed, so must the old one -> BitCast
11297 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011298 }
11299 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011300 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011301 }
Chris Lattner58407792009-01-09 04:53:57 +000011302
Chris Lattner46cd5a12009-01-09 05:44:56 +000011303 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011304 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011305 /// Y = gep X, <...constant indices...>
11306 /// into a gep of the original struct. This is important for SROA and alias
11307 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011308 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011309 if (TD &&
11310 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011311 // Determine how much the GEP moves the pointer. We are guaranteed to get
11312 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011313 ConstantInt *OffsetV =
11314 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011315 int64_t Offset = OffsetV->getSExtValue();
11316
11317 // If this GEP instruction doesn't move the pointer, just replace the GEP
11318 // with a bitcast of the real input to the dest type.
11319 if (Offset == 0) {
11320 // If the bitcast is of an allocation, and the allocation will be
11321 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000011322 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000011323 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011324 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11325 if (Instruction *I = visitBitCast(*BCI)) {
11326 if (I != BCI) {
11327 I->takeName(BCI);
11328 BCI->getParent()->getInstList().insert(BCI, I);
11329 ReplaceInstUsesWith(*BCI, I);
11330 }
11331 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011332 }
Chris Lattner58407792009-01-09 04:53:57 +000011333 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011334 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011335 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011336
11337 // Otherwise, if the offset is non-zero, we need to find out if there is a
11338 // field at Offset in 'A's type. If so, we can pull the cast through the
11339 // GEP.
11340 SmallVector<Value*, 8> NewIndices;
11341 const Type *InTy =
11342 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011343 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011344 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11345 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11346 NewIndices.end()) :
11347 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11348 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011349
11350 if (NGEP->getType() == GEP.getType())
11351 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011352 NGEP->takeName(&GEP);
11353 return new BitCastInst(NGEP, GEP.getType());
11354 }
Chris Lattner58407792009-01-09 04:53:57 +000011355 }
11356 }
11357
Chris Lattner8a2a3112001-12-14 16:52:21 +000011358 return 0;
11359}
11360
Victor Hernandez7b929da2009-10-23 21:09:37 +000011361Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000011362 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011363 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011364 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11365 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011366 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000011367 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000011368 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011369 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011370
Chris Lattner0864acf2002-11-04 16:18:53 +000011371 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011372 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011373 //
11374 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000011375 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011376
11377 // Now that I is pointing to the first non-allocation-inst in the block,
11378 // insert our getelementptr instruction...
11379 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011380 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011381 Value *Idx[2];
11382 Idx[0] = NullIdx;
11383 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011384 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11385 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011386
11387 // Now make everything use the getelementptr instead of the original
11388 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011389 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011390 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011391 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011392 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011393 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011394
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011395 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011396 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011397 // Note that we only do this for alloca's, because malloc should allocate
11398 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011399 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011400 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011401
11402 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11403 if (AI.getAlignment() == 0)
11404 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11405 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011406
Chris Lattner0864acf2002-11-04 16:18:53 +000011407 return 0;
11408}
11409
Victor Hernandez66284e02009-10-24 04:23:03 +000011410Instruction *InstCombiner::visitFree(Instruction &FI) {
11411 Value *Op = FI.getOperand(1);
11412
11413 // free undef -> unreachable.
11414 if (isa<UndefValue>(Op)) {
11415 // Insert a new store to null because we cannot modify the CFG here.
11416 new StoreInst(ConstantInt::getTrue(*Context),
11417 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11418 return EraseInstFromFunction(FI);
11419 }
11420
11421 // If we have 'free null' delete the instruction. This can happen in stl code
11422 // when lots of inlining happens.
11423 if (isa<ConstantPointerNull>(Op))
11424 return EraseInstFromFunction(FI);
11425
Victor Hernandez046e78c2009-10-26 23:43:48 +000011426 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000011427 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000011428 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11429 if (Op->hasOneUse() && CI->hasOneUse()) {
11430 EraseInstFromFunction(FI);
11431 EraseInstFromFunction(*CI);
11432 return EraseInstFromFunction(*cast<Instruction>(Op));
11433 }
11434 } else {
11435 // Op is a call to malloc
11436 if (Op->hasOneUse()) {
11437 EraseInstFromFunction(FI);
11438 return EraseInstFromFunction(*cast<Instruction>(Op));
11439 }
11440 }
Dan Gohman7f712a12009-10-27 00:11:02 +000011441 }
Victor Hernandez66284e02009-10-24 04:23:03 +000011442
11443 return 0;
11444}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011445
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011446/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011447static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011448 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011449 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011450 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011451 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011452
Mon P Wang6753f952009-02-07 22:19:29 +000011453 const PointerType *DestTy = cast<PointerType>(CI->getType());
11454 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011455 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011456
11457 // If the address spaces don't match, don't eliminate the cast.
11458 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11459 return 0;
11460
Chris Lattnerb89e0712004-07-13 01:49:43 +000011461 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011462
Reid Spencer42230162007-01-22 05:51:25 +000011463 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011464 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011465 // If the source is an array, the code below will not succeed. Check to
11466 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11467 // constants.
11468 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11469 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11470 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011471 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000011472 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11473 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000011474 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011475 SrcTy = cast<PointerType>(CastOp->getType());
11476 SrcPTy = SrcTy->getElementType();
11477 }
11478
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011479 if (IC.getTargetData() &&
11480 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011481 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011482 // Do not allow turning this into a load of an integer, which is then
11483 // casted to a pointer, this pessimizes pointer analysis a lot.
11484 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011485 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11486 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011487
Chris Lattnerf9527852005-01-31 04:50:46 +000011488 // Okay, we are casting from one integer or pointer type to another of
11489 // the same size. Instead of casting the pointer before the load, cast
11490 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011491 Value *NewLoad =
11492 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011493 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011494 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011495 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011496 }
11497 }
11498 return 0;
11499}
11500
Chris Lattner833b8a42003-06-26 05:06:25 +000011501Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11502 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011503
Dan Gohman9941f742007-07-20 16:34:21 +000011504 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011505 if (TD) {
11506 unsigned KnownAlign =
11507 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11508 if (KnownAlign >
11509 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11510 LI.getAlignment()))
11511 LI.setAlignment(KnownAlign);
11512 }
Dan Gohman9941f742007-07-20 16:34:21 +000011513
Chris Lattner963f4ba2009-08-30 20:36:46 +000011514 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011515 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011516 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011517 return Res;
11518
11519 // None of the following transforms are legal for volatile loads.
11520 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011521
Dan Gohman2276a7b2008-10-15 23:19:35 +000011522 // Do really simple store-to-load forwarding and load CSE, to catch cases
11523 // where there are several consequtive memory accesses to the same location,
11524 // separated by a few arithmetic operations.
11525 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011526 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11527 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011528
Chris Lattner878e4942009-10-22 06:25:11 +000011529 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000011530 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11531 const Value *GEPI0 = GEPI->getOperand(0);
11532 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011533 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011534 // Insert a new store to null instruction before the load to indicate
11535 // that this code is not reachable. We do this instead of inserting
11536 // an unreachable instruction directly because we cannot modify the
11537 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011538 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011539 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011540 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011541 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011542 }
Chris Lattner37366c12005-05-01 04:24:53 +000011543
Chris Lattner878e4942009-10-22 06:25:11 +000011544 // load null/undef -> unreachable
11545 // TODO: Consider a target hook for valid address spaces for this xform.
11546 if (isa<UndefValue>(Op) ||
11547 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11548 // Insert a new store to null instruction before the load to indicate that
11549 // this code is not reachable. We do this instead of inserting an
11550 // unreachable instruction directly because we cannot modify the CFG.
11551 new StoreInst(UndefValue::get(LI.getType()),
11552 Constant::getNullValue(Op->getType()), &LI);
11553 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011554 }
Chris Lattner878e4942009-10-22 06:25:11 +000011555
11556 // Instcombine load (constantexpr_cast global) -> cast (load global)
11557 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11558 if (CE->isCast())
11559 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11560 return Res;
11561
Chris Lattner37366c12005-05-01 04:24:53 +000011562 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011563 // Change select and PHI nodes to select values instead of addresses: this
11564 // helps alias analysis out a lot, allows many others simplifications, and
11565 // exposes redundancy in the code.
11566 //
11567 // Note that we cannot do the transformation unless we know that the
11568 // introduced loads cannot trap! Something like this is valid as long as
11569 // the condition is always false: load (select bool %C, int* null, int* %G),
11570 // but it would not be valid if we transformed it to load from null
11571 // unconditionally.
11572 //
11573 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11574 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011575 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11576 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011577 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11578 SI->getOperand(1)->getName()+".val");
11579 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11580 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011581 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011582 }
11583
Chris Lattner684fe212004-09-23 15:46:00 +000011584 // load (select (cond, null, P)) -> load P
11585 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11586 if (C->isNullValue()) {
11587 LI.setOperand(0, SI->getOperand(2));
11588 return &LI;
11589 }
11590
11591 // load (select (cond, P, null)) -> load P
11592 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11593 if (C->isNullValue()) {
11594 LI.setOperand(0, SI->getOperand(1));
11595 return &LI;
11596 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011597 }
11598 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011599 return 0;
11600}
11601
Reid Spencer55af2b52007-01-19 21:20:31 +000011602/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011603/// when possible. This makes it generally easy to do alias analysis and/or
11604/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011605static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11606 User *CI = cast<User>(SI.getOperand(1));
11607 Value *CastOp = CI->getOperand(0);
11608
11609 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011610 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11611 if (SrcTy == 0) return 0;
11612
11613 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011614
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011615 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11616 return 0;
11617
Chris Lattner3914f722009-01-24 01:00:13 +000011618 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11619 /// to its first element. This allows us to handle things like:
11620 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11621 /// on 32-bit hosts.
11622 SmallVector<Value*, 4> NewGEPIndices;
11623
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011624 // If the source is an array, the code below will not succeed. Check to
11625 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11626 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011627 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11628 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011629 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011630 NewGEPIndices.push_back(Zero);
11631
11632 while (1) {
11633 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011634 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011635 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011636 NewGEPIndices.push_back(Zero);
11637 SrcPTy = STy->getElementType(0);
11638 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11639 NewGEPIndices.push_back(Zero);
11640 SrcPTy = ATy->getElementType();
11641 } else {
11642 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011643 }
Chris Lattner3914f722009-01-24 01:00:13 +000011644 }
11645
Owen Andersondebcb012009-07-29 22:17:13 +000011646 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011647 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011648
11649 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11650 return 0;
11651
Chris Lattner71759c42009-01-16 20:12:52 +000011652 // If the pointers point into different address spaces or if they point to
11653 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011654 if (!IC.getTargetData() ||
11655 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011656 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011657 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11658 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011659 return 0;
11660
11661 // Okay, we are casting from one integer or pointer type to another of
11662 // the same size. Instead of casting the pointer before
11663 // the store, cast the value to be stored.
11664 Value *NewCast;
11665 Value *SIOp0 = SI.getOperand(0);
11666 Instruction::CastOps opcode = Instruction::BitCast;
11667 const Type* CastSrcTy = SIOp0->getType();
11668 const Type* CastDstTy = SrcPTy;
11669 if (isa<PointerType>(CastDstTy)) {
11670 if (CastSrcTy->isInteger())
11671 opcode = Instruction::IntToPtr;
11672 } else if (isa<IntegerType>(CastDstTy)) {
11673 if (isa<PointerType>(SIOp0->getType()))
11674 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011675 }
Chris Lattner3914f722009-01-24 01:00:13 +000011676
11677 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11678 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011679 if (!NewGEPIndices.empty())
11680 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11681 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011682
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011683 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11684 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011685 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011686}
11687
Chris Lattner4aebaee2008-11-27 08:56:30 +000011688/// equivalentAddressValues - Test if A and B will obviously have the same
11689/// value. This includes recognizing that %t0 and %t1 will have the same
11690/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011691/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011692/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011693/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011694/// %t2 = load i32* %t1
11695///
11696static bool equivalentAddressValues(Value *A, Value *B) {
11697 // Test if the values are trivially equivalent.
11698 if (A == B) return true;
11699
11700 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011701 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11702 // its only used to compare two uses within the same basic block, which
11703 // means that they'll always either have the same value or one of them
11704 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011705 if (isa<BinaryOperator>(A) ||
11706 isa<CastInst>(A) ||
11707 isa<PHINode>(A) ||
11708 isa<GetElementPtrInst>(A))
11709 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011710 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011711 return true;
11712
11713 // Otherwise they may not be equivalent.
11714 return false;
11715}
11716
Dale Johannesen4945c652009-03-03 21:26:39 +000011717// If this instruction has two uses, one of which is a llvm.dbg.declare,
11718// return the llvm.dbg.declare.
11719DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11720 if (!V->hasNUses(2))
11721 return 0;
11722 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11723 UI != E; ++UI) {
11724 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11725 return DI;
11726 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11727 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11728 return DI;
11729 }
11730 }
11731 return 0;
11732}
11733
Chris Lattner2f503e62005-01-31 05:36:43 +000011734Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11735 Value *Val = SI.getOperand(0);
11736 Value *Ptr = SI.getOperand(1);
11737
11738 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011739 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011740 ++NumCombined;
11741 return 0;
11742 }
Chris Lattner836692d2007-01-15 06:51:56 +000011743
11744 // If the RHS is an alloca with a single use, zapify the store, making the
11745 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011746 // If the RHS is an alloca with a two uses, the other one being a
11747 // llvm.dbg.declare, zapify the store and the declare, making the
11748 // alloca dead. We must do this to prevent declare's from affecting
11749 // codegen.
11750 if (!SI.isVolatile()) {
11751 if (Ptr->hasOneUse()) {
11752 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011753 EraseInstFromFunction(SI);
11754 ++NumCombined;
11755 return 0;
11756 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011757 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11758 if (isa<AllocaInst>(GEP->getOperand(0))) {
11759 if (GEP->getOperand(0)->hasOneUse()) {
11760 EraseInstFromFunction(SI);
11761 ++NumCombined;
11762 return 0;
11763 }
11764 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11765 EraseInstFromFunction(*DI);
11766 EraseInstFromFunction(SI);
11767 ++NumCombined;
11768 return 0;
11769 }
11770 }
11771 }
11772 }
11773 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11774 EraseInstFromFunction(*DI);
11775 EraseInstFromFunction(SI);
11776 ++NumCombined;
11777 return 0;
11778 }
Chris Lattner836692d2007-01-15 06:51:56 +000011779 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011780
Dan Gohman9941f742007-07-20 16:34:21 +000011781 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011782 if (TD) {
11783 unsigned KnownAlign =
11784 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11785 if (KnownAlign >
11786 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11787 SI.getAlignment()))
11788 SI.setAlignment(KnownAlign);
11789 }
Dan Gohman9941f742007-07-20 16:34:21 +000011790
Dale Johannesenacb51a32009-03-03 01:43:03 +000011791 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011792 // stores to the same location, separated by a few arithmetic operations. This
11793 // situation often occurs with bitfield accesses.
11794 BasicBlock::iterator BBI = &SI;
11795 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11796 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011797 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011798 // Don't count debug info directives, lest they affect codegen,
11799 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11800 // It is necessary for correctness to skip those that feed into a
11801 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011802 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011803 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011804 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011805 continue;
11806 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011807
11808 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11809 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011810 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11811 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011812 ++NumDeadStore;
11813 ++BBI;
11814 EraseInstFromFunction(*PrevSI);
11815 continue;
11816 }
11817 break;
11818 }
11819
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011820 // If this is a load, we have to stop. However, if the loaded value is from
11821 // the pointer we're loading and is producing the pointer we're storing,
11822 // then *this* store is dead (X = load P; store X -> P).
11823 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011824 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11825 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011826 EraseInstFromFunction(SI);
11827 ++NumCombined;
11828 return 0;
11829 }
11830 // Otherwise, this is a load from some other location. Stores before it
11831 // may not be dead.
11832 break;
11833 }
11834
Chris Lattner9ca96412006-02-08 03:25:32 +000011835 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011836 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011837 break;
11838 }
11839
11840
11841 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011842
11843 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011844 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011845 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011846 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011847 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011848 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011849 ++NumCombined;
11850 }
11851 return 0; // Do not modify these!
11852 }
11853
11854 // store undef, Ptr -> noop
11855 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011856 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011857 ++NumCombined;
11858 return 0;
11859 }
11860
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011861 // If the pointer destination is a cast, see if we can fold the cast into the
11862 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011863 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011864 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11865 return Res;
11866 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011867 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011868 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11869 return Res;
11870
Chris Lattner408902b2005-09-12 23:23:25 +000011871
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011872 // If this store is the last instruction in the basic block (possibly
11873 // excepting debug info instructions and the pointer bitcasts that feed
11874 // into them), and if the block ends with an unconditional branch, try
11875 // to move it to the successor block.
11876 BBI = &SI;
11877 do {
11878 ++BBI;
11879 } while (isa<DbgInfoIntrinsic>(BBI) ||
11880 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011881 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011882 if (BI->isUnconditional())
11883 if (SimplifyStoreAtEndOfBlock(SI))
11884 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011885
Chris Lattner2f503e62005-01-31 05:36:43 +000011886 return 0;
11887}
11888
Chris Lattner3284d1f2007-04-15 00:07:55 +000011889/// SimplifyStoreAtEndOfBlock - Turn things like:
11890/// if () { *P = v1; } else { *P = v2 }
11891/// into a phi node with a store in the successor.
11892///
Chris Lattner31755a02007-04-15 01:02:18 +000011893/// Simplify things like:
11894/// *P = v1; if () { *P = v2; }
11895/// into a phi node with a store in the successor.
11896///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011897bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11898 BasicBlock *StoreBB = SI.getParent();
11899
11900 // Check to see if the successor block has exactly two incoming edges. If
11901 // so, see if the other predecessor contains a store to the same location.
11902 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011903 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011904
11905 // Determine whether Dest has exactly two predecessors and, if so, compute
11906 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011907 pred_iterator PI = pred_begin(DestBB);
11908 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011909 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011910 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011911 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011912 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011913 return false;
11914
11915 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011916 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011917 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011918 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011919 }
Chris Lattner31755a02007-04-15 01:02:18 +000011920 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011921 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011922
11923 // Bail out if all the relevant blocks aren't distinct (this can happen,
11924 // for example, if SI is in an infinite loop)
11925 if (StoreBB == DestBB || OtherBB == DestBB)
11926 return false;
11927
Chris Lattner31755a02007-04-15 01:02:18 +000011928 // Verify that the other block ends in a branch and is not otherwise empty.
11929 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011930 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011931 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011932 return false;
11933
Chris Lattner31755a02007-04-15 01:02:18 +000011934 // If the other block ends in an unconditional branch, check for the 'if then
11935 // else' case. there is an instruction before the branch.
11936 StoreInst *OtherStore = 0;
11937 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011938 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011939 // Skip over debugging info.
11940 while (isa<DbgInfoIntrinsic>(BBI) ||
11941 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11942 if (BBI==OtherBB->begin())
11943 return false;
11944 --BBI;
11945 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000011946 // If this isn't a store, isn't a store to the same location, or if the
11947 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011948 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000011949 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
11950 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000011951 return false;
11952 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011953 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011954 // destinations is StoreBB, then we have the if/then case.
11955 if (OtherBr->getSuccessor(0) != StoreBB &&
11956 OtherBr->getSuccessor(1) != StoreBB)
11957 return false;
11958
11959 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011960 // if/then triangle. See if there is a store to the same ptr as SI that
11961 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011962 for (;; --BBI) {
11963 // Check to see if we find the matching store.
11964 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000011965 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
11966 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000011967 return false;
11968 break;
11969 }
Eli Friedman6903a242008-06-13 22:02:12 +000011970 // If we find something that may be using or overwriting the stored
11971 // value, or if we run out of instructions, we can't do the xform.
11972 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011973 BBI == OtherBB->begin())
11974 return false;
11975 }
11976
11977 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011978 // make sure nothing reads or overwrites the stored value in
11979 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011980 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11981 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011982 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011983 return false;
11984 }
11985 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011986
Chris Lattner31755a02007-04-15 01:02:18 +000011987 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011988 Value *MergedVal = OtherStore->getOperand(0);
11989 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011990 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011991 PN->reserveOperandSpace(2);
11992 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011993 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11994 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011995 }
11996
11997 // Advance to a place where it is safe to insert the new store and
11998 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011999 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012000 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012001 OtherStore->isVolatile(),
12002 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012003
12004 // Nuke the old stores.
12005 EraseInstFromFunction(SI);
12006 EraseInstFromFunction(*OtherStore);
12007 ++NumCombined;
12008 return true;
12009}
12010
Chris Lattner2f503e62005-01-31 05:36:43 +000012011
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012012Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12013 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012014 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012015 BasicBlock *TrueDest;
12016 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012017 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012018 !isa<Constant>(X)) {
12019 // Swap Destinations and condition...
12020 BI.setCondition(X);
12021 BI.setSuccessor(0, FalseDest);
12022 BI.setSuccessor(1, TrueDest);
12023 return &BI;
12024 }
12025
Reid Spencere4d87aa2006-12-23 06:05:41 +000012026 // Cannonicalize fcmp_one -> fcmp_oeq
12027 FCmpInst::Predicate FPred; Value *Y;
12028 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012029 TrueDest, FalseDest)) &&
12030 BI.getCondition()->hasOneUse())
12031 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12032 FPred == FCmpInst::FCMP_OGE) {
12033 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12034 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12035
12036 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012037 BI.setSuccessor(0, FalseDest);
12038 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012039 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012040 return &BI;
12041 }
12042
12043 // Cannonicalize icmp_ne -> icmp_eq
12044 ICmpInst::Predicate IPred;
12045 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012046 TrueDest, FalseDest)) &&
12047 BI.getCondition()->hasOneUse())
12048 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12049 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12050 IPred == ICmpInst::ICMP_SGE) {
12051 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12052 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12053 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012054 BI.setSuccessor(0, FalseDest);
12055 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012056 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012057 return &BI;
12058 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012059
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012060 return 0;
12061}
Chris Lattner0864acf2002-11-04 16:18:53 +000012062
Chris Lattner46238a62004-07-03 00:26:11 +000012063Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12064 Value *Cond = SI.getCondition();
12065 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12066 if (I->getOpcode() == Instruction::Add)
12067 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12068 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12069 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012070 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012071 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012072 AddRHS));
12073 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012074 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012075 return &SI;
12076 }
12077 }
12078 return 0;
12079}
12080
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012081Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012082 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012083
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012084 if (!EV.hasIndices())
12085 return ReplaceInstUsesWith(EV, Agg);
12086
12087 if (Constant *C = dyn_cast<Constant>(Agg)) {
12088 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012089 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012090
12091 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012092 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012093
12094 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12095 // Extract the element indexed by the first index out of the constant
12096 Value *V = C->getOperand(*EV.idx_begin());
12097 if (EV.getNumIndices() > 1)
12098 // Extract the remaining indices out of the constant indexed by the
12099 // first index
12100 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12101 else
12102 return ReplaceInstUsesWith(EV, V);
12103 }
12104 return 0; // Can't handle other constants
12105 }
12106 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12107 // We're extracting from an insertvalue instruction, compare the indices
12108 const unsigned *exti, *exte, *insi, *inse;
12109 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12110 exte = EV.idx_end(), inse = IV->idx_end();
12111 exti != exte && insi != inse;
12112 ++exti, ++insi) {
12113 if (*insi != *exti)
12114 // The insert and extract both reference distinctly different elements.
12115 // This means the extract is not influenced by the insert, and we can
12116 // replace the aggregate operand of the extract with the aggregate
12117 // operand of the insert. i.e., replace
12118 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12119 // %E = extractvalue { i32, { i32 } } %I, 0
12120 // with
12121 // %E = extractvalue { i32, { i32 } } %A, 0
12122 return ExtractValueInst::Create(IV->getAggregateOperand(),
12123 EV.idx_begin(), EV.idx_end());
12124 }
12125 if (exti == exte && insi == inse)
12126 // Both iterators are at the end: Index lists are identical. Replace
12127 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12128 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12129 // with "i32 42"
12130 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12131 if (exti == exte) {
12132 // The extract list is a prefix of the insert list. i.e. replace
12133 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12134 // %E = extractvalue { i32, { i32 } } %I, 1
12135 // with
12136 // %X = extractvalue { i32, { i32 } } %A, 1
12137 // %E = insertvalue { i32 } %X, i32 42, 0
12138 // by switching the order of the insert and extract (though the
12139 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012140 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12141 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012142 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12143 insi, inse);
12144 }
12145 if (insi == inse)
12146 // The insert list is a prefix of the extract list
12147 // We can simply remove the common indices from the extract and make it
12148 // operate on the inserted value instead of the insertvalue result.
12149 // i.e., replace
12150 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12151 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12152 // with
12153 // %E extractvalue { i32 } { i32 42 }, 0
12154 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12155 exti, exte);
12156 }
12157 // Can't simplify extracts from other values. Note that nested extracts are
12158 // already simplified implicitely by the above (extract ( extract (insert) )
12159 // will be translated into extract ( insert ( extract ) ) first and then just
12160 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012161 return 0;
12162}
12163
Chris Lattner220b0cf2006-03-05 00:22:33 +000012164/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12165/// is to leave as a vector operation.
12166static bool CheapToScalarize(Value *V, bool isConstant) {
12167 if (isa<ConstantAggregateZero>(V))
12168 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012169 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012170 if (isConstant) return true;
12171 // If all elts are the same, we can extract.
12172 Constant *Op0 = C->getOperand(0);
12173 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12174 if (C->getOperand(i) != Op0)
12175 return false;
12176 return true;
12177 }
12178 Instruction *I = dyn_cast<Instruction>(V);
12179 if (!I) return false;
12180
12181 // Insert element gets simplified to the inserted element or is deleted if
12182 // this is constant idx extract element and its a constant idx insertelt.
12183 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12184 isa<ConstantInt>(I->getOperand(2)))
12185 return true;
12186 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12187 return true;
12188 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12189 if (BO->hasOneUse() &&
12190 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12191 CheapToScalarize(BO->getOperand(1), isConstant)))
12192 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012193 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12194 if (CI->hasOneUse() &&
12195 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12196 CheapToScalarize(CI->getOperand(1), isConstant)))
12197 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012198
12199 return false;
12200}
12201
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012202/// Read and decode a shufflevector mask.
12203///
12204/// It turns undef elements into values that are larger than the number of
12205/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012206static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12207 unsigned NElts = SVI->getType()->getNumElements();
12208 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12209 return std::vector<unsigned>(NElts, 0);
12210 if (isa<UndefValue>(SVI->getOperand(2)))
12211 return std::vector<unsigned>(NElts, 2*NElts);
12212
12213 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012214 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012215 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12216 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012217 Result.push_back(NElts*2); // undef -> 8
12218 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012219 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012220 return Result;
12221}
12222
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012223/// FindScalarElement - Given a vector and an element number, see if the scalar
12224/// value is already around as a register, for example if it were inserted then
12225/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012226static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012227 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012228 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12229 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012230 unsigned Width = PTy->getNumElements();
12231 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012232 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012233
12234 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012235 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012236 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012237 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012238 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012239 return CP->getOperand(EltNo);
12240 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12241 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012242 if (!isa<ConstantInt>(III->getOperand(2)))
12243 return 0;
12244 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012245
12246 // If this is an insert to the element we are looking for, return the
12247 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012248 if (EltNo == IIElt)
12249 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012250
12251 // Otherwise, the insertelement doesn't modify the value, recurse on its
12252 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012253 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012254 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012255 unsigned LHSWidth =
12256 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012257 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012258 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012259 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012260 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012261 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012262 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012263 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012264 }
12265
12266 // Otherwise, we don't know.
12267 return 0;
12268}
12269
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012270Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012271 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012272 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012273 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012274
Dan Gohman07a96762007-07-16 14:29:03 +000012275 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012276 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012277 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012278
Reid Spencer9d6565a2007-02-15 02:26:10 +000012279 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012280 // If vector val is constant with all elements the same, replace EI with
12281 // that element. When the elements are not identical, we cannot replace yet
12282 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012283 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012284 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012285 if (C->getOperand(i) != op0) {
12286 op0 = 0;
12287 break;
12288 }
12289 if (op0)
12290 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012291 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012292
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012293 // If extracting a specified index from the vector, see if we can recursively
12294 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012295 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012296 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012297 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012298
12299 // If this is extracting an invalid index, turn this into undef, to avoid
12300 // crashing the code below.
12301 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012302 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012303
Chris Lattner867b99f2006-10-05 06:55:50 +000012304 // This instruction only demands the single element from the input vector.
12305 // If the input vector has a single use, simplify it based on this use
12306 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012307 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012308 APInt UndefElts(VectorWidth, 0);
12309 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012310 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012311 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012312 EI.setOperand(0, V);
12313 return &EI;
12314 }
12315 }
12316
Owen Andersond672ecb2009-07-03 00:17:18 +000012317 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012318 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012319
12320 // If the this extractelement is directly using a bitcast from a vector of
12321 // the same number of elements, see if we can find the source element from
12322 // it. In this case, we will end up needing to bitcast the scalars.
12323 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12324 if (const VectorType *VT =
12325 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12326 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012327 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12328 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012329 return new BitCastInst(Elt, EI.getType());
12330 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012331 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012332
Chris Lattner73fa49d2006-05-25 22:53:38 +000012333 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012334 // Push extractelement into predecessor operation if legal and
12335 // profitable to do so
12336 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12337 if (I->hasOneUse() &&
12338 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12339 Value *newEI0 =
12340 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12341 EI.getName()+".lhs");
12342 Value *newEI1 =
12343 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12344 EI.getName()+".rhs");
12345 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012346 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012347 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012348 // Extracting the inserted element?
12349 if (IE->getOperand(2) == EI.getOperand(1))
12350 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12351 // If the inserted and extracted elements are constants, they must not
12352 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012353 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012354 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012355 EI.setOperand(0, IE->getOperand(0));
12356 return &EI;
12357 }
12358 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12359 // If this is extracting an element from a shufflevector, figure out where
12360 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012361 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12362 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012363 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012364 unsigned LHSWidth =
12365 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12366
12367 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012368 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012369 else if (SrcIdx < LHSWidth*2) {
12370 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012371 Src = SVI->getOperand(1);
12372 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012373 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012374 }
Eric Christophera3500da2009-07-25 02:28:41 +000012375 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012376 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12377 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012378 }
12379 }
Eli Friedman2451a642009-07-18 23:06:53 +000012380 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012381 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012382 return 0;
12383}
12384
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012385/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12386/// elements from either LHS or RHS, return the shuffle mask and true.
12387/// Otherwise, return false.
12388static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012389 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012390 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012391 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12392 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012393 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012394
12395 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012396 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012397 return true;
12398 } else if (V == LHS) {
12399 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012400 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012401 return true;
12402 } else if (V == RHS) {
12403 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012404 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012405 return true;
12406 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12407 // If this is an insert of an extract from some other vector, include it.
12408 Value *VecOp = IEI->getOperand(0);
12409 Value *ScalarOp = IEI->getOperand(1);
12410 Value *IdxOp = IEI->getOperand(2);
12411
Chris Lattnerd929f062006-04-27 21:14:21 +000012412 if (!isa<ConstantInt>(IdxOp))
12413 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012414 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012415
12416 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12417 // Okay, we can handle this if the vector we are insertinting into is
12418 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012419 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012420 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012421 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012422 return true;
12423 }
12424 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12425 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012426 EI->getOperand(0)->getType() == V->getType()) {
12427 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012428 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012429
12430 // This must be extracting from either LHS or RHS.
12431 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12432 // Okay, we can handle this if the vector we are insertinting into is
12433 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012434 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012435 // If so, update the mask to reflect the inserted value.
12436 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012437 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012438 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012439 } else {
12440 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012441 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012442 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012443
12444 }
12445 return true;
12446 }
12447 }
12448 }
12449 }
12450 }
12451 // TODO: Handle shufflevector here!
12452
12453 return false;
12454}
12455
12456/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12457/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12458/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012459static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012460 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012461 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012462 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012463 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012464 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012465
12466 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012467 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012468 return V;
12469 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012470 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012471 return V;
12472 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12473 // If this is an insert of an extract from some other vector, include it.
12474 Value *VecOp = IEI->getOperand(0);
12475 Value *ScalarOp = IEI->getOperand(1);
12476 Value *IdxOp = IEI->getOperand(2);
12477
12478 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12479 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12480 EI->getOperand(0)->getType() == V->getType()) {
12481 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012482 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12483 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012484
12485 // Either the extracted from or inserted into vector must be RHSVec,
12486 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012487 if (EI->getOperand(0) == RHS || RHS == 0) {
12488 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012489 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012490 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012491 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012492 return V;
12493 }
12494
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012495 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012496 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12497 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012498 // Everything but the extracted element is replaced with the RHS.
12499 for (unsigned i = 0; i != NumElts; ++i) {
12500 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012501 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012502 }
12503 return V;
12504 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012505
12506 // If this insertelement is a chain that comes from exactly these two
12507 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012508 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12509 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012510 return EI->getOperand(0);
12511
Chris Lattnerefb47352006-04-15 01:39:45 +000012512 }
12513 }
12514 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012515 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012516
12517 // Otherwise, can't do anything fancy. Return an identity vector.
12518 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012519 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012520 return V;
12521}
12522
12523Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12524 Value *VecOp = IE.getOperand(0);
12525 Value *ScalarOp = IE.getOperand(1);
12526 Value *IdxOp = IE.getOperand(2);
12527
Chris Lattner599ded12007-04-09 01:11:16 +000012528 // Inserting an undef or into an undefined place, remove this.
12529 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12530 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012531
Chris Lattnerefb47352006-04-15 01:39:45 +000012532 // If the inserted element was extracted from some other vector, and if the
12533 // indexes are constant, try to turn this into a shufflevector operation.
12534 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12535 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12536 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012537 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012538 unsigned ExtractedIdx =
12539 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012540 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012541
12542 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12543 return ReplaceInstUsesWith(IE, VecOp);
12544
12545 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012546 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012547
12548 // If we are extracting a value from a vector, then inserting it right
12549 // back into the same place, just use the input vector.
12550 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12551 return ReplaceInstUsesWith(IE, VecOp);
12552
Chris Lattnerefb47352006-04-15 01:39:45 +000012553 // If this insertelement isn't used by some other insertelement, turn it
12554 // (and any insertelements it points to), into one big shuffle.
12555 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12556 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012557 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012558 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012559 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012560 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012561 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012562 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012563 }
12564 }
12565 }
12566
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012567 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12568 APInt UndefElts(VWidth, 0);
12569 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12570 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12571 return &IE;
12572
Chris Lattnerefb47352006-04-15 01:39:45 +000012573 return 0;
12574}
12575
12576
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012577Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12578 Value *LHS = SVI.getOperand(0);
12579 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012580 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012581
12582 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012583
Chris Lattner867b99f2006-10-05 06:55:50 +000012584 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012585 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012586 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012587
Dan Gohman488fbfc2008-09-09 18:11:14 +000012588 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012589
12590 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12591 return 0;
12592
Evan Cheng388df622009-02-03 10:05:09 +000012593 APInt UndefElts(VWidth, 0);
12594 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12595 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012596 LHS = SVI.getOperand(0);
12597 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012598 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012599 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012600
Chris Lattner863bcff2006-05-25 23:48:38 +000012601 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12602 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12603 if (LHS == RHS || isa<UndefValue>(LHS)) {
12604 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012605 // shuffle(undef,undef,mask) -> undef.
12606 return ReplaceInstUsesWith(SVI, LHS);
12607 }
12608
Chris Lattner863bcff2006-05-25 23:48:38 +000012609 // Remap any references to RHS to use LHS.
12610 std::vector<Constant*> Elts;
12611 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012612 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012613 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012614 else {
12615 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012616 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012617 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012618 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012619 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012620 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012621 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012622 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012623 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012624 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012625 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012626 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012627 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012628 LHS = SVI.getOperand(0);
12629 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012630 MadeChange = true;
12631 }
12632
Chris Lattner7b2e27922006-05-26 00:29:06 +000012633 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012634 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012635
Chris Lattner863bcff2006-05-25 23:48:38 +000012636 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12637 if (Mask[i] >= e*2) continue; // Ignore undef values.
12638 // Is this an identity shuffle of the LHS value?
12639 isLHSID &= (Mask[i] == i);
12640
12641 // Is this an identity shuffle of the RHS value?
12642 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012643 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012644
Chris Lattner863bcff2006-05-25 23:48:38 +000012645 // Eliminate identity shuffles.
12646 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12647 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012648
Chris Lattner7b2e27922006-05-26 00:29:06 +000012649 // If the LHS is a shufflevector itself, see if we can combine it with this
12650 // one without producing an unusual shuffle. Here we are really conservative:
12651 // we are absolutely afraid of producing a shuffle mask not in the input
12652 // program, because the code gen may not be smart enough to turn a merged
12653 // shuffle into two specific shuffles: it may produce worse code. As such,
12654 // we only merge two shuffles if the result is one of the two input shuffle
12655 // masks. In this case, merging the shuffles just removes one instruction,
12656 // which we know is safe. This is good for things like turning:
12657 // (splat(splat)) -> splat.
12658 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12659 if (isa<UndefValue>(RHS)) {
12660 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12661
12662 std::vector<unsigned> NewMask;
12663 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12664 if (Mask[i] >= 2*e)
12665 NewMask.push_back(2*e);
12666 else
12667 NewMask.push_back(LHSMask[Mask[i]]);
12668
12669 // If the result mask is equal to the src shuffle or this shuffle mask, do
12670 // the replacement.
12671 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012672 unsigned LHSInNElts =
12673 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012674 std::vector<Constant*> Elts;
12675 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012676 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012677 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012678 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012679 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012680 }
12681 }
12682 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12683 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012684 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012685 }
12686 }
12687 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012688
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012689 return MadeChange ? &SVI : 0;
12690}
12691
12692
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012693
Chris Lattnerea1c4542004-12-08 23:43:58 +000012694
12695/// TryToSinkInstruction - Try to move the specified instruction from its
12696/// current block into the beginning of DestBlock, which can only happen if it's
12697/// safe to move the instruction past all of the instructions between it and the
12698/// end of its block.
12699static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12700 assert(I->hasOneUse() && "Invariants didn't hold!");
12701
Chris Lattner108e9022005-10-27 17:13:11 +000012702 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012703 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012704 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012705
Chris Lattnerea1c4542004-12-08 23:43:58 +000012706 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012707 if (isa<AllocaInst>(I) && I->getParent() ==
12708 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012709 return false;
12710
Chris Lattner96a52a62004-12-09 07:14:34 +000012711 // We can only sink load instructions if there is nothing between the load and
12712 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012713 if (I->mayReadFromMemory()) {
12714 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012715 Scan != E; ++Scan)
12716 if (Scan->mayWriteToMemory())
12717 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012718 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012719
Dan Gohman02dea8b2008-05-23 21:05:58 +000012720 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012721
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012722 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012723 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012724 ++NumSunkInst;
12725 return true;
12726}
12727
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012728
12729/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12730/// all reachable code to the worklist.
12731///
12732/// This has a couple of tricks to make the code faster and more powerful. In
12733/// particular, we constant fold and DCE instructions as we go, to avoid adding
12734/// them to the worklist (this significantly speeds up instcombine on code where
12735/// many instructions are dead or constant). Additionally, if we find a branch
12736/// whose condition is a known constant, we only visit the reachable successors.
12737///
Chris Lattner2ee743b2009-10-15 04:59:28 +000012738static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012739 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012740 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012741 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000012742 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000012743 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012744 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000012745
12746 std::vector<Instruction*> InstrsForInstCombineWorklist;
12747 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012748
Chris Lattner2ee743b2009-10-15 04:59:28 +000012749 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12750
Chris Lattner2c7718a2007-03-23 19:17:18 +000012751 while (!Worklist.empty()) {
12752 BB = Worklist.back();
12753 Worklist.pop_back();
12754
12755 // We have now visited this block! If we've already been here, ignore it.
12756 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012757
Chris Lattner2c7718a2007-03-23 19:17:18 +000012758 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12759 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012760
Chris Lattner2c7718a2007-03-23 19:17:18 +000012761 // DCE instruction if trivially dead.
12762 if (isInstructionTriviallyDead(Inst)) {
12763 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012764 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012765 Inst->eraseFromParent();
12766 continue;
12767 }
12768
12769 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012770 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
12771 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12772 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12773 << *Inst << '\n');
12774 Inst->replaceAllUsesWith(C);
12775 ++NumConstProp;
12776 Inst->eraseFromParent();
12777 continue;
12778 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000012779
12780
12781
12782 if (TD) {
12783 // See if we can constant fold its operands.
12784 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12785 i != e; ++i) {
12786 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12787 if (CE == 0) continue;
12788
12789 // If we already folded this constant, don't try again.
12790 if (!FoldedConstants.insert(CE))
12791 continue;
12792
12793 Constant *NewC =
12794 ConstantFoldConstantExpression(CE, BB->getContext(), TD);
12795 if (NewC && NewC != CE) {
12796 *i = NewC;
12797 MadeIRChange = true;
12798 }
12799 }
12800 }
12801
Devang Patel7fe1dec2008-11-19 18:56:50 +000012802
Chris Lattner67f7d542009-10-12 03:58:40 +000012803 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012804 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012805
12806 // Recursively visit successors. If this is a branch or switch on a
12807 // constant, only visit the reachable successor.
12808 TerminatorInst *TI = BB->getTerminator();
12809 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12810 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12811 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012812 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012813 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012814 continue;
12815 }
12816 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12817 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12818 // See if this is an explicit destination.
12819 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12820 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012821 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012822 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012823 continue;
12824 }
12825
12826 // Otherwise it is the default destination.
12827 Worklist.push_back(SI->getSuccessor(0));
12828 continue;
12829 }
12830 }
12831
12832 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12833 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012834 }
Chris Lattner67f7d542009-10-12 03:58:40 +000012835
12836 // Once we've found all of the instructions to add to instcombine's worklist,
12837 // add them in reverse order. This way instcombine will visit from the top
12838 // of the function down. This jives well with the way that it adds all uses
12839 // of instructions to the worklist after doing a transformation, thus avoiding
12840 // some N^2 behavior in pathological cases.
12841 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12842 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000012843
12844 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012845}
12846
Chris Lattnerec9c3582007-03-03 02:04:50 +000012847bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012848 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012849
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012850 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12851 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012852
Chris Lattnerb3d59702005-07-07 20:40:38 +000012853 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012854 // Do a depth-first traversal of the function, populate the worklist with
12855 // the reachable instructions. Ignore blocks that are not reachable. Keep
12856 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012857 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000012858 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012859
Chris Lattnerb3d59702005-07-07 20:40:38 +000012860 // Do a quick scan over the function. If we find any blocks that are
12861 // unreachable, remove any instructions inside of them. This prevents
12862 // the instcombine code from having to deal with some bad special cases.
12863 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12864 if (!Visited.count(BB)) {
12865 Instruction *Term = BB->getTerminator();
12866 while (Term != BB->begin()) { // Remove instrs bottom-up
12867 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012868
Chris Lattnerbdff5482009-08-23 04:37:46 +000012869 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012870 // A debug intrinsic shouldn't force another iteration if we weren't
12871 // going to do one without it.
12872 if (!isa<DbgInfoIntrinsic>(I)) {
12873 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012874 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000012875 }
Devang Patel228ebd02009-10-13 22:56:32 +000012876
Devang Patel228ebd02009-10-13 22:56:32 +000012877 // If I is not void type then replaceAllUsesWith undef.
12878 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000012879 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000012880 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012881 I->eraseFromParent();
12882 }
12883 }
12884 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012885
Chris Lattner873ff012009-08-30 05:55:36 +000012886 while (!Worklist.isEmpty()) {
12887 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012888 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012889
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012890 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012891 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012892 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012893 EraseInstFromFunction(*I);
12894 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012895 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012896 continue;
12897 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012898
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012899 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012900 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
12901 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12902 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012903
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012904 // Add operands to the worklist.
12905 ReplaceInstUsesWith(*I, C);
12906 ++NumConstProp;
12907 EraseInstFromFunction(*I);
12908 MadeIRChange = true;
12909 continue;
12910 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012911
Chris Lattnerea1c4542004-12-08 23:43:58 +000012912 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012913 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012914 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000012915 Instruction *UserInst = cast<Instruction>(I->use_back());
12916 BasicBlock *UserParent;
12917
12918 // Get the block the use occurs in.
12919 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12920 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12921 else
12922 UserParent = UserInst->getParent();
12923
Chris Lattnerea1c4542004-12-08 23:43:58 +000012924 if (UserParent != BB) {
12925 bool UserIsSuccessor = false;
12926 // See if the user is one of our successors.
12927 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12928 if (*SI == UserParent) {
12929 UserIsSuccessor = true;
12930 break;
12931 }
12932
12933 // If the user is one of our immediate successors, and if that successor
12934 // only has us as a predecessors (we'd have to split the critical edge
12935 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000012936 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012937 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012938 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012939 }
12940 }
12941
Chris Lattner74381062009-08-30 07:44:24 +000012942 // Now that we have an instruction, try combining it to simplify it.
12943 Builder->SetInsertPoint(I->getParent(), I);
12944
Reid Spencera9b81012007-03-26 17:44:01 +000012945#ifndef NDEBUG
12946 std::string OrigI;
12947#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012948 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000012949 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12950
Chris Lattner90ac28c2002-08-02 19:29:35 +000012951 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012952 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012953 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012954 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012955 DEBUG(errs() << "IC: Old = " << *I << '\n'
12956 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012957
Chris Lattnerf523d062004-06-09 05:08:07 +000012958 // Everything uses the new instruction now.
12959 I->replaceAllUsesWith(Result);
12960
12961 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012962 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012963 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012964
Chris Lattner6934a042007-02-11 01:23:03 +000012965 // Move the name to the new instruction first.
12966 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012967
12968 // Insert the new instruction into the basic block...
12969 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012970 BasicBlock::iterator InsertPos = I;
12971
12972 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12973 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12974 ++InsertPos;
12975
12976 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012977
Chris Lattner7a1e9242009-08-30 06:13:40 +000012978 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012979 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012980#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012981 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12982 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012983#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012984
Chris Lattner90ac28c2002-08-02 19:29:35 +000012985 // If the instruction was modified, it's possible that it is now dead.
12986 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012987 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012988 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012989 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012990 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012991 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012992 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012993 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012994 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012995 }
12996 }
12997
Chris Lattner873ff012009-08-30 05:55:36 +000012998 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012999 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013000}
13001
Chris Lattnerec9c3582007-03-03 02:04:50 +000013002
13003bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013004 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013005 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013006 TD = getAnalysisIfAvailable<TargetData>();
13007
Chris Lattner74381062009-08-30 07:44:24 +000013008
13009 /// Builder - This is an IRBuilder that automatically inserts new
13010 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013011 IRBuilder<true, TargetFolder, InstCombineIRInserter>
13012 TheBuilder(F.getContext(), TargetFolder(TD, F.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +000013013 InstCombineIRInserter(Worklist));
13014 Builder = &TheBuilder;
13015
Chris Lattnerec9c3582007-03-03 02:04:50 +000013016 bool EverMadeChange = false;
13017
13018 // Iterate while there is work to do.
13019 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013020 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013021 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000013022
13023 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013024 return EverMadeChange;
13025}
13026
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013027FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013028 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013029}